MessageMultipleDeleteForm.php in Message UI 8
File
src/Form/MessageMultipleDeleteForm.php
View source
<?php
namespace Drupal\message_ui\Form;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class MessageMultipleDeleteForm extends FormBase {
protected $entityTypeManager;
protected $moduleHandler;
public function __construct(EntityTypeManagerInterface $entity_type_manager, ModuleHandlerInterface $module_handler) {
$this->entityTypeManager = $entity_type_manager;
$this->moduleHandler = $module_handler;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('entity_type.manager'), $container
->get('module_handler'));
}
public function getFormId() {
return 'message_multiple_delete_form';
}
public function buildForm(array $form, FormStateInterface $form_state) {
$templates = $this->entityTypeManager
->getStorage('message_template')
->loadMultiple();
$options = [];
foreach ($templates as $template) {
$options[$template
->id()] = $template
->label();
}
$form['message_templates'] = [
'#type' => 'select',
'#title' => $this
->t('Message types'),
'#description' => $this
->t('Select which message templates you to delete at once'),
'#options' => $options,
'#size' => 5,
'#multiple' => TRUE,
];
$form['submit'] = [
'#type' => 'submit',
'#value' => $this
->t('Submit'),
];
return $form;
}
public function submitForm(array &$form, FormStateInterface $form_state) {
$templates = $form_state
->getValue('message_templates');
$query = $this->entityTypeManager
->getStorage('message')
->getQuery()
->condition('template', $templates, 'IN');
$this->moduleHandler
->alter('message_ui_multiple_message_delete_query', $query);
$messages = $query
->execute();
$chunks = array_chunk($messages, 250);
$operations = [];
foreach ($chunks as $chunk) {
$operations[] = [
'\\Drupal\\message_ui\\Form\\MessageMultipleDeleteForm::deleteMessages',
[
$chunk,
],
];
}
$batch = [
'title' => $this
->t('Deleting messages'),
'operations' => $operations,
'finished' => '\\Drupal\\message_ui\\Form\\MessageMultipleDeleteForm::deleteMessagesFinish',
];
batch_set($batch);
}
public static function deleteMessages(array $mids, array &$sandbox) {
$messages = \Drupal::entityTypeManager()
->getStorage('message')
->loadMultiple($mids);
$sandbox['message'] = t('Deleting messages between @start ot @end', [
'@start' => reset($mids),
'@end' => end($mids),
]);
\Drupal::entityTypeManager()
->getStorage('message')
->delete($messages);
}
public static function deleteMessagesFinish() {
\Drupal::messenger()
->addMessage(t('The messages were deleted.'));
}
}