Prepare table:
$table = [
'#type' => 'table',
'#header' => [
'id' => $this->t('Id'),
'title' => $this->t('Title'),
'links' => '',
],
'#rows' => [],
];
For example we might display query results in a table:
$query = \Drupal::database()->select(...);
$results = $query->execute()->fetchAll();
Loop through results and add a new table row for each one of them, with image edit
and delete
links opening relevant pages in modal popup:
foreach ($results as $result) {
$row['id'] = $result->id;
$row['title'] = $result->title;
$linkOptions = [
// Display the target page in a modal popup.
'attributes' => [
'class' => ['use-ajax'],
'data-dialog-type' => 'modal',
'data-dialog-options' => Json::encode(['width' => '80%']),
],
// Redirect back to current page after submitting the modal form.
'query' => [
'destination' => \Drupal::service('path.current')->getPath(),
],
];
$row['links']['data'] = [
'container' => [
'edit_link' => [
'#type' => 'link',
'#url' => Url::fromRoute('entity.MYENTITY.edit_form', [
'MYENTITY' => $result->id,
], $linkOptions),
'#title' => [
'#theme' => 'image',
'#uri' => \Drupal::service('module_handler')
->getModule('MYMODULE')
->getPath() . '/images/icons/edit.svg',
'#width' => 16,
'#height' => 16,
],
],
'delete_link' => [
'#type' => 'link',
'#url' => Url::fromRoute('entity.MYENTITY.delete_form', [
'MYENTITY' => $result->id,
], $linkOptions),
'#title' => [
'#theme' => 'image',
'#uri' => \Drupal::service('module_handler')
->getModule('MYMODULE')
->getPath() . '/images/icons/delete.svg',
'#width' => 16,
'#height' => 16,
],
],
],
'#attached' => ['library' => ['core/drupal.dialog.ajax']]
];
$table['#rows'][] = $row;
}