I have entity Domain which has fields id, domain, users in field users, I have an id which is the id of the user who created that domain.
now I have created for in the template which will display every domain that the user created.
I messed it up somehow and I don’t know how to solve it.
workspaces.html.twig
{% for domain in workspaces %} <div class="workspace card"> <div class="card-body"> <h4 class="card-title">{{workspaces.number}}</h4> <a href="/project" class="card-link">Card link</a> </div> </div> {% endfor %}
MainController.php
public function show() { //todo: show domains for current user $repository = $this->getDoctrine()->getRepository(Domain::class); $currentUser = $this->getUser()->getID(); $workspaces = $this->getDoctrine() ->getRepository(Domain::class) ->findByUsers($currentUser); return $this->render('workspaces.html.twig',array('workspaces' => $workspaces)); }
DomainRepository.php
/** * @param $currentUser * @return Domain[] Returns an array of Domain objects */ public function findByUsers($currentUser) { return $this->createQueryBuilder('d') ->andWhere('d.users = :val') ->setParameter('val', $currentUser) ->orderBy('d.id', 'ASC') ->setMaxResults(15) ->getQuery() ->getResult(); }
Error that I get: Key “domain” for an array with keys “0, 1” does not exist. currently, I got 2 records in the database but when I add more then the error shows more keys “0, 1, 2…”
I know that I somehow messed up for or something (bad naming does not help 🙁 ).
Advertisement
Answer
Did you check your query if its working? if its working there is a problem in your code
First let’s clean a little the code.
MainController.php
public function showAction() { //todo: show domains for current user $currentUser = $this->getUser()->getID(); $workspaces = $this->getDoctrine() ->getRepository(Domain::class) ->getDomainsByUser($currentUser); return $this->render('workspaces.html.twig',array('workspaces' => $workspaces)); }
DomainRepository.php
public function getDomainsByUser($currentUser) { return $this->createQueryBuilder('d') ->andWhere('d.users = :val') ->setParameter('val', $currentUser) ->orderBy('d.id', 'ASC') ->setMaxResults(15) ->getQuery() ->getResult(); }
workspaces.html.twig
The problem in the code is in the twig part. {{ domain.domain }} not {{ workspaces.number }} {% for domain in workspaces %} <div class="workspace card"> <div class="card-body"> <h4 class="card-title">{{ domain.domain }}</h4> <a href="/project" class="card-link">Card link</a> </div> </div> {% endfor %}