BentCoder
BentCoder

Reputation: 12740

Accessing array values in twig loop

I cannot access to cars in TWIG but code below works fine in controller itself. I'm getting error like this when trying to access cars in Twig:

Method "model" for object "Doctrine\ORM\PersistentCollection" does not exist in

None of these DOESN'T WORK in TWIG loop below:

{{ car.model }}
{{ cars.model }}
{{ brand.car.model }}
{{ brand.cars.model }}
{{ brand.car.car.model }}
{{ brand.car.cars.model }}
{{ brand.cars.car.model }}
{{ brand.cars.cars.model }}

This work fine TWIG file:

{% for brand in result %}
   {{ brand.name }}
{% endfor %}

CONTROLLER (Works fine):

    foreach ($result as $brand)
    {
        echo $brand->getName() . ':';

        foreach ($brand->getCars() as $car)
        {
            echo $car->getModel() . ',';
        }

        echo '<br />';
    }

OUTPUT:

bmw:3.16,3.18,
mercedes:amg,

QUERY IN REPOSITORY:

$query = $em->createQuery('SELECT car, brand
                            FROM CarBrandBundle:Brands brand
                            JOIN brand.cars car
                            ORDER BY
                                brand.name ASC,
                                car.model ASC');

Upvotes: 0

Views: 758

Answers (1)

qooplmao
qooplmao

Reputation: 17759

Cars is an array so you need to loop through them like..

{% for car in brand.cars %}
    {{ car.model }}
{% endfor %}

Alternatively you could access it like {{ brans.cars[0].model }} but then you would have to know how many cars there are beforehand.

Upvotes: 2

Related Questions