2

I need to use an entity query such as this:

$query = \Drupal::entityQuery('node')
->condition('type', 'blog_post')
->sort('field');

$nids = $query->execute();

to make a table that is sortable in a custom module . I found instructions on how to do this with a normal query , (below) how can I make this work for this entity query

  $header = array(
  // We make it sortable by name.
  array('data' => $this->t('Name'), 'field' => 'name', 'sort' => 'asc'),
  array('data' => $this->t('Content')),
);

$db = \Drupal::database();
$query = $db->select('config','c');
$query->fields('c', array('name'));
// The actual action of sorting the rows is here.
$table_sort = $query->extend('Drupal\Core\Database\Query\TableSortExtender')
                    ->orderByHeader($header);
// Limit the rows to 20 for each page.
$pager = $table_sort->extend('Drupal\Core\Database\Query\PagerSelectExtender')
                    ->limit(20);
$result = $pager->execute();

// Populate the rows.
$rows = array();
foreach($result as $row) {
  $rows[] = array('data' => array(
    'name' => $row->name,
    'content' => '[BLOB]', // This hardcoded [BLOB] is just for display purpose only.
  ));
}

// The table description.
$build = array(
  '#markup' => t('List of All Configurations')
);

// Generate the table.
$build['config_table'] = array(
  '#theme' => 'table',
  '#header' => $header,
  '#rows' => $rows,
);

// Finally add the pager.
$build['pager'] = array(
  '#type' => 'pager'
);

return $build;

} }

2 Answers 2

1

EntityQuery doesn't appear to have the extend() function that this example relies on, so much of what's happening in the example will need to be done manually.

You can get the sort parameters from the request object

$sort_field = \Drupal::request()->query->get('order');
$sort_order = \Drupal::request()->query->get('sort');

With those, you can update your query to something like.

$query = \Drupal::entityQuery('node')
  ->condition('type', 'blog_post')
  ->sort($sort_field, $sort_direction);
$nids = $query->execute();
$nodes = \Drupal\node\Entity\Node::loadMultiple($nids);

Then use $nodes to build your $rows array as in the example.

0

EntityQuery have a tableSort() method that you can use to update the sorting from the URL parameters.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.