2
<?php

namespace Drupal\drupal_block\Controller;


use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Database\Connection;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Database\Query\PagerSelectExtender;

class DrupalBlockController extends ControllerBase {
  protected $connection;

  public function __construct(Connection $connection) {
      $this->connection = $connection;
  }

  public static function create(ContainerInterface $container)
  {
      return new static(
          $container ->get('database')
      );
  }


  public function mymodule()
  {
    $data = $this->connection->select('custom_table', 'ct')
      ->fields('ct', ['name', 'lastname', 'sexo', 'email']);


  $pager = $data->extend(PagerSelectExtender::class)->limit(5);
      //$pager->setCurrentPage($page);
      $data = $pager->execute()->fetchAll();
      $rows = array();

      foreach ($data as $row){
        $rows[] = [
          'name' => $row->name,
          'lastname' => $row->lastname,
          'sexo' => $row->sexo,
          'email' => $row->email,
        ];
      }


    return [
      '#theme' => 'table',
      '#pager' => [
        '#type' =>'pager'
      ],
      '#header' => [
        $this->t('Name'),
        $this->t('Last Name'),
        $this->t('Gender'),
        $this->t('Email')
      ],
      '#rows' => $rows,
      ];
      }
    }

enter image description here

0

1 Answer 1

1

This:

return [
  '#theme' => 'table',
  '#pager' => [
    '#type' =>'pager'
  ],
  '#header' => [
    $this->t('Name'),
    $this->t('Last Name'),
    $this->t('Gender'),
    $this->t('Email')
  ],
  '#rows' => $rows,
];

Should be this:

return [
  'pager' => [
    '#type' =>'pager'
  ],
  'table' => [
    '#theme' => 'table',
    '#header' => [
      $this->t('Name'),
      $this->t('Last Name'),
      $this->t('Gender'),
      $this->t('Email')
    ],
    '#rows' => $rows,
  ],
];

  1. Elements with hashtag prefixes are not rendered, they are metadata. So the hashtag needs to be removed from the array key.
  2. The pager needs to be a separate render array from the table.

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