0

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?

2

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. – Ravi Jul 31 '18 at 1:33
1

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(),
];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.