You are here

public function TokenCustomForm::save in Custom Tokens 8

Form submission handler for the 'save' action.

Normally this method should be overridden to provide specific messages to the user and redirect the form after the entity has been saved.

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

int Either SAVED_NEW or SAVED_UPDATED, depending on the operation performed.

Overrides EntityForm::save

File

src/Form/TokenCustomForm.php, line 114

Class

TokenCustomForm
Form handler for the custom token edit forms.

Namespace

Drupal\token_custom\Form

Code

public function save(array $form, FormStateInterface $form_state) {
  $token = $this->entity;
  $insert = $token
    ->isNew();
  $token
    ->save();
  token_clear_cache();
  $context = [
    '@type' => $token
      ->bundle(),
    '%info' => $token
      ->label(),
  ];
  $logger = $this
    ->logger('token_custom');
  $token_type = $this->tokenCustomTypeStorage
    ->load($token
    ->bundle());
  $t_args = [
    '@type' => $token_type
      ->label(),
    '%info' => $token
      ->label(),
  ];
  if ($insert) {
    $logger
      ->notice('@type: added %info.', $context);
    $this
      ->messenger()
      ->addStatus($this
      ->t('@type %info has been created.', $t_args));
  }
  else {
    $logger
      ->notice('@type: updated %info.', $context);
    $this
      ->messenger()
      ->addStatus($this
      ->t('@type %info has been updated.', $t_args));
  }
  if ($token
    ->id()) {
    $form_state
      ->setValue('id', $token
      ->id());
    $form_state
      ->set('id', $token
      ->id());
    $form_state
      ->setRedirectUrl($token
      ->toUrl('collection'));
  }
  else {

    // In the unlikely case something went wrong on save, the token will be
    // rebuilt and token form redisplayed.
    $this
      ->messenger()
      ->addError($this
      ->t('The token could not be saved.'));
    $form_state
      ->setRebuild();
  }
}