SendApplicantEmailAction.php
Thu Sep 29 2022 17:35:11 GMT+0000 (Coordinated Universal Time)
<?php
namespace Drupal\pos_entity_email_template\Plugin\Action;
use Drupal\Component\Utility\Crypt;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Action\ConfigurableActionBase;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\RemoveCommand;
use Drupal\Core\Ajax\ReplaceCommand;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Site\Settings;
use Drupal\file\Entity\File;
/**
* Provides a a Send Applicant email action.
*
* @Action(
* id = "send_applicant_email",
* label = @Translation("Send Applicant email"),
* type = "user",
* category = @Translation("Custom"),
* confirm = TRUE
* )
*
* @DCG
* For a simple updating entity fields consider extending FieldUpdateActionBase.
*/
class SendApplicantEmailAction extends ConfigurableActionBase {
/**
* {@inheritdoc}
*/
public function defaultConfiguration() {
return [
'title' => '',
'body' => '',
'attachment_files' => [],
];
}
/**
* {@inheritdoc}
*/
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
//@todo: Check which templates will be available for this kind of e-mails. Maybe create a new type of templates.
$templates = \Drupal::entityTypeManager()
->getStorage('pos_entity_email_template')->loadMultiple();
$options = ['_none' => $this->t('None')];
foreach ($templates as $template) {
$options[$template->id()] = $template->id() . ') ' . $template->label();
}
ksort($options, SORT_NUMERIC);
$form['template'] = [
'#type' => 'select',
'#title' => $this->t('Template'),
'#options' => $options,
'#ajax' => [
'callback' => '\Drupal\pos_entity_email_template\Plugin\Action\SendApplicantEmailAction::replaceElements'
]
];
$form['title'] = [
'#title' => $this->t('Title'),
'#type' => 'textfield',
'#wrapper_attributes' => [
'class' => 'mrmot-title',
],
];
$form['body'] = [
'#type' => 'text_format',
'#title' => $this->t('Body'),
'#format' => 'ckeditor_5',
'#wrapper_attributes' => [
'class' => 'mrmot-body',
],
];
$form['attachment_files'] = [
'#type' => 'managed_file',
'#title' => $this->t('Attachments'),
'#description' => t('Allowed types: pdf xls xlsx odt doc docx.'),
'#upload_validators' => [
'file_validate_extensions' => ['pdf xls xlsx odt doc docx'],
],
'#upload_location' => 'public://email_attachments/',
'#progress_indicator' => 'bar',
'#multiple' => TRUE,
'#wrapper_attributes' => [
'class' => 'mrmot',
],
];
return $form;
}
/**
* {@inheritdoc}
*/
public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
$this->configuration['title'] = $form_state->getValue('title');
$this->configuration['body'] = $form_state->getValue('body')['value'];
$this->configuration['file_ids'] = $form_state->getValue('attachment_files');
foreach ($form_state->getValue('attachment_files') as $fid) {
$file = File::load($fid);
$this->configuration['attachments'][] = [
'filepath' => $file->getFileUri(),
'filename' => $file->getFilename(),
'filemime' => $file->getMimeType(),
];
}
}
/**
* {@inheritdoc}
*/
public function access($node, AccountInterface $account = NULL, $return_as_object = FALSE) {
return $return_as_object ? AccessResult::allowedIfHasPermission($account, 'send emails from administration') : $account->hasPermission('send emails from administration');
}
/**
* {@inheritdoc}
*/
public function execute($user = NULL) {
$params['headers'] = [
'Content-Type' => 'text/html; charset=UTF-8;',
'Content-Transfer-Encoding' => '8Bit',
];
/** @var \Drupal\Core\Mail\MailManagerInterface $mail_manager */
$mail_manager = \Drupal::service('plugin.manager.mail');
$user_mail = $user->getEmail();
$emails = [$user_mail];
$params['title'] = $this->configuration['title'];
$params['message'] = $this->configuration['body'];
$params['file_ids'] = $this->configuration['file_ids'];
$params['attachments'] = $this->configuration['attachments'];
$params['entity'] = $user;
$result = $mail_manager->mail('pos_entity_applicant', 'pos_entity_applicant_mail_send', implode(',', $emails), 'hu', $params, NULL, TRUE);
}
public static function replaceElements(array &$form, FormStateInterface $form_state) {
// @todo: Check what kind of templates will be used.
$triggering_element = $form_state->getTriggeringElement();
$response = new AjaxResponse();
/** @var \Drupal\pos_entity_email_template\Entity\EmailTemplateEntity $email_template */
if (is_numeric($triggering_element['#value'])) {
$email_template = \Drupal::entityTypeManager()
->getStorage('pos_entity_email_template')
->load($triggering_element['#value']);
$form['title']['#value'] = $email_template->getTitle();
$form['body']['value']['#value'] = $email_template->getBody();
$form['attachment_files']['#value']['fids'] = array_unique(array_merge($form['attachment_files']['#value']['fids'], $email_template->getAttachmentsInElementFormat()));
$form['attachment_files']['fids']['#value'] = array_unique(array_merge($form['attachment_files']['fids']['#value'], $email_template->getAttachmentsInElementFormat()));
foreach ($form['attachment_files']['#value']['fids'] as $fid) {
$form['attachment_files']['#files'][$fid] = File::load($fid);
}
$element = &$form['attachment_files'];
foreach ($element['#files'] as $delta => $file) {
$file_link = [
'#theme' => 'file_link',
'#file' => $file,
];
if ($element['#multiple']) {
$element['file_' . $delta]['selected'] = [
'#type' => 'checkbox',
'#title' => \Drupal::service('renderer')->renderPlain($file_link),
];
}
else {
$element['file_' . $delta]['filename'] = $file_link + ['#weight' => -10];
}
// Anonymous users who have uploaded a temporary file need a
// non-session-based token added so $this->valueCallback() can check
// that they have permission to use this file on subsequent submissions
// of the same form (for example, after an Ajax upload or form
// validation error).
if ($file->isTemporary() && \Drupal::currentUser()->isAnonymous()) {
$element['file_' . $delta]['fid_token'] = [
'#type' => 'hidden',
'#value' => Crypt::hmacBase64('file-' . $delta, \Drupal::service('private_key')->get() . Settings::getHashSalt()),
];
}
}
$form_state->setRebuild(TRUE);
}
else {
$form['title']['#value'] = '';
$form['body']['value']['#value'] = '';
}
$response->addCommand(new RemoveCommand('[id^=edit-body-format]'));
$response->addCommand(new ReplaceCommand('.mrmot-body', $form['body']));
$response->addCommand(new ReplaceCommand('.mrmot-title', $form['title']));
$response->addCommand(new ReplaceCommand('.mrmot', $form['attachment_files']));
return $response;
}
}



Comments