MessageViewBuilder.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. <?php
  2. namespace Drupal\contact;
  3. use Drupal\Core\Entity\EntityInterface;
  4. use Drupal\Core\Entity\EntityViewBuilder;
  5. use Drupal\Core\Mail\MailFormatHelper;
  6. use Drupal\Core\Render\Element;
  7. /**
  8. * Render controller for contact messages.
  9. */
  10. class MessageViewBuilder extends EntityViewBuilder {
  11. /**
  12. * {@inheritdoc}
  13. */
  14. protected function getBuildDefaults(EntityInterface $entity, $view_mode) {
  15. $build = parent::getBuildDefaults($entity, $view_mode);
  16. // The message fields are individually rendered into email templates, so
  17. // the entity has no template itself.
  18. unset($build['#theme']);
  19. return $build;
  20. }
  21. /**
  22. * {@inheritdoc}
  23. */
  24. public function view(EntityInterface $entity, $view_mode = 'full', $langcode = NULL) {
  25. $build = parent::view($entity, $view_mode, $langcode);
  26. if ($view_mode == 'mail') {
  27. // Convert field labels into headings.
  28. // @todo Improve \Drupal\Core\Mail\MailFormatHelper::htmlToText() to
  29. // convert DIVs correctly.
  30. foreach (Element::children($build) as $key) {
  31. if (isset($build[$key]['#label_display']) && $build[$key]['#label_display'] == 'above') {
  32. $build[$key] += ['#prefix' => ''];
  33. $build[$key]['#prefix'] = $build[$key]['#title'] . ":\n";
  34. $build[$key]['#label_display'] = 'hidden';
  35. }
  36. }
  37. $build['#post_render'][] = function ($html, array $elements) {
  38. return MailFormatHelper::htmlToText($html);
  39. };
  40. }
  41. return $build;
  42. }
  43. }