Bonjour,
Voila je rencontre un petit problème avec mon code pour récupérer l'utilisateur en twig, j'ai une relation ManyToOne entre la table Article et la table User, Je souhaite récupérer l'auteur de l'article et je n'arrive pas. dans la base de données tout est bon, mais en twig je ne sais pas comment faire.
Ce que je fais
Mon controller pour les articles
/**
* @Route("/add-article", name="add_article", methods={"GET","POST"})
*/
public function new(Request $request): Response
{
$article = new Article();
$form = $this->createForm(ArticleFormType::class, $article);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid())
{
$article->setUsers($this->getUser());
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($article);
$entityManager->flush();
return $this->redirectToRoute('blog_articles');
}
return $this->render('articles/Article-form.html.twig', [
'form_title'=> 'Ajouter un Article',
'form_article' => $form->createView(),
]);
}
Ce que je veux Mon Twig
si je fais un dump {{ article.users }} je récupère l'objet mais je veux le nom et prenom de l'utilisateur
{% for article in articles %}
<div class="col-md-6 col-lg-4">
<div class="card mb-4 shadow-sm">
<!-- CONDITIONS POUR L'AFFICHAGE DES PHOTOS-->
{% if article.photo is defined and article.photo is not null %}
<img src="{{asset('images/')}}{{ article.photo }}" class="img-fluid" width="100%" height="225">
{% else %}
<img src="{{asset('images/img-17.jpg')}}" class="img-fluid" width="100%" height="225">
{% endif %}
<div class="card-body">
<!--BOUCLE POUR RECUPERER LE CATEGORIE DE CHAQUE ARTICLE-->
{% for categorie in article.categories %}
<span class="text-left" style="color: grey;">{{ categorie.nom }}</span>
{% endfor %}
<!-- FIN DE LA BOUCLE-->
<h4 class="text-center titre">
<a href="{{ path('blog_article', {'id': article.id}) }}"> {{ article.titre }} </a>
</h4>
<p class="card-text">{{ article.description }}</p>
<div class="d-flex justify-content-between align-items-center">
<!-- Post Author -->
<p class="text-muted">{{ article.users.nom }} - {{ article.createdAt| date('d/m/Y')}}</p>
<div class="social">
<ul class="list-inline">
<a href="" class="mr-4"><i class="fa fa-heart" aria-hidden="true"></i> 3 </a>
<a href=""><i class="fas fa-comments" aria-hidden="true"></i> 5 </a>
</ul>
</div>
</div>
</div>
</div>
</div>
{% endfor %}
<!-- FIN DE LA BOUCLE POUR LES ARTICLES-->
Ce que j'obtiens
Impossible to access an attribute ("nom") on a null variable.