Skip to main content

Drupal 8: How to build an entity query from the url query params

This is a snippet on how to build a custom drupal entity database query that fetches the nodes you want from the database based on custom selection criteria.

    $request_params = \Drupal::request()->query->all();
    // for example my_custom_path?arg1=1&arg2=3&arg3=15 will return an array with arg1 => 1, arg2 => 3 etc
    if (!empty($request_params)) {

      $entity = \Drupal::entityTypeManager()->getStorage('node');
      $query = $entity->getQuery();
      $query->condition('type', 'bundle');
      $query->condition('status', 1);

      foreach ($request_params as $key => $arr) {

        if ($key === 'node_id') {
          $query->condition('field_node_ref',array_keys($arr),'IN');
        }

        if ($key === 'entity_id') {
          $query->condition('field_entity_ref',array_keys($arr),'IN');
        }

        if ($key === 'multiple_value_field') {
          $query->condition('field_multiple_value',array_keys($arr),'IN');
        }

        if ($key === 'field_with_extra_values') {
           $query->condition('field_with_extra_values.starthours', $arr, '<=');
        }

        if ($key === 'field_with_extra_values') {
           $query->condition('field_with_extra_values.endhours', $arr, '>=');
        }

      }
     
      //Get only 4 of them
      $query->range(0,4);

      //sort by DESC custom field value
      $query->sort('field_custom_integer','DESC');

      //most recent
      $query->sort('created','DESC');

      $ids = $query->execute();
   
    }

 

 

entity query