I am working on Symfony 3.4 in PHP 5.6.
Here is the context of my problem:
I have an "information" table that contains several lines. I want to sort these lines and display them according to a certain column called "Zone". So the goal is to have for example
"Zone 1" * Lines of information corresponding to this area " "Zone 2" * Lines of information corresponding to this area " ...
I realized my functions in the Repository, and I also made the layout under Twig. Everything worked. All I had to do was optimize my code on the controller to make it cleaner.
My idea was therefore:
- Retrieve an array containing all the existing distinct areas by a query.
- Loop on this array using each value of the array as a parameter for the SQL query that retrieves the rows corresponding to the passed field and retrieve them in an array variable
- Make an array_push () of the array of each zone, in another array that will contain the array of each zone.
But I can't. This is my code
Repository :
public function getInformationsZone($zone)
{
$queryBuilder = $this->createQueryBuilder("i")
->where("i.zone = :zone")
->orderBy("i.updatedAt","DESC")
->orderBy("i.criticite","DESC")
->setParameter('zone',$zone);
return $queryBuilder->getQuery()->getResult();
}
public function getZonesActives()
{
$queryBuilder = $this->createQueryBuilder("i")
->select("i.zone")
->distinct(true);
return $queryBuilder->getQuery()->getResult();
}
controller
/**
* Lists all information entities.
*
* @Route("/", name="informations_index")
* @Method("GET")
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$information = $em->getRepository('PagesBundle:Information')->findAll();
$listZones = $this->getDoctrine()->getRepository('PagesBundle:Information')->getZonesActives();
$tabInfos = array();
foreach($listZones as $key=>$value)
{
$zone = $this->getDoctrine()->getRepository('PagesBundle:Information')->getInformationsZone($value);
array_push($tabInfos,$zone);
}
// This is what i did just before
/* $infosZone1 = $this->getDoctrine()->getRepository('PagesBundle:Information')->getInformationsZone("Zone 1");
$infosZone2 = $this->getDoctrine()->getRepository('PagesBundle:Information')->getInformationsZone("Zone 2");
$infosZone3 = $this->getDoctrine()->getRepository('PagesBundle:Information')->getInformationsZone("Zone 3");
$tabInfos = array($infosZone1,$infosZone2,$infosZone3);*/
return $this->render('information/index.html.twig', array(
/* 'information' => $information,
'infosZone1'=> $infosZone1,
'infosZone2'=> $infosZone2,
'infosZone3'=> $infosZone3,*/
'tabInfos'=>$tabInfos,
));
}
I've this error :
An exception occurred while executing 'SELECT i0_.id AS id_0, i0_.contenu AS contenu_1, i0_.updated_at AS updated_at_2, i0_.zone AS zone_3, i0_.titre AS titre_4, i0_.criticite AS criticite_5 FROM information i0_ WHERE i0_.zone = ? ORDER BY i0_.criticite DESC' with params ["Zone 1"]:
SQLSTATE[HY093]: Invalid parameter number: parameter was not defined