My Blog
Here I am having a little problem with my code to retrieve the user in Twig, I have a ManyToOne relations between the Article table and the User table, I want to retrieve the author of the article and I cannot. in the database everything is good, but in Twig I don't know how to do it.
Mon code
ArticleController.php
/**
* @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(),
]);
}
My Twig
{% 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-->
What i get
Impossible to access an attribute ("nom") on a null variable.
Article.php
<?php
namespace App\Entity;
use App\Repository\ArticleRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass=ArticleRepository::class)
*/
class Article
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=50)
*/
private $titre;
/**
* @ORM\Column(type="string", length=255)
*/
private $description;
/**
* @ORM\Column(type="text")
*/
private $contenu;
/**
* @ORM\Column(type="string", length=255, nullable=true)
*/
private $photo;
/**
* @ORM\Column(type="string", length=255)
*/
private $slug;
/**
* @ORM\Column(type="datetime")
*/
private $created_at;
/**
* @ORM\Column(type="datetime", nullable=true)
*/
private $updated_at;
/**
* @ORM\OneToMany(targetEntity=Commentaire::class, mappedBy="articles", orphanRemoval=true)
*/
private $commentaires;
/**
* @ORM\ManyToMany(targetEntity=Categorie::class, inversedBy="articles")
*/
private $categories;
/**
* @ORM\ManyToOne(targetEntity=User::class, inversedBy="articles")
*/
private $users;
public function __construct()
{
$this->commentaires = new ArrayCollection();
$this->categories = new ArrayCollection();
$this->created_at= new \DateTime('now');
}
public function getId(): ?int
{
return $this->id;
}
public function getTitre(): ?string
{
return $this->titre;
}
public function setTitre(string $titre): self
{
$this->titre = $titre;
return $this;
}
public function getDescription(): ?string
{
return $this->description;
}
public function setDescription(string $description): self
{
$this->description = $description;
return $this;
}
public function getContenu(): ?string
{
return $this->contenu;
}
public function setContenu(string $contenu): self
{
$this->contenu = $contenu;
return $this;
}
public function getPhoto(): ?string
{
return $this->photo;
}
public function setPhoto(?string $photo): self
{
$this->photo = $photo;
return $this;
}
public function getSlug(): ?string
{
return $this->slug;
}
public function setSlug(string $slug): self
{
$this->slug = $slug;
return $this;
}
public function getCreatedAt(): ?\DateTimeInterface
{
return $this->created_at;
}
public function setCreatedAt(\DateTimeInterface $created_at): self
{
$this->created_at = $created_at;
return $this;
}
public function getUpdatedAt(): ?\DateTimeInterface
{
return $this->updated_at;
}
public function setUpdatedAt(?\DateTimeInterface $updated_at): self
{
$this->updated_at = $updated_at;
return $this;
}
/**
* @return Collection|Commentaire[]
*/
public function getCommentaires(): Collection
{
return $this->commentaires;
}
public function addCommentaire(Commentaire $commentaire): self
{
if (!$this->commentaires->contains($commentaire)) {
$this->commentaires[] = $commentaire;
$commentaire->setArticles($this);
}
return $this;
}
public function removeCommentaire(Commentaire $commentaire): self
{
if ($this->commentaires->removeElement($commentaire)) {
// set the owning side to null (unless already changed)
if ($commentaire->getArticles() === $this) {
$commentaire->setArticles(null);
}
}
return $this;
}
/**
* @return Collection|categorie[]
*/
public function getCategories(): Collection
{
return $this->categories;
}
public function addCategory(categorie $category): self
{
if (!$this->categories->contains($category)) {
$this->categories[] = $category;
}
return $this;
}
public function removeCategory(categorie $category): self
{
$this->categories->removeElement($category);
return $this;
}
public function getUsers(): ?user
{
return $this->users;
}
public function setUsers(?user $users): self
{
$this->users = $users;
return $this;
}
}
User.php
<?php
namespace App\Entity;
use App\Repository\UserRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* @ORM\Entity(repositoryClass=UserRepository::class)
* @UniqueEntity(fields={"email"}, message="There is already an account with this email")
*/
class User implements UserInterface
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=180, unique=true)
*/
private $email;
/**
* @ORM\Column(type="json")
*/
private $roles = [];
/**
* @var string The hashed password
* @ORM\Column(type="string")
*/
private $password;
/**
* @ORM\Column(type="boolean")
*/
private $isVerified = false;
/**
* @ORM\Column(type="string", length=50)
*/
private $nom;
/**
* @ORM\Column(type="string", length=50)
*/
private $prenom;
/**
* @ORM\OneToMany(targetEntity=Article::class, mappedBy="users")
*/
private $articles;
/**
* @ORM\OneToMany(targetEntity=Commentaire::class, mappedBy="users", orphanRemoval=true)
*/
private $commentaires;
public function __construct()
{
$this->articles = new ArrayCollection();
$this->commentaires = new ArrayCollection();
}
public function __toString()
{
return $this->prenom . ' ' . $this->nom;
}
public function getId(): ?int
{
return $this->id;
}
public function getEmail(): ?string
{
return $this->email;
}
public function setEmail(string $email): self
{
$this->email = $email;
return $this;
}
/**
* A visual identifier that represents this user.
*
* @see UserInterface
*/
public function getUsername(): string
{
return (string) $this->email;
}
/**
* @see UserInterface
*/
public function getRoles(): array
{
$roles = $this->roles;
// guarantee every user at least has ROLE_USER
$roles[] = 'ROLE_USER';
return array_unique($roles);
}
public function setRoles(array $roles): self
{
$this->roles = $roles;
return $this;
}
/**
* @see UserInterface
*/
public function getPassword(): string
{
return (string) $this->password;
}
public function setPassword(string $password): self
{
$this->password = $password;
return $this;
}
/**
* @see UserInterface
*/
public function getSalt()
{
// not needed when using the "bcrypt" algorithm in security.yaml
}
/**
* @see UserInterface
*/
public function eraseCredentials()
{
// If you store any temporary, sensitive data on the user, clear it here
// $this->plainPassword = null;
}
public function isVerified(): bool
{
return $this->isVerified;
}
public function setIsVerified(bool $isVerified): self
{
$this->isVerified = $isVerified;
return $this;
}
public function getNom(): ?string
{
return $this->nom;
}
public function setNom(string $nom): self
{
$this->nom = $nom;
return $this;
}
public function getPrenom(): ?string
{
return $this->prenom;
}
public function setPrenom(string $prenom): self
{
$this->prenom = $prenom;
return $this;
}
/**
* @return Collection|Article[]
*/
public function getArticles(): Collection
{
return $this->articles;
}
public function addArticle(Article $article): self
{
if (!$this->articles->contains($article)) {
$this->articles[] = $article;
$article->setUsers($this);
}
return $this;
}
public function removeArticle(Article $article): self
{
if ($this->articles->removeElement($article)) {
// set the owning side to null (unless already changed)
if ($article->getUsers() === $this) {
$article->setUsers(null);
}
}
return $this;
}
/**
* @return Collection|Commentaire[]
*/
public function getCommentaires(): Collection
{
return $this->commentaires;
}
public function addCommentaire(Commentaire $commentaire): self
{
if (!$this->commentaires->contains($commentaire)) {
$this->commentaires[] = $commentaire;
$commentaire->setUsers($this);
}
return $this;
}
public function removeCommentaire(Commentaire $commentaire): self
{
if ($this->commentaires->removeElement($commentaire)) {
// set the owning side to null (unless already changed)
if ($commentaire->getUsers() === $this) {
$commentaire->setUsers(null);
}
}
return $this;
}
}
PhpMyAdmin
It is an article, user_Id 1. its good, I have all the information I need in the database. my problem is that I can't show the name of the person who created the article.
I'm sorry my english is not perfect .
the code is perfect, the only problem I had is that some articles had been created before connecting and for that reason the user was null in the database and could not display it. I deleted these articles and the problem has been solved.