質問

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.

役に立ちましたか?

解決

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;
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top