PHP code example of willsprod / ux-datatables

1. Go to this page and download the library: Download willsprod/ux-datatables library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

willsprod / ux-datatables example snippets


$table = new DataTable();

return $this->render('path/to/your/twig', [
    'table' => $table
])

    //App/Controller/UserController.php
    #[Route(name: 'app_user_index', methods: ['GET'])]
    public function index(DataTableBuilderInterface $builder): Response
    {
        $table = $builder->createDataTable('userTable');

        $table->setOptions([
            "columns" => [
                ["title" => 'ID'],
                ["title" => 'Email'],
                ["title" => 'Roles'],
                ["title" => 'Actions'],
            ],
            "ajax" => [
                'url' => $this->generateUrl("app_user_list"),
                'dataSrc' => ''
            ],
            'language' => [
                'url' => 'https://cdn.datatables.net/plug-ins/1.13.7/i18n/fr-FR.json' //use https://datatables.net/plug-ins/i18n/ to find your langage
            ],
            "columnDefs" => [
                [
                    "targets" => [0], // ID column
                    "visible" => false,
                    "searchable" => false,
                ],
                [
                    "targets" => [3], // Actions column
                    "className" => "text-base !font-normal text-slate-600 border-b !border-b-slate-100 !p-1 text-right dt-head-right" // Using tailwind classes - you can install tailwind by using composer 

    #[Route("/api/users", name: 'app_user_list', methods: ['GET'])]
    public function usersList(UserRepository $userRepository): JsonResponse
    {
        $showRoute = "app_user_show";
        $editRoute = "app_user_edit";

        return $this->json($userRepository->findUsers($showRoute, $editRoute));
    }

    //App/Repository/UserRepository
    public function findUsers(string $showRoute, string $editRoute): array
    {

        $qb = $this->createQueryBuilder('u');
        $qb->select('u.id', 'u.email', 'u.roles');

        $result = $qb->getQuery()->getScalarResult();

        return array_map(function ($row) use ($showRoute, $editRoute) {
            return [
                $row['id'],
                $row['email'],
                $row['roles'],
                sprintf(
                    "<a href='%s' class='text-blue-500'>Details</a> | <a href='%s' class='text-green-500'>Edit</a>",
                    $this->urlGenerator->generate($showRoute, ['id' => $row['id']]),
                    $this->urlGenerator->generate($editRoute, ['id' => $row['id']])
                )
            ];
        }, $result);
    }