I'm using the hook_mail_alter()
to create a custom email for contact forms.
I was able to get the fields labels and values and use a twig template to send the email. Most of it is working just fine, but my problem is when I use file fields on the contact form. I want to be able to show the path of the uploaded files. When I use the default drupal email, it shows the paths at the end of the file. I want to do the same thing at my custom email. Can anyone tell me how to do this?
Add a comment
|
2 Answers
You can get the file entity directly from the field and check if the field is not empty before applying any methods on the file object:
/** @var \Drupal\contact\Entity\Message $contactMessage */
$contactMessage = $message['params']['contact_message'];
$file = $contactMessage->field_file->entity;
if (!empty($file)) {
$fileInfo[] = [
'value' => $file->getFilename(),
'url' => $file->url(),
];
}
-
Thanks! That is better than what I was doing. I was surprised that using
->getEntity()
gets the Message Entity and->entity
gets the File Entity.– RaviCommented Jul 31, 2018 at 1:33
I solved my question by getting the file from the fileId.
/** @var \Drupal\contact\Entity\Message $contactMessage */
$contactMessage = $message['params']['contact_message'];
$fileId = $contactMessage->get('field_file')->getValue()[0]['target_id'];
$file = \Drupal\file\Entity\File::load($fileId);
$fileInfo[] = [
'value' => $file->getFilename(),
'url' => $file->url(),
];