Search code examples
symfony-3.3

Variable "user" does not exist


Can someone help me please I had this error Variable "user" does not exist when I want to display the list of my friends added (todo)

listeami.html.twig (relation many to many between user and todo)

{% if not user.todos.empty %}

{% for todo in user.todos %}
  {{ todos.age }}{% if not loop.last %}, {% endif %}
{% endfor %}${% endif %}

Controller:todoController.php (page to display list):

  /**
    * @Route("/todo/listeami", name="todo_listeami")
    */


     public function listeamiAction(Request $request)
     {
         $todos = $this->getDoctrine()
         ->getRepository('AppBundle:Todo')
         ->findAll();

         return $this->render('todo/listeami.html.twig',array('todos'=>$todos));

     }

Controller edit:

  ` **/**
         * @Route("/todo/editmany/{id}", name="todo_editmany")
         */**


    public function editmanyAction($id, Request $request)
        {
          $em = $this->getDoctrine()->getManager();

          // On récupère l'annonce $id
          $user = $em->getRepository('AppBundle:User')->find($id);

          if (null === $user) {
            throw new NotFoundHttpException("L'user d'id ".$id." n'existe pas.");
          }

          // La méthode findAll retourne toutes les catégories de la base de données
          $listTodos = $em->getRepository('AppBundle:Todo')->findAll();

          // On boucle sur les catégories pour les lier à l'annonce
          foreach ($listTodos as $todo) {
            $user->addCategory($todo);
          }

          // Pour persister le changement dans la relation, il faut persister l'entité propriétaire
          // Ici, Advert est le propriétaire, donc inutile de la persister car on l'a récupérée depuis Doctrine

          // Étape 2 : On déclenche l'enregistrement
          $em->flush();

          // … reste de la méthode
        }
    `

this page for DATA fixtures:

<?php
// src/OC/PlatformBundle/DataFixtures/ORM/LoadCategory.php

namespace AppBundle\DataFixtures\ORM;
use Doctrine\Bundle\FixturesBundle\Fixture;

use Doctrine\Common\Persistence\ObjectManager;
use AppBundle\Entity\Todo;

class LoadTodo extends Fixture
{
  // Dans l'argument de la méthode load, l'objet $manager est l'EntityManager
  public function load(ObjectManager $manager)
  {
    // Liste des noms de catégorie à ajouter
    $ages = array(
      'un mois',
      'deux jours',
      'quatre jours',
      'trois heures',
      'un jour'
    );



    foreach ($ages as $age) {
      // On crée la catégorie
      $todo = new Todo();
      $todo->setAge($age);
      $todo->setNourriture('Omnivore');
      $todo->setRace('Race');
      $todo->setFamille('Famille');
      $todo->setEmail($age."@gmail.com");
      // On la persiste
      $manager->persist($todo);
    }

    // On déclenche l'enregistrement de toutes les catégories
    $manager->flush();
  }
}

thanks in adavance


Solution

  • You are not passing the user variable from listeamiAction action you should fix the problem this way

    Option #1: Passing the variable to your view

    public function listeamiAction(Request $request)
         {
    

    $user = $this->getUser();

             return $this->render('todo/listeami.html.twig',array('user'=>$user));
    
         }
    

    Option #2: Access to the user env variable(i think this is what you are trying to do)

      {% for todo in app.user.todos %}
          {{ todo.age }}{% if not loop.last %}, {% endif %}
        {% endfor %}${% endif %}
    

    With the app.user you can access to your UserInterface declared. It's important that the getTodos() is an accesible function in the User class.

    Option #3: use the todo variables passed to the view(todos)

    {% if not todos.empty %}
    
    {% for todo in todos %}
      {{ todo.age }}{% if not loop.last %}, {% endif %}
    {% endfor %}${% endif %}
    

    Hope it helps!!