Я пытаюсь работать с таблицами данных в соответствии с этим руководством (https://github.com/webinarium/DataTablesBundle/wiki),, но у меня есть некоторые проблемы:
SRC / контроллер / DataTableController.php
<?php
namespace App\Controller;
use DataTables\DataTablesInterface;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Routing\Annotation\Route;
/**
*
* @Route("/users", name="users")
*
* @param Request $request
* @param DataTablesInterface $datatables
* @return JsonResponse
*/
class DataTableController extends Controller
{
const ID = 'users';
public function usersAction(Request $request, DataTablesInterface $datatables): JsonResponse
{
try {
// Tell the DataTables service to process the request,
// specifying ID of the required handler.
$results = $datatables->handle($request, 'users');
return $this->json($results);
}
catch (HttpException $e) {
// In fact the line below returns 400 HTTP status code.
// The message contains the error description.
return $this->json($e->getMessage(), $e->getStatusCode());
}
}
}
ЦСИ / DataTables / UsersDataTable.php
<?php
use DataTables\DataTableHandlerInterface;
use DataTables\DataTableQuery;
use DataTables\DataTableResults;
use Symfony\Bridge\Doctrine\RegistryInterface;
class UsersDataTable implements DataTableHandlerInterface
{
protected $doctrine;
/**
* Dependency Injection constructor.
*
* @param RegistryInterface $doctrine
*/
public function __construct(RegistryInterface $doctrine)
{
$this->doctrine = $doctrine;
}
/**
* {@inheritdoc}
*/
public function handle(DataTableQuery $request): DataTableResults
{
/** @var \Doctrine\ORM\EntityRepository $repository */
$repository = $this->doctrine->getRepository('AppBundle:User');
$results = new DataTableResults();
// Total number of users.
$query = $repository->createQueryBuilder('u')->select('COUNT(u.id)');
$results->recordsTotal = $query->getQuery()->getSingleScalarResult();
// Query to get requested entities.
$query = $repository->createQueryBuilder('u');
// Search.
if ($request->search->value) {
$query->where('(LOWER(u.username) LIKE :search OR' .
' LOWER(u.email) LIKE :search)');
$query->setParameter('search', strtolower("%{$request->search->value}%"));
}
// Filter by columns.
foreach ($request->columns as $column) {
if ($column->search->value) {
$value = strtolower($column->search->value);
// "ID" column
if ($column->data == 0) {
$query->andWhere('u.id = :id');
$query->setParameter('id', intval($value));
}
// "Username" column
elseif ($column->data == 1) {
$query->andWhere('LOWER(u.username) LIKE :username');
$query->setParameter('username', "%{$value}%");
}
// "Email" column
elseif ($column->data == 2) {
$query->andWhere('LOWER(u.email) LIKE :email');
$query->setParameter('email', "%{$value}%");
}
}
}
// Order.
foreach ($request->order as $order) {
// "ID" column
if ($order->column == 0) {
$query->addOrderBy('u.id', $order->dir);
}
// "Username" column
elseif ($order->column == 1) {
$query->addOrderBy('u.username', $order->dir);
}
// "Email" column
elseif ($order->column == 2) {
$query->addOrderBy('u.email', $order->dir);
}
}
// Get filtered count.
$queryCount = clone $query;
$queryCount->select('COUNT(u.id)');
$results->recordsFiltered = $queryCount->getQuery()->getSingleScalarResult();
// Restrict results.
$query->setMaxResults($request->length);
$query->setFirstResult($request->start);
/** @var \AppBundle\Entity\User[] $users */
$users = $query->getQuery()->getResult();
foreach ($users as $user) {
$results->data[] = [
$user->getId(),
$user->getUsername(),
$user->getEmail(),
];
}
return $results;
}
}
конфиг / services.yaml
parameters:
locale: 'en'
services:
# default configuration for services in *this* file
_defaults:
autowire: true # Automatically injects dependencies in your services.
autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.
public: false # Allows optimizing the container by removing unused services; this also means
# fetching services directly from the container via $container->get() won't work.
# The best practice is to be explicit about your dependencies anyway.
# makes classes in src/ available to be used as services
# this creates a service per class whose id is the fully-qualified class name
App\:
resource: '../src/*'
exclude: '../src/{Entity,Migrations,Tests,Kernel.php}'
# controllers are imported separately to make sure services can be injected
# as action arguments even if you don't extend any base controller class
App\Controller\:
resource: '../src/Controller'
tags: ['controller.service_arguments']
# add more service definitions when explicit configuration is needed
# please note that last definitions always *replace* previous ones
datatable.users:
class: AppBundle\DataTables\UsersDataTable
tags: [{ name: datatable, id: users }]
arguments: [ '@doctrine' ]
Я получаю сообщение об ошибке: