2

symfony 2.8

Ok, I have a Category entity which looks like this:

class Category
{

    // ... //
    /**
     * @ORM\OneToMany(targetEntity="Classified", mappedBy="category")
     */
    private $classified;

    // ... // 

    public function __construct()
    {
        $this->classified = new ArrayCollection();
    }

}

and the Classified entity looks like this: Class Classified

{
    /**
     * @ORM\ManyToOne(targetEntity="Category", inversedBy="classified")
     */
    private $category;
}

In my result.html.twig I called to render the controller like this:

{{ render(controller('ClassifiedBundle:Category:displayCategoryPanelList'))}}

which basically calls Category Controller

class CategoryController extends Controller
{
    public function displayCategoryPanelListAction(Request $request)
    {

        $em = $this->getDoctrine()->getManager();
        $categories = $em->getRepository('ClassifiedBundle:Category')
                    ->findAllOrderedByName();


        return $this->render('ClassifiedBundle:Front/Widgets:category-panel-list.html.twig',
            array(
                'categories'    => $categories
            ));
    }
}

which in turn calls the CategoryRepository for query:

class CategoryRepository extends EntityRepository
{
    public function findAllOrderedByName()
    {

        $query = $this->createQueryBuilder('c')
            ->select('c, cc')
            ->leftJoin('c.classified', 'cc')
            ->orderBy('c.name', 'ASC')
            ->getQuery()
            ->getResult();

        return $query;
    }
}

which in the end is rendered to category-panel-list.html.twig:

<ul>
  {% for c in categories %}
    <li>
      <a href="#">
        <i class="fa {{ c.icon }}"></i>
        {{ c.name }} <span class="category-counter">{# COUNT SHOULD GO HERE#}</span>
      </a>
    </li>
  {% endfor %}

</ul>

Now, all these work fine apart from the counting classified arraycollection part. I have tried {{ c.classified|length }} but this gives a fatal error.

The dump looks good and I can see the entry for the classified collection, but just don't know how to count them. Some categories have empty classified collection. enter image description here

shaNnex
  • 1,043
  • 2
  • 19
  • 34
  • "I have tried {{ c.classified|length }} but this gives a fatal error." - What is the fatal error? – emarref Nov 16 '16 at 02:53

2 Answers2

4

{{ c.classified|length }} is applied to an array.

Your object c.classified is a PersistCollection, not an array.

You should use {{ c.classified.count }}

progg
  • 294
  • 1
  • 4
0

You could try just using the doctrine method

{{ c.classified.count }}
Brett
  • 1,951
  • 2
  • 28
  • 35