You are here

public function AccessUnpublishedForm::formAlter in Access unpublished 8

Alter the entity form to add access unpublished elements.

File

src/Form/AccessUnpublishedForm.php, line 63

Class

AccessUnpublishedForm
Alter the entity form to add access unpublished elements.

Namespace

Drupal\access_unpublished\Form

Code

public function formAlter(&$form, FormStateInterface $form_state) {
  if (!$form_state
    ->getFormObject() instanceof EntityForm) {
    return;
  }

  /** @var \Drupal\Core\Entity\EntityInterface $entity */
  $entity = $form_state
    ->getFormObject()
    ->getEntity();
  if (AccessUnpublished::applicableEntityType($entity
    ->getEntityType()) && !$entity
    ->isPublished() && !$entity
    ->isNew()) {

    /** @var \Drupal\Core\Entity\EntityListBuilder $list_builder */
    $list_builder = $this->entityTypeManager
      ->getHandler('access_token', 'entity_form_list_builder');
    $form['access_unpublished_settings'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Temporary unpublished access'),
      '#weight' => 35,
      '#attributes' => [
        'class' => [
          'access-unpublished-form',
        ],
        'id' => 'edit-access-unpublished-settings',
      ],
      '#optional' => FALSE,
      '#group' => 'advanced',
    ];
    $form['access_unpublished_settings'] += $list_builder
      ->render($entity);
    $form['access_unpublished_settings']['duration'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Lifetime'),
      '#options' => static::getDurationOptions(),
      '#default_value' => $this->config
        ->get('duration'),
      '#attributes' => [
        'id' => 'edit-duration',
      ],
    ];
    $form['access_unpublished_settings']['generate_token'] = [
      '#type' => 'button',
      '#value' => $this
        ->t('Generate token'),
      '#ajax' => [
        'callback' => [
          __CLASS__,
          'generateToken',
        ],
      ],
      '#attributes' => [
        'id' => 'edit-generate-token',
      ],
    ];
  }
}