You are here

public function ViewsContactFormEmailFormatter::viewElements in Views Contact Form 8

Builds a renderable array for a field value.

Parameters

\Drupal\Core\Field\FieldItemListInterface $items: The field values to be rendered.

string $langcode: The language that should be used to render the field.

Return value

array A renderable array for $items, as an array of child elements keyed by consecutive numeric indexes starting from 0.

Overrides FormatterInterface::viewElements

File

lib/Drupal/views_contact_form/Plugin/Field/FieldFormatter/ViewsContactFormEmailFormatter.php, line 34
Definition of Drupal\views_contact_form\Plugin\field\formatter\ViewsContactFormEmailFormatter.

Class

ViewsContactFormEmailFormatter
Plugin implementation of the 'ViewsContactFormEmailFormatter' formatter

Namespace

Drupal\views_contact_form\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items) {
  module_load_include('pages.inc', 'contact');

  // Get the category entity from the configuration.
  $category = clone entity_load('contact_category', $this
    ->getSetting('category'));

  // Get value from the items and store it.
  $recipients = array();
  foreach ($items as $delta => $item) {
    $recipients[] = $item->value;
  }

  // If we want to send email also to the recipients from the category,
  // merge recipients from items and category.
  if ($this
    ->getSetting('category_recipients_include') == TRUE) {
    $recipients = array_merge($recipients, $category->recipients);
  }

  // Remove the doubles to avoid double mail.
  $recipients = array_unique($recipients);

  // Finally override the recipients on the category entity.
  $category
    ->set('recipients', $recipients);

  // Create the Message entity from the category.
  $message = entity_create('contact_message', array(
    'category' => $category
      ->id(),
  ));

  // Override the entity category in the Message.
  // So the recipients are also set.
  $message->category->entity = $category;

  // Get the form
  $form = \Drupal::entityManager()
    ->getForm($message);

  // Override the title
  $form['#title'] = String::checkPlain($category
    ->label());

  // Render the form and return the element.
  return array(
    0 => array(
      '#markup' => drupal_render($form),
    ),
  );
}