I am trying to generate a combo box with values of my database in it.
To do so I decided to put a simple php code inside my .html.twig
Here is the code
<?php
$villes = $this->getDoctrine()
->getRepository('ProjetEsamuzeDiorBundle:Villes')
->findAll();
echo "<select name='ville'>";
for ($i=0;$i<count($villes)-1;$i++)
{
echo "<option value='".$villes[$i]->getId()."'>".$villes[$i]->getNom()."</option>";
}
echo "</select>";
?>
The output of this is
getDoctrine() ->getRepository('ProjetEsamuzeDiorBundle:Villes') ->findAll(); echo ""; for ($i=0;i".$villes[i]->getNom().""; } echo ""; ?>
Keep in mind this is directly on the page, as if there was an echo just before, but there isn’t. I thought maybe it’s the $this, but replacing it with $villes gave the same result
Also I don’t see the for what I see is exactly this
getDoctrine() ->getRepository('ProjetEsamuzeDiorBundle:Villes') ->findAll(); echo "(combobox is empty here)"; ?>
What am I doing wrong?
You cannot use PHP in twig templates. Twig is parsed and converted to PHP but no PHP code is interpreted. You have to use twig syntax.
Furthermore, you really shouldn’t put logic into templates. Twig is doing great job preventing you from doing that. Database query should go to the controller.