You are here

public function StateTransitionFormFormatter::viewElements in State Machine 8

Builds a renderable array for a field value.

Parameters

\Drupal\Core\Field\FieldItemListInterface $items: The field values to be rendered.

string $langcode: The language that should be used to render the field.

Return value

array A renderable array for $items, as an array of child elements keyed by consecutive numeric indexes starting from 0.

Overrides FormatterInterface::viewElements

File

src/Plugin/Field/FieldFormatter/StateTransitionFormFormatter.php, line 104

Class

StateTransitionFormFormatter
Plugin implementation of the 'state_transition_form' formatter.

Namespace

Drupal\state_machine\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {

  /** @var \Drupal\Core\Entity\FieldableEntityInterface $entity */
  $entity = $items
    ->getEntity();

  // Do not show the form if the user isn't allowed to modify the entity.
  if (!$entity
    ->access('update')) {
    return [];
  }

  /** @var \Drupal\state_machine\Form\StateTransitionFormInterface $form_object */
  $form_object = $this->classResolver
    ->getInstanceFromDefinition(StateTransitionForm::class);
  $form_object
    ->setEntity($entity);
  $form_object
    ->setFieldName($items
    ->getFieldDefinition()
    ->getName());
  $form_state_additions = [];
  if ($this
    ->supportsConfirmationForm()) {
    $form_state_additions += [
      // Store in the form state whether a confirmation is required before
      // applying the state transition.
      'require_confirmation' => (bool) $this
        ->getSetting('require_confirmation'),
      'use_modal' => (bool) $this
        ->getSetting('use_modal'),
    ];
  }
  $form_state = (new FormState())
    ->setFormState($form_state_additions);

  // $elements needs a value for each delta. State fields can't be multivalue,
  // so it's safe to hardcode 0.
  $elements = [];
  $elements[0] = $this->formBuilder
    ->buildForm($form_object, $form_state);
  return $elements;
}