Skip to content

Instantly share code, notes, and snippets.

@akovalyov
Created June 4, 2013 12:49
Show Gist options
  • Save akovalyov/5705639 to your computer and use it in GitHub Desktop.
Save akovalyov/5705639 to your computer and use it in GitHub Desktop.
filtering function for collections of objects for twig
use Doctrine\Common\Collections\Collection;
use Symfony\Component\PropertyAccess\PropertyAccess;
public function getFilters()
{
return array(
'sortCollection' => new \Twig_Filter_Method($this, 'sortCollection'),
);
}
public function sortCollection(Collection $collection, $column, $direction = 'ASC')
{
$iterator = $collection->getIterator();
$accessor = PropertyAccess::createPropertyAccessor();
$iterator->uasort(function ($first, $second) use ($accessor, $column, $direction) {
if ($direction == 'ASC') {
return ((int)$accessor->getValue($first, $column) > (int)$accessor->getValue($second, $column) ? 1 : -1);
} else {
return ((int)$accessor->getValue($first, $column) < (int)$accessor->getValue($second, $column) ? 1 : -1);
}
});
return $iterator;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment