You are here

public function RobotFormBase::save in Examples for Developers 8

Same name and namespace in other branches
  1. 3.x modules/config_entity_example/src/Form/RobotFormBase.php \Drupal\config_entity_example\Form\RobotFormBase::save()

Overrides Drupal\Core\Entity\EntityFormController::save().

Saves the entity. This is called after submit() has built the entity from the form values. Do not override submit() as save() is the preferred method for entity form controllers.

Parameters

array $form: An associative array containing the structure of the form.

\Drupal\Core\Form\FormStateInterface $form_state: An associative array containing the current state of the form.

Overrides EntityForm::save

File

config_entity_example/src/Form/RobotFormBase.php, line 189

Class

RobotFormBase
Class RobotFormBase.

Namespace

Drupal\config_entity_example\Form

Code

public function save(array $form, FormStateInterface $form_state) {

  // EntityForm provides us with the entity we're working on.
  $robot = $this
    ->getEntity();

  // Drupal already populated the form values in the entity object. Each
  // form field was saved as a public variable in the entity class. PHP
  // allows Drupal to do this even if the method is not defined ahead of
  // time.
  $status = $robot
    ->save();

  // Grab the URL of the new entity. We'll use it in the message.
  $url = $robot
    ->toUrl();

  // Create an edit link.
  $edit_link = Link::fromTextAndUrl($this
    ->t('Edit'), $url)
    ->toString();
  if ($status == SAVED_UPDATED) {

    // If we edited an existing entity...
    $this
      ->messenger()
      ->addMessage($this
      ->t('Robot %label has been updated.', [
      '%label' => $robot
        ->label(),
    ]));
    $this
      ->logger('contact')
      ->notice('Robot %label has been updated.', [
      '%label' => $robot
        ->label(),
      'link' => $edit_link,
    ]);
  }
  else {

    // If we created a new entity...
    $this
      ->messenger()
      ->addMessage($this
      ->t('Robot %label has been added.', [
      '%label' => $robot
        ->label(),
    ]));
    $this
      ->logger('contact')
      ->notice('Robot %label has been added.', [
      '%label' => $robot
        ->label(),
      'link' => $edit_link,
    ]);
  }

  // Redirect the user back to the listing route after the save operation.
  $form_state
    ->setRedirect('entity.robot.list');
}