How to use foreach in Symfony2

Hi guys. Today I want to speak again about the Symfony2 Framework. In this tutorial I will explain to you how you can use a function like foreach or while in Symfony2.6.

If you want to extract all information from a table in your database, you must add this code in your Controller:

$test = $this->getDoctrine()
->getRepository('NewNewBundle:test') // the name of my Entity
->findAll(); // the findAll() function will extract all information from my table test

if (!$test) {
throw $this->createNotFoundException(
'No product found for id '.$id

return $this->render('NewNewBundle:Default:index.html.twig', array('test' => $test)); // this code will display the results in my index.html.twig file.

Next, I will add this code i my index.html.twig file:

{% for item in test %} // this function works as foreach
{{item.text}}<br> // text is the name of my field in the table
{% endfor %}

So, as you can see, its very simple to use a function like foreach in Symfony!

Video tutorial:

Leave a Comment