View source
<?php
namespace Drupal\button_field\Plugin\Field\FieldFormatter;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterBase;
abstract class ButtonFieldBase extends FormatterBase {
public function viewElements(FieldItemListInterface $items, $langcode) {
$entity = $items
->getEntity();
$entity_type = $entity
->getEntityType()
->id();
$entity_id = $entity
->id();
$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(0, $items
->getLangcode());
$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' => $items
->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',
),
);
$element += $this
->elementProperties();
return \Drupal::formBuilder()
->getForm('Drupal\\button_field\\Form\\DummyForm', $element);
}
protected abstract function elementProperties();
protected function elementId($delta, $language) {
$parts = array(
'view',
str_replace('_', '-', $this->fieldDefinition
->getName()),
$language,
$delta,
'value',
);
return implode('-', $parts);
}
}