email_contact.module in Email Contact 8
Same filename and directory in other branches
Email Contact module file.
File
email_contact.moduleView source
<?php
/**
* @file
* Email Contact module file.
*/
use Drupal\Component\Utility\Html;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
/**
* Return emails from entity and given field name.
*
* @param string $entity_type
* The type of requested entity.
* @param string $id
* The id of the requested entity.
* @param object $field_name
* The name of the email field.
*
* @return array
* An array with valid email addresses.
*/
function email_contact_get_emails_from_field($entity_type, $id, $field_name) {
if (!is_numeric($id)) {
throw new NotFoundHttpException();
}
/** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
$entity = \Drupal::entityTypeManager()
->getStorage($entity_type)
->load($id);
// Check that the entity exists.
if ($entity === NULL) {
throw new NotFoundHttpException();
}
// Check that the field exists and has the right type.
if (!$entity
->hasField($field_name)) {
throw new NotFoundHttpException();
}
$field = $entity
->get($field_name);
if ($field === NULL || $field
->getFieldDefinition()
->getType() != 'email') {
throw new NotFoundHttpException();
}
// Load email addresses
foreach ($field
->getIterator() as $item) {
$value = $item
->getValue()['value'];
if (!empty($value) && strpos($value, '@') !== FALSE) {
$emails[] = $value;
}
}
// Verify that the email address is not empty.
if (empty($emails)) {
throw new NotFoundHttpException();
}
return $emails;
}
/**
* Implements hook_mail().
*/
function email_contact_mail($key, &$message, $params) {
switch ($key) {
case 'contact':
// Compose the body.
$token = Drupal::token();
$message['body'][] = $token
->replace($params['default_message']);
$message['body'][] = $params['message'];
$message['subject'] = "";
// Include the title of the entity, if one exists.
$message['subject'] .= " " . Html::escape($params['subject']);
break;
}
}
Functions
Name | Description |
---|---|
email_contact_get_emails_from_field | Return emails from entity and given field name. |
email_contact_mail | Implements hook_mail(). |