我正在学习Symfony Framework(版本2.8)。我正在使用knpPaginator来显示我数据库中的所有用户。现在我试图对注册进行排序,但我不能。 这是我项目的图像,直到现在 Users View
当我点击名称(Nombre)过滤器时,会出现此错误 给定的查询
中没有[u]别名的组件请你的帮助 感谢
答案 0 :(得分:0)
配置:
knp_paginator:
page_range: 5 # default page range used in pagination control
default_options:
page_name: page # page query parameter name
sort_field_name: sort # sort field query parameter name
sort_direction_name: direction # sort direction query parameter name
distinct: true # ensure distinct results, useful when ORM queries are using GROUP BY statements
template:
pagination: KnpPaginatorBundle:Pagination:sliding.html.twig # sliding pagination controls template
sortable: KnpPaginatorBundle:Pagination:sortable_link.html.twig # sort link template
控制器:
public function listAction(Request $request)
{
$em = $this->get('doctrine.orm.entity_manager');
$dql = "SELECT a FROM AcmeMainBundle:Article a";
$query = $em->createQuery($dql);
$paginator = $this->get('knp_paginator');
$pagination = $paginator->paginate(
$query, /* query NOT result */
$request->query->getInt('page', 1)/*page number*/,
10/*limit per page*/
);
// parameters to template
return $this->render('AcmeMainBundle:Article:list.html.twig', array('pagination' => $pagination));
}
查看:
{# total items count #}
<div class="count">
{{ pagination.getTotalItemCount }}
</div>
<table>
<tr>
{# sorting of properties based on query components #}
<th>{{ knp_pagination_sortable(pagination, 'Id', 'a.id') }}</th>
<th{% if pagination.isSorted('a.Title') %} class="sorted"{% endif %}> {{ knp_pagination_sortable(pagination, 'Title', 'a.title') }}</th>
<th>{{ knp_pagination_sortable(pagination, 'Release', ['a.date', 'a.time']) }}</th>
</tr>
{# table body #}
{% for article in pagination %}
<tr {% if loop.index is odd %}class="color"{% endif %}>
<td>{{ article.id }}</td>
<td>{{ article.title }}</td>
<td>{{ article.date | date('Y-m-d') }}, {{ article.time | date('H:i:s') }}</td>
</tr>
{% endfor %}
</table>
{# display navigation #}
<div class="navigation">
{{ knp_pagination_render(pagination) }}
</div>
答案 1 :(得分:0)
这是我的代码:
<强> Config.yml 强>
# KnpPaginatorBundle
knp_paginator:
page_range: 5 # default page range used in pagination control
default_options:
page_name: page # page query parameter name
sort_field_name: sort # sort field query parameter name
sort_direction_name: direction # sort direction query parameter name
distinct: true # ensure distinct results, useful when ORM queries are using GROUP BY statements
template:
pagination: KnpPaginatorBundle:Pagination:twitter_bootstrap_v3_pagination.html.twig # sliding pagination controls template
sortable: KnpPaginatorBundle:Pagination:sortable_link.html.twig # sort link template
我的 UserController
<?php
namespace SRQ\UserBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Form\FormError;
use SRQ\UserBundle\Entity\User;
use SRQ\UserBundle\Form\UserType;
class UserController extends Controller
{
public function indexAction(Request $request)
{
$searchQuery = $request->get('query');
if(!empty($searchQuery))
{
$finder = $this->container->get('fos_elastica.finder.app.user');
$users = $finder->createPaginatorAdapter($searchQuery);
}
else
{
$fm = $this->getDoctrine()->getManager();
$dql = "SELECT u FROM SRQUserBundle:User u ORDER BY u.id DESC";
$users = $fm->createQuery($dql);
}
$paginator = $this->get('knp_paginator');
$pagination = $paginator->paginate(
$users, $request->query->getInt('page', 1),
5
);
$deleteFormAjax = $this->createCustomForm(':USER_ID', 'DELETE', 'srq_user_delete');
return $this->render('SRQUserBundle:User:index.html.twig', array('pagination' => $pagination,
'delete_form_ajax' => $deleteFormAjax->createView()));
}
public function addAction()
{
$user = new User();
$form = $this->createCreateForm($user);
return $this->render('SRQUserBundle:User:add.html.twig', array('form' => $form->createView()));
}
private function createCreateForm(User $entity)
{
$form = $this->createForm(new UserType(), $entity, array(
'action' => $this->generateUrl('srq_user_create'),
'method' => 'POST'
));
return $form;
}
public function createAction(Request $request)
{
$user = new User();
$form = $this->createCreateForm($user);
$form->handleRequest($request);
if($form->isValid())
{
$password = $form->get('password')->getData();
$passwordConstraint = new Assert\NotBlank();
$errorList = $this->get('validator')->validate($password, $passwordConstraint);
if(count($errorList) == 0)
{
$encoder = $this->container->get('security.password_encoder');
$encoded = $encoder->encodePassword($user, $password);
$user->setPassword($encoded);
$fm = $this->getDoctrine()->getManager();
$fm->persist($user);
$fm->flush();
$successMessage = $this->get('translator')->trans('The user has been created.');
$this->addFlash('mensaje', $successMessage);
return $this->redirectToRoute('srq_user_index');
}
else
{
$errorMessage = new FormError($errorList[0]->getMessage());
$form->get('password')->addError($errorMessage);
}
}
return $this->render('SRQUserBundle:User:add.html.twig', array('form' =>$form->createView()));
}
public function editAction($id)
{
$fm = $this->getDoctrine()->getManager();
$user = $fm->getRepository('SRQUserBundle:User')->find($id);
if(!$user)
{
$messageException = $this->get('translator')->trans('User not found.');
throw $this->createNotFoundException('$messageException');
}
$form = $this->createEditForm($user);
return $this->render('SRQUserBundle:User:edit.html.twig', array('user' => $user, 'form' => $form->createView()));
}
private function createEditForm(User $entity)
{
$form = $this->createForm(new UserType(), $entity, array('action' => $this->generateUrl('srq_user_update', array('id' => $entity->getId())), 'method' => 'PUT'));
return $form;
}
public function updateAction($id, Request $request)
{
$fm = $this->getDoctrine()->getManager();
$user = $fm->getRepository('SRQUserBundle:User')->find($id);
if(!$user)
{
$messageException = $this->get('translator')->trans('User not found.');
throw $this->createNotFoundException('$messageException');
}
$form = $this->createEditForm($user);
$form ->handleRequest($request);
if($form->isSubmitted() && $form->isValid())
{
$password = $form->get('password')->getData();
if(!empty($password))
{
$encoder = $this->container->get('security.password_encoder');
$encoded = $encoder->encodePassword($user, $password);
$user->setPassword($encoded);
}
else
{
$recoverPass = $this->recoverPass($id);
$user->setPassword($recoverPass[0]['password']);
}
if($form->get('role')->getData() == 'ROLE_ADMIN')
{
$user->setIsActive(1);
}
$fm->flush();
$successMessage = $this->get('translator')->trans('The user has been modified.');
$this->addFlash('mensaje', $successMessage);
return $this->redirectToRoute('srq_user_edit', array('id' => $user->getId()));
}
return $this->render('SRQUserBundle:User:edit.html.twig', array('user' => $user, 'form' => $form->createView()));
}
private function recoverPass($id)
{
$fm = $this->getDoctrine()->getManager();
$query = $fm->createQuery(
'SELECT u.password
FROM SRQUserBundle:User u
WHERE u.id = :id'
)->setParameter('id', $id);
$currentPass = $query->getResult();
return $currentPass;
}
public function viewAction($id)
{
$repository = $this->getDoctrine()->getRepository('SRQUserBundle:User');
$user = $repository->find($id);
if(!$user)
{
$messageException = $this->get('translator')->trans('User not found.');
throw $this->createNotFoundException('$messageException');
}
$deleteForm = $this->createCustomForm($user->getId(), 'DELETE', 'srq_user_delete');
return $this->render('SRQUserBundle:User:view.html.twig', array('user' => $user, 'delete_form' => $deleteForm->createView()));
}
private function createDeleteForm($user)
{
return $this->createFormBuilder()
->setAction($this->generateUrl('srq_user_delete', array('id' => $user->getId())))
->setMethod('DELETE')
->getForm();
}
public function deleteAction(Request $request, $id)
{
$fm = $this->getDoctrine()->getManager();
$user = $fm->getRepository('SRQUserBundle:User')->find($id);
if(!$user)
{
$messageException = $this->get('translator')->trans('User not found.');
throw $this->createNotFoundException('$messageException');
}
$allUsers = $fm->getRepository('SRQUserBundle:User')->findAll();
$countUsers = count($allUsers);
$form = $this->createCustomForm($user->getId(), 'DELETE', 'srq_user_delete');
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid())
{
if($request->isXMLHttpRequest())
{
$res = $this->deleteUser($user->getRole(), $fm, $user);
return new Response(
json_encode(array('removed' => $res['removed'], 'message' => $res['message'], 'countUsers' => $countUsers)),
200,
array('Content-Type' => 'application/json')
);
}
$res = $this->deleteUser($user->getRole(), $fm, $user);
$this->addFlash($res['alert'], $res['message']);
return $this->redirectToRoute('srq_user_index');
}
}
private function deleteUser($role, $fm, $user)
{
if($role == 'ROLE_USER')
{
$fm->remove($user);
$fm->flush();
$message = $this->get('translator')->trans('The user has been deleted.');
$removed = 1;
$alert = 'mensaje';
}
elseif($role == 'ROLE_ADMIN')
{
$message = $this->get('translator')->trans('The user could not be deleted.');
$removed = 0;
$alert = 'error';
}
return array('removed' => $removed, 'message' => $message, 'alert' => $alert);
}
private function createCustomForm($id, $method, $route)
{
return $this->createFormBuilder()
->setAction($this->generateUrl($route, array('id' => $id)))
->setMethod($method)
->getForm();
}
}
我的观看次数/用户/ index.html.twig
{% extends 'layout.html.twig' %}
{% block body %}
{{ parent() }}
{# Progress bar #}
<div class="progress no-border hidden" id="delete-progress">
<div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="45" aria-valuemin="0" aria-valuemax="100" style="width: 100%">
<span class="sr-only">Loading...</span>
</div>
</div>
{{ include('SRQUserBundle:User:messages/success.html.twig') }}
{{ include('SRQUserBundle:User:messages/danger.html.twig') }}
<div class="container">
<div class="col-md-12">
<div class="page-header margin-none">
<h2 class="padding-none">{% trans %} Users {% endtrans %}</h2>
</div>
<div class="table-responsive">
{% trans %} Total records: {% endtrans %} <span id="total">{{ pagination.getTotalItemCount }}</span>
<p>
<form method="get" action="" class="form-inline" role="search">
<div class="form-group">
<input type="text" name="query" value="{{ app.request.get('query') }}" class="form-control" placeholder="{{'Search user'|trans}}" required />
</div>
<input type="submit" value="{{ 'Search'|trans }}" class="btn btn-default">
</form>
{% if not pagination|length %}
<h2>{{ 'No search results'|trans}}</h2>
{% endif %}
{% if pagination|length %}
<br>
<table class="table table-striped table-hover">
<thead>
<tr>
<th> {{ knp_pagination_sortable(pagination, 'Username'|trans, 'u
.username') }}</th>
<th{% if pagination.isSorted('u.firstName') %} class="sorted"{% endif %}>{{ knp_pagination_sortable(pagination, 'First name'|trans, 'u
.firstName') }}</th>
<th> {{ knp_pagination_sortable(pagination, 'Last name'|trans, 'u
.lastName') }} </th>
<th> {{ knp_pagination_sortable(pagination, 'Email'|trans, 'u
.email') }} </th>
<th> {{ knp_pagination_sortable(pagination, 'Role'|trans, 'u
.role') }} </th>
<th> {{ knp_pagination_sortable(pagination, 'Created'|trans, 'u
.createdAt') }} </th>
<th> {{ knp_pagination_sortable(pagination, 'Updated'|trans, 'u
.updatedAt') }} </th>
<th>{{ 'Actions'| trans}}</th>
</tr>
</thead>
<tbody>
{% for user in pagination %}
<tr data-id="{{ user.id }}">
<td>{{ user.username }}</td>
<td>{{ user.firstName }}</td>
<td>{{ user.lastName }}</td>
<td>{{ user.email }}</td>
<td>
{% if user.role == 'ROLE_ADMIN' %}
<strong>
{% trans %} Administrator {% endtrans %}
</strong>
{% elseif user.role == 'ROLE_USER' %}
<strong>
{% trans %} User {% endtrans %}
</strong>
{% endif %}
</td>
<td>{{ user.createdAt|date('d-m-Y H:i') }}</td>
<td>{{ user.updatedAt|date('d-m-Y H:i') }}</td>
<td class="actions">
<a href="{{ path('srq_user_view', { id: user.id }) }}" class="btn btn-sm btn-info">
{{ 'View'|trans }}
</a>
<a href="{{ path('srq_user_edit', { id: user.id }) }}" class="btn btn-sm btn-primary">
{{ 'Edit'|trans }}
</a>
<a href="#" class="btn btn-sm btn-danger btn-delete">
{{ 'Delete'|trans }}
</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endif %}
{# Display navigation #}
<div class="navigation">
{{ knp_pagination_render(pagination) }}
</div>
</div>
</div>
</div>
{{ include('SRQUserBundle:User:forms/form.html.twig', { form: delete_form_ajax, message: 'Are you sure ?'|trans, id: 'form-delete', with_submit: false}) }}
{% endblock %}
{% block javascripts %}
{{ parent() }}
<script src="{{ asset('bundles/srquser/js/delete-user.js') }}"></script>
{% endblock %}
按名称排序 Sort_image
错误讯息:
There is no component aliased by [u
] in the given Query
500 Internal Server Error - UnexpectedValueException
Stack Trace
in vendor/knplabs/knp-components/src/Knp/Component/Pager/Event/Subscriber/Sortable/Doctrine/ORM/Query/OrderByWalker.php at line 54 -
$alias = $aliases[$index];
if ($alias !== false) {
if (!array_key_exists($alias, $components)) {
throw new \UnexpectedValueException("There is no component aliased by [{$alias}] in the given Query");
}
$meta = $components[$alias];
if (!$meta['metadata']->hasField($field)) {
at OrderByWalker ->walkSelectStatement (object(SelectStatement))
in vendor/doctrine/orm/lib/Doctrine/ORM/Query/TreeWalkerChain.php at line 112 +
at TreeWalkerChain ->walkSelectStatement (object(SelectStatement))
in vendor/doctrine/orm/lib/Doctrine/ORM/Query/Parser.php at line 380 +
at Parser ->parse ()
in vendor/doctrine/orm/lib/Doctrine/ORM/Tools/Pagination/Paginator.php at line 260 +
at Paginator ->getCountQuery ()
in vendor/doctrine/orm/lib/Doctrine/ORM/Tools/Pagination/Paginator.php at line 123 +
at Paginator ->count ()
at count (object(Paginator))
in vendor/knplabs/knp-components/src/Knp/Component/Pager/Event/Subscriber/Paginate/Doctrine/ORM/QuerySubscriber/UsesPaginator.php at line 47 +
at UsesPaginator ->items (object(ItemsEvent), 'knp_pager.items', object(TraceableEventDispatcher))
at call_user_func (array(object(UsesPaginator), 'items'), object(ItemsEvent), 'knp_pager.items', object(TraceableEventDispatcher))
in vendor/symfony/symfony/src/Symfony/Component/EventDispatcher/Debug/WrappedListener.php at line 61 +
at WrappedListener ->__invoke (object(ItemsEvent), 'knp_pager.items', object(ContainerAwareEventDispatcher))
at call_user_func (object(WrappedListener), object(ItemsEvent), 'knp_pager.items', object(ContainerAwareEventDispatcher))
in app/cache/dev/classes.php at line 1858 +
at EventDispatcher ->doDispatch (array(object(WrappedListener), object(WrappedListener), object(WrappedListener), object(WrappedListener), object(WrappedListener), object(WrappedListener), object(WrappedListener), object(WrappedListener), object(WrappedListener), object(WrappedListener), object(WrappedListener), object(WrappedListener), object(WrappedListener), object(WrappedListener), object(WrappedListener), object(WrappedListener), object(WrappedListener), object(WrappedListener), object(WrappedListener), object(WrappedListener), object(WrappedListener)), 'knp_pager.items', object(ItemsEvent))
in app/cache/dev/classes.php at line 1773 +
at EventDispatcher ->dispatch ('knp_pager.items', object(ItemsEvent))
in vendor/symfony/symfony/src/Symfony/Component/EventDispatcher/Debug/TraceableEventDispatcher.php at line 140 +
at TraceableEventDispatcher ->dispatch ('knp_pager.items', object(ItemsEvent))
in vendor/knplabs/knp-components/src/Knp/Component/Pager/Paginator.php at line 113 +
at Paginator ->paginate (object(Query), '1', '5')
in src/SRQ/UserBundle/Controller/UserController.php at line 38 +
at UserController ->indexAction (object(Request))
at call_user_func_array (array(object(UserController), 'indexAction'), array(object(Request)))
in vendor/symfony/symfony/src/Symfony/Component/HttpKernel/HttpKernel.php at line 144 +
at HttpKernel ->handleRaw (object(Request), '1')
in vendor/symfony/symfony/src/Symfony/Component/HttpKernel/HttpKernel.php at line 64 +
at HttpKernel ->handle (object(Request), '1', true)
in vendor/symfony/symfony/src/Symfony/Component/HttpKernel/DependencyInjection/ContainerAwareHttpKernel.php at line 69 +
at ContainerAwareHttpKernel ->handle (object(Request), '1', true)
in vendor/symfony/symfony/src/Symfony/Component/HttpKernel/Kernel.php at line 185 +
at Kernel ->handle (object(Request))
in web/app_dev.php at line 32 +
Logs -
1 error
INFO - Matched route "srq_user_index".
INFO - Populated the TokenStorage with an anonymous Token.
DEBUG - Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\DebugHandlersListener::configure".
DEBUG - Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\ProfilerListener::onKernelRequest".
DEBUG - Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\DumpListener::configure".
DEBUG - Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\ValidateRequestListener::onKernelRequest".
DEBUG - Notified event "kernel.request" to listener "Symfony\Bundle\FrameworkBundle\EventListener\SessionListener::onKernelRequest".
DEBUG - Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\FragmentListener::onKernelRequest".
DEBUG - Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\RouterListener::onKernelRequest".
DEBUG - Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\LocaleListener::onKernelRequest".
DEBUG - Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\TranslatorListener::onKernelRequest".
DEBUG - Notified event "kernel.request" to listener "Symfony\Component\Security\Http\Firewall::onKernelRequest".
DEBUG - Notified event "kernel.request" to listener "Knp\Bundle\PaginatorBundle\Subscriber\SlidingPaginationSubscriber::onKernelRequest".
DEBUG - Notified event "kernel.controller" to listener "Symfony\Bundle\FrameworkBundle\DataCollector\RouterDataCollector::onKernelController".
DEBUG - Notified event "kernel.controller" to listener "Symfony\Component\HttpKernel\DataCollector\RequestDataCollector::onKernelController".
DEBUG - Notified event "kernel.controller" to listener "Sensio\Bundle\FrameworkExtraBundle\EventListener\ControllerListener::onKernelController".
DEBUG - Notified event "kernel.controller" to listener "Sensio\Bundle\FrameworkExtraBundle\EventListener\ParamConverterListener::onKernelController".
DEBUG - Notified event "kernel.controller" to listener "Sensio\Bundle\FrameworkExtraBundle\EventListener\HttpCacheListener::onKernelController".
DEBUG - Notified event "kernel.controller" to listener "Sensio\Bundle\FrameworkExtraBundle\EventListener\SecurityListener::onKernelController".
DEBUG - Notified event "kernel.controller" to listener "Sensio\Bundle\FrameworkExtraBundle\EventListener\TemplateListener::onKernelController".
DEBUG - Notified event "knp_pager.before" to listener "Knp\Component\Pager\Event\Subscriber\Sortable\SortableSubscriber::before".
DEBUG - Notified event "knp_pager.before" to listener "Knp\Component\Pager\Event\Subscriber\Filtration\FiltrationSubscriber::before".
DEBUG - Notified event "knp_pager.before" to listener "Knp\Component\Pager\Event\Subscriber\Paginate\PaginationSubscriber::before".
CRITICAL - Uncaught PHP Exception UnexpectedValueException: "There is no component aliased by [u ] in the given Query" at /home/ubuntu/workspace/vendor/knplabs/knp-components/src/Knp/Component/Pager/Event/Subscriber/Sortable/Doctrine/ORM/Query/OrderByWalker.php line 54
DEBUG - Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\DebugHandlersListener::configure".
DEBUG - Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\ProfilerListener::onKernelRequest".
DEBUG - Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\DumpListener::configure".
DEBUG - Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\ValidateRequestListener::onKernelRequest".
DEBUG - Notified event "kernel.request" to listener "Symfony\Bundle\FrameworkBundle\EventListener\SessionListener::onKernelRequest".
DEBUG - Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\FragmentListener::onKernelRequest".
DEBUG - Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\RouterListener::onKernelRequest".
DEBUG - Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\LocaleListener::onKernelRequest".
DEBUG - Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\TranslatorListener::onKernelRequest".
DEBUG - Notified event "kernel.request" to listener "Symfony\Component\Security\Http\Firewall::onKernelRequest".
DEBUG - Notified event "kernel.request" to listener "Knp\Bundle\PaginatorBundle\Subscriber\SlidingPaginationSubscriber::onKernelRequest".
DEBUG - Notified event "kernel.controller" to listener "Symfony\Bundle\FrameworkBundle\DataCollector\RouterDataCollector::onKernelController".
DEBUG - Notified event "kernel.controller" to listener "Symfony\Component\HttpKernel\DataCollector\RequestDataCollector::onKernelController".
DEBUG - Notified event "kernel.controller" to listener "Sensio\Bundle\FrameworkExtraBundle\EventListener\ControllerListener::onKernelController".
DEBUG - Notified event "kernel.controller" to listener "Sensio\Bundle\FrameworkExtraBundle\EventListener\ParamConverterListener::onKernelController".
DEBUG - Notified event "kernel.controller" to listener "Sensio\Bundle\FrameworkExtraBundle\EventListener\HttpCacheListener::onKernelController".
DEBUG - Notified event "kernel.controller" to listener "Sensio\Bundle\FrameworkExtraBundle\EventListener\SecurityListener::onKernelController".
DEBUG - Notified event "kernel.controller" to listener "Sensio\Bundle\FrameworkExtraBundle\EventListener\TemplateListener::onKernelController".
Stack Trace (Plain Text)