You are here

public function ButtonFieldBase::formElement in Button Field 8

@todo Add ajax callback.

Overrides WidgetInterface::formElement

File

src/Plugin/Field/FieldWidget/ButtonFieldBase.php, line 22
Contains Drupal\button_field\Plugin\Field\FieldWidget\ButtonFieldBase.

Class

ButtonFieldBase
Base implementation for button field widgets.

Namespace

Drupal\button_field\Plugin\Field\FieldWidget

Code

public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {

  // Get the entity that we're rendering the field for.
  $entity = $items
    ->getEntity();
  $entity_id = $entity
    ->id();
  $entity_type = $entity
    ->getEntityType();

  // If any additional classes have been defined then add them to the classes
  // now.
  $class = array(
    'button_field',
  );
  $additional_classes = $this
    ->getFieldSetting('additional_classes');
  if (!empty($additional_classes)) {
    $class = array_merge($class, explode(' ', $additional_classes));
  }

  // Button elements do not obey the #description index, so if a description
  // has been set we need to build our own suffix.
  $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;
}