function CronExampleForm::addItems

Same name in other branches
  1. 4.0.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

modules/cron_example/src/Form/CronExampleForm.php, line 233

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']);
    $request_time = $this->time
        ->getRequestTime();
    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));
}