You are here

protected function ContactEmail::getEmailFromReferencedField in Contact Emails 8

Get email address from a field.

Parameters

\Drupal\contact\MessageInterface $message: The contact message.

object $field: The target field on the message.

Return value

array An array of emails.

Throws

\Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException

\Drupal\Component\Plugin\Exception\PluginNotFoundException

2 calls to ContactEmail::getEmailFromReferencedField()
ContactEmail::getRecipients in src/Entity/ContactEmail.php
Get the email recipient(s).
ContactEmail::getReplyTo in src/Entity/ContactEmail.php
Get the reply-to email address.

File

src/Entity/ContactEmail.php, line 537

Class

ContactEmail
Defines the Contact Email entity.

Namespace

Drupal\contact_emails\Entity

Code

protected function getEmailFromReferencedField(MessageInterface $message, $field) {
  $results = [];

  // Get the reference path, it consists of:
  // [0] contact_message reference field name.
  // [1] handler.
  // [2] bundle.
  // [3] referenced bundle email field name.
  $reference_path = explode('.', $field);
  if (count($reference_path) != 4) {

    // Something is wrong.
    return $results;
  }
  $reference_field_name = $reference_path[0];
  $entity_type = $reference_path[1];
  $email_field_name = $reference_path[3];
  if ($message
    ->hasField($reference_field_name)) {

    // Reference could potentially be a repeating field.
    $referenced_entity_id = $message
      ->get($reference_field_name)->target_id;
    if ($referenced_entity_id > 0) {
      $storage = \Drupal::entityTypeManager()
        ->getStorage($entity_type);

      /** @var \Drupal\Core\Entity\FieldableEntityInterface $entity */
      $entity = $storage
        ->load($referenced_entity_id);
      if ($emails = $entity
        ->get($email_field_name)
        ->getValue()) {
        foreach ($emails as $email) {
          if ($email['value']) {
            $results[] = $email['value'];
          }
        }
      }
    }
  }
  return $results;
}