function EntityTestForm::save

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. 8.9.x core/modules/system/tests/modules/entity_test/src/EntityTestForm.php \Drupal\entity_test\EntityTestForm::save()
  3. 11.x core/modules/system/tests/modules/entity_test/src/EntityTestForm.php \Drupal\entity_test\EntityTestForm::save()

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();
    $status = $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());
  }
  return $status ?? FALSE;
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.