You are here

public function CronExampleForm::addItems in Examples for Developers 8

Same name and namespace in other branches
  1. 3.x modules/cron_example/src/Form/CronExampleForm.php \Drupal\cron_example\Form\CronExampleForm::addItems()

Add the items to the queue when signaled by the form.

File

cron_example/src/Form/CronExampleForm.php, line 210

Class

CronExampleForm
Form with examples on how to use cron.

Namespace

Drupal\cron_example\Form

Code

public function addItems(array &$form, FormStateInterface &$form_state) {
  $values = $form_state
    ->getValues();
  $queue_name = $form['cron_queue_setup']['queue'][$values['queue']]['#title'];
  $num_items = $form_state
    ->getValue('num_items');

  // Queues are defined by a QueueWorker Plugin which are selected by their
  // id attritbute.
  // @see \Drupal\cron_example\Plugin\QueueWorker\ReportWorkerOne
  $queue = $this->queue
    ->get($values['queue']);
  for ($i = 1; $i <= $num_items; $i++) {

    // Create a new item, a new data object, which is passed to the
    // QueueWorker's processItem() method.
    $item = new \stdClass();
    $item->created = REQUEST_TIME;
    $item->sequence = $i;
    $queue
      ->createItem($item);
  }
  $args = [
    '%num' => $num_items,
    '%queue' => $queue_name,
  ];
  $this
    ->messenger()
    ->addMessage($this
    ->t('Added %num items to %queue', $args));
}