Enqueuing items programmaticallyfor Drupal 8 , 9 , 10 , and 11

Last updated :  

Introduction

Building on our previous lesson on defining a queue for background tasks in Drupal, our next step is to explore how to enqueue these tasks programmatically. This process allows you to dynamically add items to the queue based on certain conditions or events within your Drupal application. Whether you're processing form submissions or handling batch operations, programmatically adding items to a queue is a powerful technique in Drupal module development.

Understanding the Enqueuing Process

Enqueuing involves adding data or tasks to a queue that are processed asynchronously. By controlling how and when items enter the queue, you can manage system resources more effectively and ensure tasks do not interfere with user experience.

Steps to Enqueue Items Programmatically

Let's walk through the steps necessary to enqueue items in a queue. We will continue using our hypothetical module mymodule, which manages specific tasks through a queue named mymodule_some_task.

Step 1: Access the Queue Service

To enqueue items, we first need to access the queue service. This is done using Drupal's service container:

php
// Getting the queue service
$queue = \Drupal::service('queue')->get('mymodule_some_task');

Step 2: Prepare the Data

The next step is to prepare the data you'd like to enqueue. This data will be specific to the operation you aim to perform inside the queue worker. Assume we want to add user IDs for processing in the queue:

php
$data = [
  'uid' => $user->id(),
  'operation' => 'processUser'
];

Step 3: Enqueue the Data

Now that you have the queue service and the data ready, you can add this data to the queue using the createItem() method:

php
$queue->createItem($data);

Explanation:

This method takes the data array you prepared and adds it as a task to be processed by the queue worker. Each time you call createItem, a new task is added to the queue, ready to be processed according to the conditions you've defined.

Integrating Enqueuing with Your Module

Typically, you will enqueue items in response to specific events within your module. For instance, you might trigger enqueuing when a form is submitted or when an entity is saved:

Example Use Case: Enqueue on Form Submission

Assuming you have a form that collects user details and you need to process them in the background, you could enqueue tasks as follows:

php
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class ExampleForm extends FormBase {

  public function getFormId() {
    return 'example_form';
  }

  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['username'] = [
      '#type' => 'textfield',
      '#title' => t('Username'),
      '#required' => TRUE,
    ];

    $form['actions']['#type'] = 'actions';
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Submit'),
    ];

    return $form;
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    $user_id = $this->getUserIdFromUsername($form_state->getValue('username'));

    if ($user_id) {
      $data = [
        'uid' => $user_id,
        'operation' => 'processUser'
      ];

      // Enqueue the task.
      \Drupal::service('queue')->get('mymodule_some_task')->createItem($data);
    }
  }

  private function getUserIdFromUsername($username) {
    // Logic to get user ID from username.
    return 1; // Placeholder for example.
  }
}

Review and Test Your Code

After integrating enqueuing functionality, ensure your logic is correct by adding test tasks to the queue and checking that they are processed as expected. Monitor the performance and observe the logs to ensure tasks are added and processed correctly.

Conclusion

By programmatically enqueuing items, you extend your Drupal module's capability to handle tasks asynchronously, improving the performance and responsiveness of your website. Mastering this feature enables you to manage background tasks efficiently, keeping your application scalable and responsive.

In the next lesson, we'll move forward to explore how to create a queue worker plugin, diving deeper into customizing how your queued tasks are processed. Stay with us as we continue to build more robust, feature-rich Drupal modules!