You are here

public function PrivateMessageForm::validateMembers in Private Message 8

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

Validate members that have been added to a private message thread.

Validates that submitted members have permission to use the Private message system. This validation is not added automatically, as the members field is not part of the Private Message entity, but rather something that has been shoehorned in from the PrivateMessageThread entity, to make for a better user experience, by creating a thread and a message in a single form.

See also

\Drupal\private_message\Entity\PrivateMessageThead::baseFieldDefinitions

File

src/Form/PrivateMessageForm.php, line 223

Class

PrivateMessageForm
Defines the private message form.

Namespace

Drupal\private_message\Form

Code

public function validateMembers(array &$form, FormStateInterface $form_state) {

  // The members form element was loaded from the PrivateMessageThread entity
  // type. As it is not a part of the PrivateMessage entity, for which this
  // form is built, the constraints that are a part of the field on the
  // Private Message Thread are not applied. As such, the constraints need to
  // be checked manually.
  // First, get the PrivateMessageThread entity type.
  $entity_type = $this->entityTypeManager
    ->getDefinition('private_message_thread');

  // Next, load the field definitions as defined on the entity type.
  $field_definitions = PrivateMessageThread::baseFieldDefinitions($entity_type);

  // Get the member's field, as this is the field to be validated.
  $members_field = $field_definitions['members'];

  // Retrieve any members submitted on the form.
  $members = [];
  foreach ($form_state
    ->getValue('members') as $info) {
    if (is_array($info) && is_numeric($info[0]['target_id'])) {
      $user = $this->userManager
        ->load($info[0]['target_id']);
      if ($user) {
        $members[] = $user;
      }
    }
  }

  // Get a typed data element that can be used for validation.
  $typed_data = $this->typedDataManager
    ->create($members_field, $members);

  // Validate the submitted members.
  $violations = $typed_data
    ->validate();

  // Check to see if any contraint violations were found.
  if ($violations
    ->count() > 0) {

    // Output any errors for found constraint violations.
    foreach ($violations as $violation) {
      $form_state
        ->setError($form['members'], $violation
        ->getMessage());
    }
  }
}