class MassContactForm in Mass Contact 8
Main form for sending Mass Contact emails.
Hierarchy
- class \Drupal\Core\Form\FormBase implements ContainerInjectionInterface, FormInterface uses DependencySerializationTrait, LoggerChannelTrait, MessengerTrait, LinkGeneratorTrait, RedirectDestinationTrait, UrlGeneratorTrait, StringTranslationTrait
- class \Drupal\Core\Entity\EntityForm implements EntityFormInterface
- class \Drupal\Core\Entity\ContentEntityForm implements ContentEntityFormInterface
- class \Drupal\mass_contact\Form\MassContactForm
- class \Drupal\Core\Entity\ContentEntityForm implements ContentEntityFormInterface
- class \Drupal\Core\Entity\EntityForm implements EntityFormInterface
Expanded class hierarchy of MassContactForm
File
- src/
Form/ MassContactForm.php, line 21
Namespace
Drupal\mass_contact\FormView source
class MassContactForm extends ContentEntityForm {
/**
* The mass contact configuration.
*
* @var \Drupal\Core\Config\ImmutableConfig
*/
protected $config;
/**
* The entity type manager service.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* The module handler service.
*
* @var \Drupal\Core\Extension\ModuleHandlerInterface
*/
protected $moduleHandler;
/**
* The mass contact service.
*
* @var \Drupal\mass_contact\MassContactInterface
*/
protected $massContact;
/**
* Constructs the Mass Contact form.
*
* @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
* The entity manager.
* @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $entity_type_bundle_info
* The entity type bundle service.
* @param \Drupal\Component\Datetime\TimeInterface $time
* The time service.
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
* The module handler service.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager service.
* @param \Drupal\mass_contact\MassContactInterface $mass_contact
* The mass contact service.
* @param \Drupal\user\PrivateTempStoreFactory $temp_store_factory
* The factory for the temp store object.
*/
public function __construct(EntityManagerInterface $entity_manager, EntityTypeBundleInfoInterface $entity_type_bundle_info = NULL, TimeInterface $time = NULL, ModuleHandlerInterface $module_handler, EntityTypeManagerInterface $entity_type_manager, MassContactInterface $mass_contact, PrivateTempStoreFactory $temp_store_factory) {
parent::__construct($entity_manager, $entity_type_bundle_info, $time);
$this->config = $this
->configFactory()
->get('mass_contact.settings');
$this->entityTypeManager = $entity_type_manager;
$this->moduleHandler = $module_handler;
$this->massContact = $mass_contact;
$this->tempStoreFactory = $temp_store_factory;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static($container
->get('entity.manager'), $container
->get('entity_type.bundle.info'), $container
->get('datetime.time'), $container
->get('module_handler'), $container
->get('entity_type.manager'), $container
->get('mass_contact'), $container
->get('user.private_tempstore'));
}
/**
* {@inheritdoc}
*/
public function form(array $form, FormStateInterface $form_state) {
$form = parent::form($form, $form_state);
$categories = [];
$default_category = [];
$default_category_name = '';
/** @var \Drupal\mass_contact\Entity\MassContactCategoryInterface $category */
foreach ($this->entityTypeManager
->getStorage('mass_contact_category')
->loadMultiple() as $category) {
if ($category
->access('view')) {
$categories[$category
->id()] = $category
->label();
if ($category
->getSelected()) {
$default_category[] = $category
->id();
$default_category_name = $category
->label();
}
}
}
$form['contact_information'] = [
'#markup' => Xss::filterAdmin($this->config
->get('form_information')),
];
// Add the field for specifying the sender's name.
$default_sender_name = $this->config
->get('default_sender_name');
$sender_name_title = $this
->t('Sender name');
if ($default_sender_name) {
if ($this
->currentUser()
->hasPermission('mass contact change default sender information')) {
$form['sender_name'] = [
'#type' => 'textfield',
'#title' => $sender_name_title,
'#maxlength' => 255,
'#default_value' => $default_sender_name,
'#required' => TRUE,
];
}
else {
$form['sender_name'] = [
'#type' => 'item',
'#title' => $sender_name_title,
'#value' => $default_sender_name,
];
}
}
else {
$form['sender_name'] = [
'#type' => 'textfield',
'#title' => $sender_name_title,
'#maxlength' => 255,
'#default_value' => $this
->currentUser()
->getDisplayName(),
'#required' => TRUE,
];
}
// Add the field for specifying the sender's email address.
$default_sender_email = $this->config
->get('default_sender_email');
$sender_name_title = $this
->t('Sender email');
if ($default_sender_email) {
if ($this
->currentUser()
->hasPermission('mass contact change default sender information')) {
$form['sender_mail'] = [
'#type' => 'email',
'#title' => $sender_name_title,
'#default_value' => $default_sender_email,
'#required' => TRUE,
];
}
else {
$form['sender_mail'] = [
'#type' => 'item',
'#title' => $sender_name_title,
'#value' => $default_sender_email,
];
}
}
else {
$form['sender_mail'] = [
'#type' => 'email',
'#title' => $sender_name_title,
'#default_value' => $this
->currentUser()
->getEmail(),
'#required' => TRUE,
];
}
// Add the field for specifying the category(ies).
// Categories are optional. This means that if there is no category
// configured, the user can send a copy to him/herself.
// If there are categories configured and one of them has been configured as
// 'selected' by default, present a list of categories to choose from,
// defaulted to the one configured as one.
if (count($categories) > 0) {
// Display a choice when one is needed.
$form['categories'] = [
'#type' => $this->config
->get('category_display'),
'#title' => $this
->t('Category'),
'#default_value' => $default_category,
'#options' => $categories,
'#multiple' => TRUE,
];
}
else {
// There is a default category selected and it is only one category
// configured.
if ($default_category) {
// Otherwise, just use the default category.
$form['categories'] = [
'#type' => 'value',
'#value' => $default_category,
];
$form['cid-info'] = [
'#type' => 'item',
'#title' => $this
->t('Category'),
'#markup' => $this
->t('This message will be sent to all users in the %category category.', [
'%category' => $default_category_name,
]),
];
}
else {
// There are no categories configured.
$form['cid-info'] = [
'#type' => 'item',
'#title' => $this
->t('Category'),
'#markup' => $this
->t('No categories have been configured.'),
];
}
}
// Add the field for specifying whether opt-outs are respected or not.
$optout_setting = $this->config
->get('optout_enabled');
// Allow users to opt-out of mass emails:
// 'disabled' => 'No', 'global' == 'Yes', 'category' == 'Selected
// categories'.
if ($optout_setting !== MassContactInterface::OPT_OUT_DISABLED) {
// @todo https://www.drupal.org/node/2867177
// Allow to override or respect opt-outs if admin, otherwise use
// default.
if ($this
->currentUser()
->hasPermission('mass contact administer')) {
$form['optout'] = [
'#type' => 'checkbox',
'#title' => $this
->t('Respect user opt-outs.'),
'#default_value' => 1,
];
}
else {
$form['optout'] = [
'#type' => 'hidden',
'#default_value' => 1,
];
}
}
else {
$form['optout'] = [
'#type' => 'hidden',
'#default_value' => 0,
];
}
// Add the field for specifying whether the recipients are in the To or
// BCC field of the message.
// Check if the user is allowed to override the BCC setting.
if ($this
->currentUser()
->hasPermission('mass contact override bcc')) {
$form['use_bcc'] = [
'#type' => 'checkbox',
'#title' => $this
->t('Send as BCC (hide recipients).'),
'#default_value' => $this->config
->get('use_bcc'),
];
}
else {
$form['use_bcc'] = [
'#type' => 'value',
'#value' => $this->config
->get('use_bcc'),
];
$form['bcc-info'] = [
'#type' => 'item',
'#title' => $this
->t('Send as BCC (hide recipients)'),
'#markup' => $this->config
->get('use_bcc') ? $this
->t('Recipients will be hidden from each other.') : $this
->t('Recipients will NOT be hidden from each other.'),
];
}
// Add the field for specifying the subject of the message.
$form['subject'] = [
'#type' => 'textfield',
'#title' => $this
->t('Subject'),
'#maxlength' => 255,
'#required' => TRUE,
];
// Add the field for specifying the body and text format of the message.
// Get the HTML input format setting and the corresponding name.
// Get the admin specified default text format.
$default_filter_format = $this->config
->get('message_format');
// Check if the user is allowed to override the text format.
$form['body'] = [
'#type' => 'text_format',
'#title' => $this
->t('Message'),
'#format' => $default_filter_format ?: filter_default_format(),
'#rows' => 12,
'#required' => TRUE,
];
if (!$this
->currentUser()
->hasPermission('mass contact override text format')) {
// The user is not allowed to override the text format, so lock it down
// to the default one.
$form['body']['#allowed_formats'] = [
$default_filter_format ?: filter_default_format(),
];
}
if (!$this->moduleHandler
->moduleExists('mimemail') && !$this->moduleHandler
->moduleExists('swiftmailer')) {
// No HTML email handling, lock down to plain text.
$form['body']['#allowed_formats'] = [
'plain_text',
];
$form['body']['#format'] = 'plain_text';
}
// If the user has access, add the field for specifying the attachment.
if (FALSE && ($this->moduleHandler
->moduleExists('mimemail') || $this->moduleHandler
->moduleExists('swiftmailer'))) {
// @todo Port email attachments.
// @see https://www.drupal.org/node/2867544
if ($this
->currentUser()
->hasPermission('mass contact include attachments')) {
for ($i = 1; $i <= $this->config
->get('number_of_attachments'); $i++) {
$form['attachment_' . $i] = [
'#type' => 'file',
'#title' => $this
->t('Attachment #!number', [
'!number' => $i,
]),
];
}
}
}
// We do not allow anonymous users to send themselves a copy because it
// can be abused to spam people.
// @todo Why are anonymous users allowed to hit this form at all?!
if ($this
->currentUser()
->id()) {
$form['copy'] = [
'#type' => 'checkbox',
'#title' => $this
->t('Send yourself a copy.'),
];
}
// Check if the user is allowed to override the node copy setting.
if ($this
->currentUser()
->hasPermission('mass contact override archiving')) {
$form['create_archive_copy'] = [
'#type' => 'checkbox',
'#title' => $this
->t('Archive a copy of this message on this website.'),
'#default_value' => $this->config
->get('create_archive_copy'),
];
}
else {
$form['create_archive_copy'] = [
'#type' => 'value',
'#value' => $this->config
->get('create_archive_copy'),
];
$form['archive_notice'] = [
'#type' => 'item',
'#title' => $this
->t('Archive a copy of this message on this website'),
'#markup' => $this->config
->get('create_archive_copy') ? $this
->t('A copy of this message will be archived on this website.') : $this
->t('A copy of this message will NOT be archived on this website.'),
];
}
// Add the submit button.
$form['submit'] = [
'#type' => 'submit',
'#value' => $this
->t('Send email'),
];
$this
->buildTaskList($form);
return $form;
}
/**
* {@inheritdoc}
*/
public function actions(array $form, FormStateInterface $form_state) {
// @todo Potentially refactor to add the 'Send email' button here.
return [];
}
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
parent::validateForm($form, $form_state);
// Get the list of recipients for all chosen categories if any have been
// chosen.
$field_categories_value = array_filter($form_state
->getValue('categories'));
if (!empty($field_categories_value)) {
$categories = $this->entityTypeManager
->getStorage('mass_contact_category')
->loadMultiple($field_categories_value);
$all_recipients = $this->massContact
->getRecipients($categories, $form_state
->getValue('optout'));
}
// If the 'Send yourself a copy' option has been chosen. count it as a
// recipient.
if ($form_state
->getValue('copy')) {
$all_recipients[] = $this
->currentUser()
->id();
}
// Either a category should be chosen, or send yourself a copy option should
// be checked.
if (empty($all_recipients)) {
$form_state
->setErrorByName('categories', $this
->t('There are no recipients chosen for this mass contact message.'));
}
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$configuration = [
'use_bcc' => $form_state
->getValue('use_bcc'),
'sender_name' => $form_state
->getValue('sender_name'),
'sender_mail' => $form_state
->getValue('sender_mail'),
'create_archive_copy' => $form_state
->getValue('create_archive_copy'),
'respect_opt_out' => $form_state
->getValue('optout'),
];
// Add the sender's email to the configs, if the 'Send yourself a copy'
// option has been chosen.
if ($form_state
->getValue('copy')) {
$configuration['send_me_copy_user'] = $this
->currentUser()
->id();
}
else {
$configuration['send_me_copy_user'] = FALSE;
}
$message = $this->entityTypeManager
->getStorage('mass_contact_message')
->create([
'subject' => $form_state
->getValue('subject'),
'body' => $form_state
->getValue('body'),
]);
$categories = [];
$field_categories_value = array_filter($form_state
->getValue('categories'));
if (!empty($field_categories_value)) {
foreach ($field_categories_value as $id) {
$categories[] = [
'target_id' => $id,
];
}
$message->categories = $categories;
}
// Store data needed for the confirmation form in the user's private temp
// storage.
$store = \Drupal::service("user.private_tempstore")
->get('mass_contact_confirm_info');
$store
->set($message
->uuid(), [
'mass_contact_message' => $message,
'configuration' => $configuration,
]);
// Redirect to the confirmation form.
$form_state
->setRedirect('entity.mass_contact.confirm_before_send', [
'mass_contact_confirm_info' => $message
->uuid(),
]);
}
/**
* Builds the task list at the bottom of the mass contact form.
*
* @param array $form
* The mass contact form definition.
*/
protected function buildTaskList(array &$form) {
if ($this
->currentUser()
->hasPermission('mass contact administer')) {
$tasks = [];
if ($this
->currentUser()
->hasPermission('administer permissions')) {
$tasks[] = Link::createFromRoute($this
->t('Set Mass Contact permissions'), 'user.admin_permissions', [], [
'fragment' => 'module-mass_contact',
])
->toRenderable();
}
$tasks[] = Link::createFromRoute($this
->t('List current categories'), 'entity.mass_contact_category.collection')
->toRenderable();
$tasks[] = Link::createFromRoute($this
->t('Add new category'), 'entity.mass_contact_category.add_form')
->toRenderable();
$tasks[] = Link::createFromRoute($this
->t('Configure Mass Contact settings'), 'mass_contact.settings')
->toRenderable();
$tasks[] = Link::createFromRoute($this
->t('Help'), 'help.page', [
'name' => 'mass_contact',
])
->toRenderable();
$form['tasklist'] = [
'#type' => 'details',
// Open if there are no categories.
'#open' => empty($categories),
'#title' => $this
->t('Related tasks'),
];
$form['tasklist']['tasks'] = [
'#theme' => 'item_list',
'#items' => $tasks,
];
}
}
}
Members
Name | Modifiers | Type | Description | Overrides |
---|---|---|---|---|
ContentEntityForm:: |
protected | property |
The entity being used by this form. Overrides EntityForm:: |
9 |
ContentEntityForm:: |
protected | property | The entity repository service. | |
ContentEntityForm:: |
protected | property | The entity type bundle info service. | |
ContentEntityForm:: |
protected | property | The time service. | |
ContentEntityForm:: |
protected | function | Add revision form fields if the entity enabled the UI. | |
ContentEntityForm:: |
public | function |
Builds an updated entity object based upon the submitted form values. Overrides EntityForm:: |
3 |
ContentEntityForm:: |
protected | function |
Copies top-level form values to entity properties Overrides EntityForm:: |
|
ContentEntityForm:: |
protected | function | Flags violations for the current form. | 4 |
ContentEntityForm:: |
protected | function | Returns the bundle entity of the entity, or NULL if there is none. | |
ContentEntityForm:: |
protected | function | Gets the names of all fields edited in the form. | 4 |
ContentEntityForm:: |
public | function |
Gets the form display. Overrides ContentEntityFormInterface:: |
|
ContentEntityForm:: |
public | function |
Gets the code identifying the active form language. Overrides ContentEntityFormInterface:: |
|
ContentEntityForm:: |
protected | function | Should new revisions created on default. | |
ContentEntityForm:: |
protected | function |
Initializes the form state and the entity before the first form build. Overrides EntityForm:: |
1 |
ContentEntityForm:: |
protected | function | Initializes form language code values. | |
ContentEntityForm:: |
public | function |
Checks whether the current form language matches the entity one. Overrides ContentEntityFormInterface:: |
|
ContentEntityForm:: |
protected | function |
Prepares the entity object before the form is built first. Overrides EntityForm:: |
1 |
ContentEntityForm:: |
public | function |
Sets the form display. Overrides ContentEntityFormInterface:: |
|
ContentEntityForm:: |
protected | function | Checks whether the revision form fields should be added to the form. | |
ContentEntityForm:: |
public | function | Updates the changed time of the entity. | |
ContentEntityForm:: |
public | function | Updates the form language to reflect any change to the entity language. | |
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 | |
EntityForm:: |
protected | property | The name of the current operation. | |
EntityForm:: |
private | property | The entity manager. | |
EntityForm:: |
protected | function | Returns the action form element for the current entity form. | |
EntityForm:: |
public | function | Form element #after_build callback: Updates the entity with submitted data. | |
EntityForm:: |
public | function |
Form constructor. Overrides FormInterface:: |
10 |
EntityForm:: |
public | function |
Returns a string identifying the base form. Overrides BaseFormIdInterface:: |
5 |
EntityForm:: |
public | function |
Gets the form entity. Overrides EntityFormInterface:: |
|
EntityForm:: |
public | function |
Determines which entity will be used by this form from a RouteMatch object. Overrides EntityFormInterface:: |
1 |
EntityForm:: |
public | function |
Returns a unique string identifying the form. Overrides FormInterface:: |
10 |
EntityForm:: |
public | function |
Gets the operation identifying the form. Overrides EntityFormInterface:: |
|
EntityForm:: |
protected | function | Invokes the specified prepare hook variant. | |
EntityForm:: |
public | function | Process callback: assigns weights and hides extra fields. | |
EntityForm:: |
public | function |
Form submission handler for the 'save' action. Overrides EntityFormInterface:: |
41 |
EntityForm:: |
public | function |
Sets the form entity. Overrides EntityFormInterface:: |
|
EntityForm:: |
public | function |
Sets the entity manager for this form. Overrides EntityFormInterface:: |
|
EntityForm:: |
public | function |
Sets the entity type manager for this form. Overrides EntityFormInterface:: |
|
EntityForm:: |
public | function |
Sets the module handler for this form. Overrides EntityFormInterface:: |
|
EntityForm:: |
public | function |
Sets the operation for this form. Overrides EntityFormInterface:: |
|
EntityForm:: |
public | function | ||
EntityForm:: |
public | function | ||
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. | |
MassContactForm:: |
protected | property | The mass contact configuration. | |
MassContactForm:: |
protected | property |
The entity type manager service. Overrides EntityForm:: |
|
MassContactForm:: |
protected | property | The mass contact service. | |
MassContactForm:: |
protected | property |
The module handler service. Overrides EntityForm:: |
|
MassContactForm:: |
public | function |
Returns an array of supported actions for the current entity form. Overrides EntityForm:: |
|
MassContactForm:: |
protected | function | Builds the task list at the bottom of the mass contact form. | |
MassContactForm:: |
public static | function |
Instantiates a new instance of this class. Overrides ContentEntityForm:: |
|
MassContactForm:: |
public | function |
Gets the actual form array to be built. Overrides ContentEntityForm:: |
|
MassContactForm:: |
public | function |
This is the default entity object builder function. It is called before any
other submit handler to build the new entity object to be used by the
following submit handlers. At this point of the form workflow the entity is
validated and the form state… Overrides ContentEntityForm:: |
|
MassContactForm:: |
public | function |
Button-level validation handlers are highly discouraged for entity forms,
as they will prevent entity validation from running. If the entity is going
to be saved during the form submission, this method should be manually
invoked from the button-level… Overrides ContentEntityForm:: |
|
MassContactForm:: |
public | function |
Constructs the Mass Contact form. Overrides ContentEntityForm:: |
|
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. |