You are here

public function DynamicLayoutForm::save in Dynamic Layouts 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/DynamicLayoutForm.php, line 427

Class

DynamicLayoutForm
Form controller for the DynamicLayout entity edit forms.

Namespace

Drupal\dynamic_layouts\Form

Code

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

  // Check for the layout form element.
  if (!($general_settings = $form_state
    ->getValue(Constants::GENERAL_SETTING))) {
    return NULL;
  }

  /** @var \Drupal\dynamic_layouts\DynamicLayoutInterface $entity */
  $entity = $this->entity;

  // Check if we need to redirect to the list.
  $entity_is_new = FALSE;
  if ($entity
    ->isNew()) {
    $entity_is_new = TRUE;
  }
  $this
    ->setFormValues($general_settings, $entity, $entity_is_new);

  // Save the entity, add the starting rows and set the action.
  $status = $entity
    ->save();
  if ($entity_is_new && isset($general_settings[Constants::START_ROWS_COUNT]) && $general_settings[Constants::START_ROWS_COUNT]) {
    $entity
      ->addStartingRows($general_settings);
  }
  $action = $status == SAVED_UPDATED ? 'updated' : 'added';

  // Tell the user we've updated their layout.
  $this
    ->messenger()
    ->addStatus($this
    ->t('Layout %label has been %action.', [
    '%label' => $entity
      ->label(),
    '%action' => $action,
  ]));
  $this
    ->logger(Constants::DYNAMIC_LAYOUT)
    ->notice('Layout %label has been %action.', array(
    '%label' => $entity
      ->label(),
    '%action' => $action,
  ));

  // Clear all plugin caches.
  // This is needed to display the Dynamic Layouts in Display Suite.
  \Drupal::service('plugin.cache_clearer')
    ->clearCachedDefinitions();

  // Redirect back to the list view if layout is not new.
  if (!$entity_is_new) {
    $form_state
      ->setRedirect('dynamic_layout.dynamic_layout_list');
  }
  else {
    $form_state
      ->setRedirect('entity.dynamic_layout.edit_form', [
      Constants::DYNAMIC_LAYOUT => $entity
        ->id(),
    ]);
  }
}