postoffice-1.0.x-dev/examples/postoffice_form_example/src/Form/TestEmailForm.php
examples/postoffice_form_example/src/Form/TestEmailForm.php
<?php
namespace Drupal\postoffice_form_example\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\postoffice_form_example\Email\TestEmail;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Mailer\Exception\ExceptionInterface as MailerExceptionInterface;
use Symfony\Component\Mailer\MailerInterface;
/**
* Example email form.
*/
class TestEmailForm extends FormBase implements FormInterface {
/**
* The mailer service.
*/
protected MailerInterface $mailer;
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static($container->get('postoffice.mailer'));
}
/**
* Constructs new email test form.
*/
public function __construct(MailerInterface $mailer) {
$this->mailer = $mailer;
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'custom_mailer_mail_test';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$form['to'] = [
'#type' => 'email',
'#title' => $this->t('To'),
'#default_value' => $this->currentUser()->getEmail(),
];
$form['name'] = [
'#type' => 'textfield',
'#title' => $this->t('Name'),
'#default_value' => $this->currentUser()->getDisplayName(),
];
$form['actions']['#type'] = 'actions';
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Send'),
];
return $form;
}
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$mail = (new TestEmail($form_state->getValue('name'), $this->config('system.site')))
->to($form_state->getValue('to'));
try {
$this->mailer->send($mail);
$this->messenger()->addMessage($this->t('Mail sent!'));
}
catch (MailerExceptionInterface $e) {
$this->messenger()->addError($this->t('Failed to send mail: @error', [
'@error' => $e->getMessage(),
]));
}
}
}
