I'm getting my objects 'Tasks' from doctrine which contain latitude and longtitude and I use those value to calculate distance from the user to those tasks. The calculated value is not part of the Tasks themselves, because it depends on user's location.
$tasksQ = $entityManager->createQueryBuilder()
->select('p')
->from('App\Entity\Task', 'p');
$tasksQ->orderBy('p.id', 'DESC');
$tasksQ
->addSelect(
'( 6371 * acos(cos(radians(' . $lat . '))' .
'* cos( radians( p.lat ) )' .
'* cos( radians( p.lng )' .
'- radians(' . $lng . ') )' .
'+ sin( radians(' . $lat . ') )' .
'* sin( radians( p.lat ) ) ) ) as distance'
)
->having('distance < :distance')
->setParameter('distance', $radius)
->orderBy('distance', 'ASC');
And here is my paginator:
/* @var $paginator \Knp\Component\Pager\Paginator */
$paginator = $this->get('knp_paginator');
$tasks = $paginator->paginate(
$tasksQ->getQuery()->getArrayResult(),
$request->query->getInt('page', 1), // Which page to open by default
10, // 10 results per page
array('wrap-queries' => true));
if ($radius != null) {
foreach ($tasks as $key => $value) {
$tab = $tasks[$key][0];
$tab['distance'] = $tasks[$key]['distance'];
$tasks[$key] = $tab;
}
}
twig:
<th>{{ knp_pagination_sortable(tasks, 'Id', 'p.id') }}</th>
<th>{{ knp_pagination_sortable(tasks, 'Status', 'p.opened') }}</th>
<th>{{ knp_pagination_sortable(tasks, 'Type', 'p.type') }}</th>
<th>{{ knp_pagination_sortable(tasks, 'Skills required', 'p.skillsReq') }}</th>
<th>{{ knp_pagination_sortable(tasks, 'Reward', 'p.credit') }}</th>
<th>{{ knp_pagination_sortable(tasks, 'Location', 'p.town') }}</th>
{% if tasks[0].distance is defined %}
<th>Distance (km)</th>
{% endif %}
The pagination does not work because of getArrayResult(), KNPpaginator expects pure objects so Task object which does not contain distance. Removing getArrayResult will break on the other hand having the distance in the object.
Maybe there is a different approach to adding a custom field to an object and still having the whole table sortable? I'm looking for any solutions/suggestions