Récupération entité dans une vue

Par bibi427, il y a 10 ans


Bonjour à tous,

Je découvre Symfony et j'ai un petit soucis pour récupérer un objet dans une vue.
Disons que je "crée" une platforme d'annonces. Quand je liste toutes mes annonces j'arrive à les récupérer sur ma page d'accueil mais quand je veux n'afficher qu'une seule annonce j'obtiens une erreur twig m'indiquant que ma clé image ou title n'existe pas.
(Key "image" for array with keys "0" does not exist in BmidPlatformBundle:Advert:view.html.twig at line 11).
Ici j'ai un objet Advert lié à un objet Image par une relation One To One.
Dans mon repository j'ai créé deux fonctions pour récupérer soit l'ensemble des annonces, soit une annonce

//Bmid/PlatformBundle/Entity/AdvertRepository
<?php

namespace Bmid\PlatformBundle\Entity;    
use Doctrine\ORM\EntityRepository;

class AdvertRepository extends EntityRepository
{
    public function getAdverts()
    {
        $query = $this->createQueryBuilder('a')
            ->leftJoin('a.image', 'i')
            ->addSelect('i')
            ->orderBy('a.date', 'DESC')
            ->getQuery()
            ;
        return $query->getResult();
    }

    public function getAdvert($id)
    {
        $query = $this->createQueryBuilder('a')
            ->leftJoin('a.image', 'i')
            ->addSelect('i')
            ->where('a.id = :id')
            ->setParameter('id', $id)
            ->getQuery()
        ;
        return $query->getResult();

    }
}

Mon controller est le suivant

<?php    
//  Bmid/PlatformBundle/Controller/AdvertController  

namespace Bmid\PlatformBundle\Controller;    

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class AdvertController extends Controller
{
    public function indexAction($page)
    {
       if($page <1){
           throw new NotFoundHttpException('La page' . $page . "n'existe pas");
       }
        $listAdverts = $this->getDoctrine()
            ->getManager()
            ->getRepository('BmidPlatformBundle:Advert')
            ->getAdverts()
            ;
        return $this->render('BmidPlatformBundle:Advert:index.html.twig', array(
            'listAdverts' => $listAdverts
        ));
    }

    public function viewAction($id)
    {
        $advert = $this->getDoctrine()
            ->getManager()
            ->getRepository('BmidPlatformBundle:Advert')
            ->getAdvert($id)
            ;
        if($advert === null){
            throw new NotFoundHttpException("L'annonce d'id ".$id." n'existe pas");
        }
        return $this->render(
            'BmidPlatformBundle:Advert:view.html.twig',
            array('advert' => $advert)
        );
    }

Ma vue

{% block bmidplatform_body %}    
    {% if advert.image is not null %}
        <img src="{{ advert.image.url }}" alt="{{ advert.image.alt }}">
    {% endif %}

    <h2>{{ advert.title }}</h2>
    <i>par: {{ advert.author }}, le {{ advert.date|date('d/m/Y') }}</i>
    <div class="well">
        {{ advert.content }}
    </div>
{% endblock bmidplatform_body %}

Merci d'avance pour vos lumières

2 réponses

SimonAndGarfunkel, il y a 10 ans

Salut bibi427,

je pense que ton problème se situe dans ton repository. Essaye de remplacer :

public function getAdvert($id) { $query = $this->createQueryBuilder('a') ....... ; return $query->getResult(); }

par :

public function getAdvert($id) { $query = $this->createQueryBuilder('a') ....... ; return $query->getSingleResult(); }

Comme cela, tu récupères bien un objet et non un tableau d'objets.

bibi427, il y a 10 ans

Effectivement ça marche beaucoup mieux comme cela :)
Merci