View source
<?php
namespace Drupal\button_field\Plugin\Field\FieldWidget;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
abstract class ButtonFieldBase extends WidgetBase {
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$entity = $items
->getEntity();
$entity_id = $entity
->id();
$entity_type = $entity
->getEntityType();
$class = array(
'button_field',
);
$additional_classes = $this
->getFieldSetting('additional_classes');
if (!empty($additional_classes)) {
$class = array_merge($class, explode(' ', $additional_classes));
}
$suffix = NULL;
$description = $this->fieldDefinition
->getDescription();
if (!empty($description)) {
$suffix = '<div class="description">' . $description . '</div>';
}
$id = $this
->elementId($delta, $form_state
->getStorage()['langcode']);
$element = array(
'#id' => $id,
'#name' => $id,
'#attributes' => array(
'class' => $class,
),
'#description' => t('this is the help text'),
'#suffix' => $suffix,
'#entity_type' => $entity_type,
'#entity' => $entity,
'#field_name' => $this->fieldDefinition
->getName(),
'#attached' => array(
'drupalSettings' => array(
'button_field' => array(
$id => array(
'entity_type' => $entity_type,
'entity_id' => $entity_id,
'confirmation' => '',
),
),
),
),
'#ajax' => array(
'callback' => 'button_field_callback_ajax',
),
);
return $this
->elementProperties() + $element;
}
protected abstract function elementProperties();
protected function elementId($delta, $language) {
$parts = array(
'edit',
str_replace('_', '-', $this->fieldDefinition
->getName()),
$language,
$delta,
'value',
);
return implode('-', $parts);
}
}