ContactController.php in Drupal 8
File
core/modules/contact/src/Controller/ContactController.php
View source
<?php
namespace Drupal\contact\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\contact\ContactFormInterface;
use Drupal\Core\Render\RendererInterface;
use Drupal\Core\Url;
use Drupal\user\UserInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class ContactController extends ControllerBase {
protected $renderer;
public function __construct(RendererInterface $renderer) {
$this->renderer = $renderer;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('renderer'));
}
public function contactSitePage(ContactFormInterface $contact_form = NULL) {
$config = $this
->config('contact.settings');
if (empty($contact_form)) {
$contact_form = $this
->entityTypeManager()
->getStorage('contact_form')
->load($config
->get('default_form'));
if (empty($contact_form)) {
if ($this
->currentUser()
->hasPermission('administer contact forms')) {
$this
->messenger()
->addError($this
->t('The contact form has not been configured. <a href=":add">Add one or more forms</a> .', [
':add' => Url::fromRoute('contact.form_add')
->toString(),
]));
return [];
}
else {
throw new NotFoundHttpException();
}
}
}
$message = $this
->entityTypeManager()
->getStorage('contact_message')
->create([
'contact_form' => $contact_form
->id(),
]);
$form = $this
->entityFormBuilder()
->getForm($message);
$form['#title'] = $contact_form
->label();
$form['#cache']['contexts'][] = 'user.permissions';
$this->renderer
->addCacheableDependency($form, $config);
return $form;
}
public function contactPersonalPage(UserInterface $user) {
if (!$user
->getEmail()) {
throw new NotFoundHttpException();
}
$message = $this
->entityTypeManager()
->getStorage('contact_message')
->create([
'contact_form' => 'personal',
'recipient' => $user
->id(),
]);
$form = $this
->entityFormBuilder()
->getForm($message);
$form['#title'] = $this
->t('Contact @username', [
'@username' => $user
->getDisplayName(),
]);
$form['#cache']['contexts'][] = 'user.permissions';
return $form;
}
}