You are here

public function QuickNodeCloneNodeForm::save in Quick Node Clone 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 NodeForm::save

File

src/Form/QuickNodeCloneNodeForm.php, line 37

Class

QuickNodeCloneNodeForm
Form controller for Quick Node Clone edit forms.

Namespace

Drupal\quick_node_clone\Form

Code

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

  /** @var \Drupal\node\NodeInterface $node */
  $node = $this->entity;
  $insert = $node
    ->isNew();
  $node
    ->save();
  $node_link = $node
    ->toLink($this
    ->t('View'))
    ->toString();
  $context = [
    '@type' => $node
      ->getType(),
    '%title' => $node
      ->label(),
    'link' => $node_link,
  ];
  $t_args = [
    '@type' => node_get_type_label($node),
    '%title' => $node
      ->label(),
  ];
  if ($insert) {
    $this
      ->logger('content')
      ->notice('@type: added %title (clone).', $context);
    $this
      ->messenger()
      ->addMessage($this
      ->t('@type %title (clone) has been created.', $t_args));
  }
  if ($node
    ->id()) {
    $form_state
      ->setValue('nid', $node
      ->id());
    $form_state
      ->set('nid', $node
      ->id());
    $storage = $form_state
      ->getStorage();
    foreach ($storage['quick_node_clone_groups_storage'] as $group) {

      // Add node to all the groups the original was in
      // (if group and gnode modules aren't installed then nothing should ever
      // be set in this array anyway)
      $group
        ->addContent($node, "group_node:" . $node
        ->bundle());
    }
    if ($node
      ->access('view')) {
      $form_state
        ->setRedirect('entity.node.canonical', [
        'node' => $node
          ->id(),
      ]);
    }
    else {
      $form_state
        ->setRedirect('<front>');
    }
  }
  else {

    // In the unlikely case something went wrong on save, the node will be
    // rebuilt and node form redisplayed the same way as in preview.
    $this
      ->messenger()
      ->addError($this
      ->t('The cloned post could not be saved.'));
    $form_state
      ->setRebuild();
  }
}