You are here

public function EntityTestForm::save in Drupal 8

Same name and namespace in other branches
  1. 9 core/modules/system/tests/modules/entity_test/src/EntityTestForm.php \Drupal\entity_test\EntityTestForm::save()
  2. 10 core/modules/system/tests/modules/entity_test/src/EntityTestForm.php \Drupal\entity_test\EntityTestForm::save()

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

core/modules/system/tests/modules/entity_test/src/EntityTestForm.php, line 50

Class

EntityTestForm
Form controller for the test entity edit forms.

Namespace

Drupal\entity_test

Code

public function save(array $form, FormStateInterface $form_state) {
  try {
    $entity = $this->entity;

    // Save as a new revision if requested to do so.
    if (!$form_state
      ->isValueEmpty('revision')) {
      $entity
        ->setNewRevision();
    }
    $is_new = $entity
      ->isNew();
    $entity
      ->save();
    if ($is_new) {
      $message = t('%entity_type @id has been created.', [
        '@id' => $entity
          ->id(),
        '%entity_type' => $entity
          ->getEntityTypeId(),
      ]);
    }
    else {
      $message = t('%entity_type @id has been updated.', [
        '@id' => $entity
          ->id(),
        '%entity_type' => $entity
          ->getEntityTypeId(),
      ]);
    }
    $this
      ->messenger()
      ->addStatus($message);
    if ($entity
      ->id()) {
      $entity_type = $entity
        ->getEntityTypeId();
      $form_state
        ->setRedirect("entity.{$entity_type}.edit_form", [
        $entity_type => $entity
          ->id(),
      ]);
    }
    else {

      // Error on save.
      $this
        ->messenger()
        ->addError($this
        ->t('The entity could not be saved.'));
      $form_state
        ->setRebuild();
    }
  } catch (\Exception $e) {
    \Drupal::state()
      ->set('entity_test.form.save.exception', get_class($e) . ': ' . $e
      ->getMessage());
  }
}