You are here

public function EntityModerationForm::buildForm in Drupal 9

Same name and namespace in other branches
  1. 8 core/modules/content_moderation/src/Form/EntityModerationForm.php \Drupal\content_moderation\Form\EntityModerationForm::buildForm()
  2. 10 core/modules/content_moderation/src/Form/EntityModerationForm.php \Drupal\content_moderation\Form\EntityModerationForm::buildForm()

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

core/modules/content_moderation/src/Form/EntityModerationForm.php, line 80

Class

EntityModerationForm
The EntityModerationForm provides a simple UI for changing moderation state.

Namespace

Drupal\content_moderation\Form

Code

public function buildForm(array $form, FormStateInterface $form_state, ContentEntityInterface $entity = NULL) {
  $current_state = $entity->moderation_state->value;
  $workflow = $this->moderationInfo
    ->getWorkflowForEntity($entity);

  /** @var \Drupal\workflows\Transition[] $transitions */
  $transitions = $this->validation
    ->getValidTransitions($entity, $this
    ->currentUser());

  // Exclude self-transitions.
  $transitions = array_filter($transitions, function (Transition $transition) use ($current_state) {
    return $transition
      ->to()
      ->id() != $current_state;
  });
  $target_states = [];
  foreach ($transitions as $transition) {
    $target_states[$transition
      ->to()
      ->id()] = $transition
      ->to()
      ->label();
  }
  if (!count($target_states)) {
    return $form;
  }
  if ($current_state) {
    $form['current'] = [
      '#type' => 'item',
      '#title' => $this
        ->t('Moderation state'),
      '#markup' => $workflow
        ->getTypePlugin()
        ->getState($current_state)
        ->label(),
    ];
  }

  // Persist the entity so we can access it in the submit handler.
  $form_state
    ->set('entity', $entity);
  $form['new_state'] = [
    '#type' => 'select',
    '#title' => $this
      ->t('Change to'),
    '#options' => $target_states,
  ];
  $form['revision_log'] = [
    '#type' => 'textfield',
    '#title' => $this
      ->t('Log message'),
    '#size' => 30,
  ];
  $form['submit'] = [
    '#type' => 'submit',
    '#value' => $this
      ->t('Apply'),
  ];
  $form['#theme'] = [
    'entity_moderation_form',
  ];
  $form['#attached']['library'][] = 'content_moderation/content_moderation';

  // Moderating an entity is allowed in a workspace.
  $form_state
    ->set('workspace_safe', TRUE);
  return $form;
}