You are here

public function StyleguidePatternForm::save in Simple Style Guide 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/StyleguidePatternForm.php, line 72

Class

StyleguidePatternForm
Class StyleguidePatternForm.

Namespace

Drupal\simple_styleguide\Form

Code

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

  // Add as highest ranked by weight to put it at the bottom of the list.
  $storage = $this->entityTypeManager
    ->getStorage('styleguide_pattern');
  $ids = $storage
    ->getQuery()
    ->execute();
  if (!empty($ids)) {
    $custom_patterns = $storage
      ->loadMultiple($ids);
  }

  // If no weight is set, then this is a new entry.
  if (!$styleguide_pattern->weight && !empty($custom_patterns)) {
    $maxWeight = NULL;
    foreach ($custom_patterns as $pattern) {
      if (!$maxWeight || $pattern->weight > $maxWeight) {
        $maxWeight = $pattern->weight;
      }
    }
    $styleguide_pattern->weight = $maxWeight + 1;
  }

  // Save pattern entity.
  $status = $styleguide_pattern
    ->save();
  switch ($status) {
    case SAVED_NEW:
      $this
        ->messenger()
        ->addMessage($this
        ->t('Created the %label Styleguide pattern.', [
        '%label' => $styleguide_pattern
          ->label(),
      ]));
      break;
    default:
      $this
        ->messenger()
        ->addMessage($this
        ->t('Saved the %label Styleguide pattern.', [
        '%label' => $styleguide_pattern
          ->label(),
      ]));
  }
  $form_state
    ->setRedirectUrl($this
    ->getListUrl());
}