Thực hiện query lấy hết bảng dữ liệu không cần phân quyền trong Drupal 8
// $node = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple();
Nếu cần phân quyền thì thực hiện câu Query sau
$query = \Drupal::entityQuery('node')
->accessCheck(FALSE)
Sau đây là 1 ví dụ cụ thể
public function my_requests() {
//load the current user details
$user= User::load(\Drupal::currentUser()->id());
$user_id = \Drupal::currentUser()->id();
//Query the database
$query = \Drupal::entityQuery('node')
->tableSort($header)
->condition('status', 1)
->condition('type', "forward_proxy_request")
->condition('uid', $user_id)
->sort('nid' , 'ASC');
$table_sort = $query->extend('Drupal\Core\Database\Query\TableSortExtender')->orderByHeader($header);
$pager = $table_sort->extend('Drupal\Core\Database\Query\PagerSelectExtender')->limit(10);
$nids = $pager->execute();
//creates the table header
$header = [
'Node id',
'title',
'Name',
'Ip',
'SLU',
];
foreach ($nids as $nid) {
$node = Node::load($nid);
$row = [
'data' => [
$node->nid->value,
$node->title->value,
$node->field_p_name[0]->value,
$node->field_ip[0]->value,
$node->field_p_slu[0]->value,
],
];
$rows[] = $row;
}
//Build the table
$build = [
'table' => [
'#prefix' => '<h1>My Requests</h1>',
'#theme' => 'table',
'#attributes' => [
'data-striping' => 0
],
'#header' => $header,
'#rows' => $rows,
],
];
//for pagination
$build['pager'] = array(
'#type' => 'pager'
);
return $build;
It shows a plain table without any style.
Here is an example of sortable table with pagination.
$header = [
'id' => [
'data' => $this->t('ID'),
'specifier' => 'nid',
],
'title' => [
'data' => $this->t('Title'),
'specifier' => 'title',
],
'created' => [
'data' => $this->t('Created'),
'specifier' => 'created',
// Set default sort criteria.
'sort' => 'desc',
],
'uid' => [
'data' => $this->t('Author'),
'specifier' => 'uid',
],
];
$storage = \Drupal::entityTypeManager()->getStorage('node');
$query = $storage->getQuery();
$query->condition('status', \Drupal\node\NodeInterface::PUBLISHED);
$query->condition('type', 'article');
$query->tableSort($header);
// Default value is 10.
$query->pager(15);
$nids = $query->execute();
$date_formatter = \Drupal::service('date.formatter');
$rows = [];
foreach ($storage->loadMultiple($nids) as $node) {
$row = [];
$row[] = $node->id();
$row[] = $node->toLink();
$created = $node->get('created')->value;
$row[] = [
'data' => [
'#theme' => 'time',
'#text' => $date_formatter->format($created),
'#attributes' => [
'datetime' => $date_formatter->format($created, 'custom', \DateTime::RFC3339),
],
],
];
$row[] = [
'data' => $node->get('uid')->view(),
];
$rows[] = $row;
}
$build['table'] = [
'#type' => 'table',
'#header' => $header,
'#rows' => $rows,
'#empty' => $this->t('No content has been found.'),
];
$build['pager'] = [
'#type' => 'pager',
];
Bình luận (0)
Add Comment