I am trying to use hook_mail_alter
to create a custom contact mail.
I want to get the display setting of the contact form.
(example path: http://mysite/admin/structure/contact/manage/my_contact_form/display/mail)
The things I want to know are:
- Field Label
- If its disabled or not
- Field order
- Field ID
How can I get this information in the PHP script?
EDIT:
I was able to get most of the information I wanted. but I couldn't get the field weight to display in the right order. I have a display mode called 'mail' and I want to get the weight of each field in this mode.
for now the code looks like this:
/**
* Implements hook_mail_alter().
*/
function contact_plus_mail_alter(&$message) {
if (isset($message['id']) && $message['id'] == 'contact_page_mail') {
$siteName = \Drupal::config('system.site')->get('name');
$siteMail = \Drupal::config('system.site')->get('mail');
/** @var \Drupal\contact\Entity\Message $contactMessage */
$contactMessage = $message['params']['contact_message'];
$entityType = $contactMessage->getEntityType()->id();
$bundle = $contactMessage->bundle();
$contactForm = $contactMessage->getContactForm();
$form_title = $contactForm->label();
$recipients = implode(',', $contactForm->getRecipients());
/** @var \Drupal\Core\Field\FieldItemListInterface[] $fields */
$fields = $contactMessage->getFields();
$data = [
'title' => $form_title,
'fields' => [],
];
foreach ($fields as $key => $field) {
$fieldDefinition = $field->getFieldDefinition();
$data['fields'][] = [
'label' => $fieldDefinition->getLabel(),
'info' => $field->getValue(),
'display_options' => $fieldDefinition->getDisplayOptions(),
'weight' => '', // I want to get the field weight for the 'mail' display mode.
];
}
// TODO: order the data by weight
// ... send the email
}
}
contact-message--mail.html.twig
assuming the view mode ismail
) to customize the resulting HTML.getComponents()
function. Here is how: answer