class ExampleForm in Mime Mail 8
The example email contact form.
Hierarchy
- class \Drupal\Core\Form\FormBase implements ContainerInjectionInterface, FormInterface uses DependencySerializationTrait, LoggerChannelTrait, MessengerTrait, LinkGeneratorTrait, RedirectDestinationTrait, UrlGeneratorTrait, StringTranslationTrait
- class \Drupal\mimemail_example\Form\ExampleForm
Expanded class hierarchy of ExampleForm
1 string reference to 'ExampleForm'
- mimemail_example.routing.yml in modules/
mimemail_example/ mimemail_example.routing.yml - modules/mimemail_example/mimemail_example.routing.yml
File
- modules/
mimemail_example/ src/ Form/ ExampleForm.php, line 16
Namespace
Drupal\mimemail_example\FormView source
class ExampleForm extends FormBase {
/**
* The email.validator service.
*
* @var \Drupal\Component\Utility\EmailValidatorInterface
*/
protected $emailValidator;
/**
* The language manager service.
*
* @var \Drupal\Core\Language\LanguageManagerInterface
*/
protected $languageManager;
/**
* The mail manager service.
*
* @var \Drupal\Core\Mail\MailManagerInterface
*/
protected $mailManager;
/**
* Constructs a new ExampleForm.
*
* @param \Drupal\Component\Utility\EmailValidatorInterface $email_validator
* The email validator service.
* @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
* The language manager service.
* @param \Drupal\Core\Mail\MailManagerInterface $mail_manager
* The mail manager service.
*/
public function __construct(EmailValidatorInterface $email_validator, LanguageManagerInterface $language_manager, MailManagerInterface $mail_manager) {
$this->emailValidator = $email_validator;
$this->languageManager = $language_manager;
$this->mailManager = $mail_manager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static($container
->get('email.validator'), $container
->get('language_manager'), $container
->get('plugin.manager.mail'));
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'mimemail_example_form';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state, $dir = NULL, $img = NULL) {
$form['intro'] = [
'#markup' => $this
->t('Use this form to send a HTML message to an email address. No spamming!'),
];
$form['key'] = [
'#type' => 'textfield',
'#title' => $this
->t('Key'),
'#description' => $this
->t('A key to identify the email sent.'),
'#default_value' => 'test',
'#required' => TRUE,
];
$form['to'] = [
'#type' => 'textfield',
'#title' => $this
->t('To'),
'#description' => $this
->t('The email address of the recipient. The formatting of this string must comply with RFC 2822.'),
'#default_value' => $this
->currentUser()
->getEmail(),
'#required' => TRUE,
];
$form['from'] = [
'#type' => 'textfield',
'#title' => $this
->t('Sender name'),
'#description' => $this
->t("The sender's name. Leave empty to use the site-wide configured name."),
];
$form['from_mail'] = [
'#type' => 'textfield',
'#title' => $this
->t('Sender email address'),
'#description' => $this
->t("The sender's email address. Leave empty to use the site-wide configured address."),
];
$form['params'] = [
'#tree' => TRUE,
'headers' => [
'Cc' => [
'#type' => 'textfield',
'#title' => $this
->t('Cc'),
'#description' => $this
->t("The mail's carbon copy address. You may separate multiple addresses with comma."),
],
'Bcc' => [
'#type' => 'textfield',
'#title' => $this
->t('Bcc'),
'#description' => $this
->t("The mail's blind carbon copy address. You may separate multiple addresses with comma."),
],
'Reply-to' => [
'#type' => 'textfield',
'#title' => $this
->t('Reply to'),
'#description' => $this
->t("The address to reply to. Leave empty to use the sender's address."),
],
'List-unsubscribe' => [
'#type' => 'textfield',
'#title' => $this
->t('List-unsubscribe'),
'#description' => $this
->t('An email address and/or a URL which can be used for unsubscription. Values must be enclosed by angle brackets and separated by a comma.'),
],
],
'subject' => [
'#type' => 'textfield',
'#title' => $this
->t('Subject'),
'#description' => $this
->t("The email's subject."),
],
'body' => [
'#type' => 'textarea',
'#title' => $this
->t('HTML message'),
'#description' => $this
->t("HTML version of the email body. This will be formatted using the text format selected at 'admin/config/system/mimemail'"),
],
// This form element forces plaintext-only email when there is no HTML
// content (that is, when the 'body' form element is empty).
'plain' => [
'#type' => 'hidden',
'#states' => [
'value' => [
':input[name="body"]' => [
'value' => '',
],
],
],
],
'plaintext' => [
'#type' => 'textarea',
'#title' => $this
->t('Plain text message'),
'#description' => $this
->t('Plain text version of the email body. HTML not allowed.'),
],
'attachments' => [
'#name' => 'files[attachment]',
'#type' => 'file',
'#title' => $this
->t('Choose a file to send as an email attachment'),
],
];
$form['submit'] = [
'#type' => 'submit',
'#value' => $this
->t('Send message'),
];
return $form;
}
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
// Extract the address part of the entered email before trying to validate.
// The email.validator service does not work on RFC2822 formatted addresses
// so we need to extract the RFC822 part out first. This is not as good as
// actually validating the full RFC2822 address, but it is better than
// either just validating RFC822 or not validating at all.
$pattern = '/<(.*?)>/';
$address = $form_state
->getValue('to');
preg_match_all($pattern, $address, $matches);
$address = isset($matches[1][0]) ? $matches[1][0] : $address;
if (!$this->emailValidator
->isValid($address)) {
$form_state
->setErrorByName('to', $this
->t('That email address is not valid.'));
}
$file = file_save_upload('attachment', [], 'temporary://', 0);
if ($file) {
$form_state
->setValue([
'params',
'attachments',
], [
[
'filepath' => $file
->getFileUri(),
],
]);
}
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
// First, assemble arguments for MailManager::mail().
$module = 'mimemail_example';
$key = $form_state
->getValue('key');
$to = $form_state
->getValue('to');
$langcode = $this->languageManager
->getDefaultLanguage()
->getId();
$params = $form_state
->getValue('params');
$reply = $params['headers']['Reply-to'];
$send = TRUE;
// Second, add values to $params and/or modify submitted values.
// Set From header.
if (!empty($form_state
->getValue('from_mail'))) {
$params['headers']['From'] = MimeMailFormatHelper::mimeMailAddress([
'name' => $form_state
->getValue('from'),
'mail' => $form_state
->getValue('from_mail'),
]);
}
elseif (!empty($form_state
->getValue('from'))) {
$params['headers']['From'] = $from = $form_state
->getValue('from');
}
else {
// Empty 'from' will result in the default site email being used.
}
// Handle empty attachments - we require this to be an array.
if (empty($params['attachments'])) {
$params['attachments'] = [];
}
// Remove empty values from $param['headers'] - this will force the
// the formatting mailsystem and the sending mailsystem to use the
// default values for these elements.
foreach ($params['headers'] as $header => $value) {
if (empty($value)) {
unset($params['headers'][$header]);
}
}
// Finally, call MailManager::mail() to send the mail.
$result = $this->mailManager
->mail($module, $key, $to, $langcode, $params, $reply, $send);
if ($result['result'] == TRUE) {
$this
->messenger()
->addMessage($this
->t('Your message has been sent.'));
}
else {
// This condition is also logged to the 'mail' logger channel by the
// default PhpMail mailsystem.
$this
->messenger()
->addError($this
->t('There was a problem sending your message and it was not sent.'));
}
}
}
Members
Name | Modifiers | Type | Description | Overrides |
---|---|---|---|---|
DependencySerializationTrait:: |
protected | property | An array of entity type IDs keyed by the property name of their storages. | |
DependencySerializationTrait:: |
protected | property | An array of service IDs keyed by property name used for serialization. | |
DependencySerializationTrait:: |
public | function | 1 | |
DependencySerializationTrait:: |
public | function | 2 | |
ExampleForm:: |
protected | property | The email.validator service. | |
ExampleForm:: |
protected | property | The language manager service. | |
ExampleForm:: |
protected | property | The mail manager service. | |
ExampleForm:: |
public | function |
Form constructor. Overrides FormInterface:: |
|
ExampleForm:: |
public static | function |
Instantiates a new instance of this class. Overrides FormBase:: |
|
ExampleForm:: |
public | function |
Returns a unique string identifying the form. Overrides FormInterface:: |
|
ExampleForm:: |
public | function |
Form submission handler. Overrides FormInterface:: |
|
ExampleForm:: |
public | function |
Form validation handler. Overrides FormBase:: |
|
ExampleForm:: |
public | function | Constructs a new ExampleForm. | |
FormBase:: |
protected | property | The config factory. | 1 |
FormBase:: |
protected | property | The request stack. | 1 |
FormBase:: |
protected | property | The route match. | |
FormBase:: |
protected | function | Retrieves a configuration object. | |
FormBase:: |
protected | function | Gets the config factory for this form. | 1 |
FormBase:: |
private | function | Returns the service container. | |
FormBase:: |
protected | function | Gets the current user. | |
FormBase:: |
protected | function | Gets the request object. | |
FormBase:: |
protected | function | Gets the route match. | |
FormBase:: |
protected | function | Gets the logger for a specific channel. | |
FormBase:: |
protected | function |
Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait:: |
|
FormBase:: |
public | function | Resets the configuration factory. | |
FormBase:: |
public | function | Sets the config factory for this form. | |
FormBase:: |
public | function | Sets the request stack object to use. | |
LinkGeneratorTrait:: |
protected | property | The link generator. | 1 |
LinkGeneratorTrait:: |
protected | function | Returns the link generator. | |
LinkGeneratorTrait:: |
protected | function | Renders a link to a route given a route name and its parameters. | |
LinkGeneratorTrait:: |
public | function | Sets the link generator service. | |
LoggerChannelTrait:: |
protected | property | The logger channel factory service. | |
LoggerChannelTrait:: |
protected | function | Gets the logger for a specific channel. | |
LoggerChannelTrait:: |
public | function | Injects the logger channel factory. | |
MessengerTrait:: |
protected | property | The messenger. | 29 |
MessengerTrait:: |
public | function | Gets the messenger. | 29 |
MessengerTrait:: |
public | function | Sets the messenger. | |
RedirectDestinationTrait:: |
protected | property | The redirect destination service. | 1 |
RedirectDestinationTrait:: |
protected | function | Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url. | |
RedirectDestinationTrait:: |
protected | function | Returns the redirect destination service. | |
RedirectDestinationTrait:: |
public | function | Sets the redirect destination service. | |
StringTranslationTrait:: |
protected | property | The string translation service. | 1 |
StringTranslationTrait:: |
protected | function | Formats a string containing a count of items. | |
StringTranslationTrait:: |
protected | function | Returns the number of plurals supported by a given language. | |
StringTranslationTrait:: |
protected | function | Gets the string translation service. | |
StringTranslationTrait:: |
public | function | Sets the string translation service to use. | 2 |
StringTranslationTrait:: |
protected | function | Translates a string to the current language or to a given language. | |
UrlGeneratorTrait:: |
protected | property | The url generator. | |
UrlGeneratorTrait:: |
protected | function | Returns the URL generator service. | |
UrlGeneratorTrait:: |
public | function | Sets the URL generator service. | |
UrlGeneratorTrait:: |
protected | function | Generates a URL or path for a specific route based on the given parameters. |