Twig extension for sorting Doctrine ArrayCollection

点点圈 提交于 2019-12-11 10:35:24

问题


I'm trying to write a Twig filter to be able to sort a Doctrine ArrayCollection, but the returned array is not sorted :( Can you please help me to fix this:

class SortExtension extends \Twig_Extension
{ 

    public function getFilters()
    {
        return array(
            new \Twig_SimpleFilter('sortby', array($this, 'sortByFilter')),
        );
    }

    public function sortbyname( $a, $b )
    {       
        if ($a->getName() === $b->getName()) {
            return 0;
        }
        if ( $a->getName() < $b->getName() ) {
            return 1;                 
        }
        return -1;
    }

    public function sortByFilter($collection)
    {
        $iterator = $collection->getIterator();
        $iterator->uasort(array($this, 'sortbyname'));

        return $collection;
    } 

I'm not quite sure if the returned collection in sortByFilter is changed.


回答1:


This is because you are getting the iterator and sorting it.
The method getIterator creates a new ArrayIterator which makes a copy of the array.
Then, you are returning the collection, which is not sorted.

Here is a little sample of what happens.

You just have to replace

return $collection;

By

return $iterator;


来源:https://stackoverflow.com/questions/18226197/twig-extension-for-sorting-doctrine-arraycollection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!