You are here

public function StateTransitionForm::buildForm in State Machine 8

Form constructor.

Parameters

array $form: An associative array containing the structure of the form.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.

Return value

array The form structure.

Overrides FormInterface::buildForm

File

src/Form/StateTransitionForm.php, line 82

Class

StateTransitionForm

Namespace

Drupal\state_machine\Form

Code

public function buildForm(array $form, FormStateInterface $form_state) {

  /** @var \Drupal\state_machine\Plugin\Field\FieldType\StateItemInterface $state_item */
  $state_item = $this->entity
    ->get($this->fieldName)
    ->first();
  $form['actions'] = [
    '#type' => 'container',
  ];

  // Determine whether we should output links to the confirmation form,
  // or submit buttons.
  $require_confirmation = $form_state
    ->get('require_confirmation');
  foreach ($state_item
    ->getTransitions() as $transition_id => $transition) {
    if (!$require_confirmation) {
      $form['actions'][$transition_id] = [
        '#type' => 'submit',
        '#value' => $transition
          ->getLabel(),
        '#submit' => [
          '::submitForm',
        ],
        '#transition' => $transition,
      ];
      continue;
    }
    $url = $this->entity
      ->toUrl('state-transition-form');
    $route_parameters = $url
      ->getRouteParameters() + [
      $this->entity
        ->getEntityTypeId() => $this->entity
        ->id(),
      'field_name' => $this->fieldName,
      'transition_id' => $transition_id,
    ];
    $form['actions'][$transition_id] = [
      '#type' => 'link',
      '#title' => $transition
        ->getLabel(),
      '#url' => Url::fromRoute("entity.{$this->entity->getEntityTypeId()}.state_transition_form", $route_parameters),
      '#attributes' => [
        'class' => [
          'button',
        ],
      ],
    ];
    if ($form_state
      ->get('use_modal')) {
      $form['actions'][$transition_id]['#attributes']['class'][] = 'use-ajax';
      $form['actions'][$transition_id]['#attributes']['data-dialog-type'] = 'modal';
      $form['#attached']['library'][] = 'core/drupal.dialog.ajax';
    }
  }
  return $form;
}