You are here

public function BulkDeleteForm::submitForm in Bulk Delete 8

Form submission handler.

Parameters

array $form: An associative array containing the structure of the form.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.

Overrides FormInterface::submitForm

File

src/Form/BulkDeleteForm.php, line 95

Class

BulkDeleteForm
BackupDatabaseForm class.

Namespace

Drupal\bulkdelete\Form

Code

public function submitForm(array &$form, FormStateInterface $form_state) {
  $values = $form_state
    ->getValues();
  $types = array_filter($values['types']);
  if (count($types) > 0) {
    try {
      foreach ($types as $bundle) {
        $result = $this->database
          ->select('node');
        $query = $result
          ->fields('node', [
          'nid',
        ]);
        $query = $result
          ->condition('type', $bundle);
        $query = $result
          ->execute()
          ->fetchAll();
        $last_row = count($query);
        $operations = [];
        if (!empty($last_row)) {
          $message = t('All nodes of type @content mark for deletion', [
            '@content' => $bundle,
          ]);
          \Drupal::logger('bulkdelete')
            ->notice($message);

          // Create batch of 20 nodes.
          $count = 1;
          foreach ($query as $row) {
            $nids[] = $row->nid;
            if ($count % 20 === 0 || $count === $last_row) {
              $operations[] = [
                [
                  get_class($this),
                  'processBatch',
                ],
                [
                  $nids,
                ],
              ];
              $nids = [];
            }
            ++$count;
          }

          // Set up the Batch API.
          $batch = [
            'operations' => $operations,
            'finished' => [
              get_class($this),
              'bulkDeleteFinishedBatch',
            ],
            'title' => $this
              ->t('Node bulk delete'),
            'init_message' => $this
              ->t('Starting nodes deletion.'),
            'progress_message' => $this
              ->t('Completed @current step of @total.'),
            'error_message' => $this
              ->t('Bulk node deletion has encountered an error.'),
          ];
          batch_set($batch);
        }
      }
    } catch (Exception $e) {
      foreach ($e
        ->getErrors() as $error_message) {
        $this
          ->messenger()
          ->addError($error_message);
      }
    }
  }
}