You are here

public function PrivateMessageForm::save in Private Message 8.2

Same name and namespace in other branches
  1. 8 src/Form/PrivateMessageForm.php \Drupal\private_message\Form\PrivateMessageForm::save()

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/PrivateMessageForm.php, line 316

Class

PrivateMessageForm
Defines the private message form.

Namespace

Drupal\private_message\Form

Code

public function save(array $form, FormStateInterface $formState) {
  $status = parent::save($form, $formState);

  /** @var \Drupal\private_message\Entity\PrivateMessageThreadInterface $private_message_thread */
  $private_message_thread = $formState
    ->get('thread');
  if (!$private_message_thread) {

    // Generate an array containing the members of the thread.
    $current_user = $this->userManager
      ->load($this->currentUser
      ->id());
    $members = [
      $current_user,
    ];
    $entity = $formState
      ->get('pmt_entity');
    foreach ($entity
      ->get('members') as $user) {
      if ($user instanceof EntityReferenceItem) {
        $user = $user->entity;
      }
      $members[] = $user;
    }

    // Get a private message thread containing the given users.
    $private_message_thread = $this->privateMessageService
      ->getThreadForMembers($members);
  }

  // Save the thread.
  $this->privateMessageThreadManager
    ->saveThread($this->entity, $private_message_thread
    ->getMembers(), [], $private_message_thread);

  // Save the thread to the form state.
  $formState
    ->set('private_message_thread', $private_message_thread);

  // Send the user to the private message page. As this thread is the newest,
  // it wll be at the top of the list.
  $formState
    ->setRedirect('entity.private_message_thread.canonical', [
    'private_message_thread' => $private_message_thread
      ->id(),
  ]);
  return $status;
}