You are here

public static function AccessUnpublishedForm::generateToken in Access unpublished 8

Submit callback to generate a token.

Parameters

array $form: Form array.

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

Return value

\Drupal\Core\Ajax\AjaxResponse The ajax response with the new form.

Throws

\Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException

\Drupal\Component\Plugin\Exception\PluginNotFoundException

\Drupal\Core\Entity\EntityStorageException

File

src/Form/AccessUnpublishedForm.php, line 129

Class

AccessUnpublishedForm
Alter the entity form to add access unpublished elements.

Namespace

Drupal\access_unpublished\Form

Code

public static function generateToken(array &$form, FormStateInterface $form_state) {

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

  /** @var \Drupal\access_unpublished\Entity\AccessToken $access_token */
  $access_token = \Drupal::entityTypeManager()
    ->getStorage('access_token')
    ->create([
    'entity_type' => $entity
      ->getEntityType()
      ->id(),
    'entity_id' => $entity
      ->id(),
    'expire' => $form_state
      ->getValue('duration') > 0 ? \Drupal::time()
      ->getRequestTime() + $form_state
      ->getValue('duration') : -1,
  ]);
  $access_token
    ->save();

  /** @var \Drupal\Core\Entity\EntityListBuilder $list_builder */
  $list_builder = \Drupal::service('entity_type.manager')
    ->getHandler('access_token', 'entity_form_list_builder');
  $form = $list_builder
    ->render($access_token
    ->getHost());
  $response = new AjaxResponse();
  $response
    ->addCommand(new ReplaceCommand('[data-drupal-selector="access-token-list"]', $form['table']));
  return $response;
}