skip to Main Content

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 AppEntity;

use AppRepositoryArticleRepository;
use DoctrineCommonCollectionsArrayCollection;
use DoctrineCommonCollectionsCollection;
use DoctrineORMMapping as ORM;

/**
 * @ORMEntity(repositoryClass=ArticleRepository::class)
 */
class Article
{
    /**
     * @ORMId
     * @ORMGeneratedValue
     * @ORMColumn(type="integer")
     */
    private $id;

    /**
     * @ORMColumn(type="string", length=50)
     */
    private $titre;

    /**
     * @ORMColumn(type="string", length=255)
     */
    private $description;

    /**
     * @ORMColumn(type="text")
     */
    private $contenu;

    /**
     * @ORMColumn(type="string", length=255, nullable=true)
     */
    private $photo;
    

    /**
     * @ORMColumn(type="string", length=255)
     */
    private $slug;

    /**
     * @ORMColumn(type="datetime")
     */
    private $created_at;

    /**
     * @ORMColumn(type="datetime", nullable=true)
     */
    private $updated_at;

    /**
     * @ORMOneToMany(targetEntity=Commentaire::class, mappedBy="articles", orphanRemoval=true)
     */
    private $commentaires;

    /**
     * @ORMManyToMany(targetEntity=Categorie::class, inversedBy="articles")
     */
    private $categories;

    /**
     * @ORMManyToOne(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 AppEntity;

use AppRepositoryUserRepository;
use DoctrineCommonCollectionsArrayCollection;
use DoctrineCommonCollectionsCollection;
use DoctrineORMMapping as ORM;
use SymfonyBridgeDoctrineValidatorConstraintsUniqueEntity;
use SymfonyComponentSecurityCoreUserUserInterface;

/**
 * @ORMEntity(repositoryClass=UserRepository::class)
 * @UniqueEntity(fields={"email"}, message="There is already an account with this email")
 */
class User implements UserInterface
{
    /**
     * @ORMId
     * @ORMGeneratedValue
     * @ORMColumn(type="integer")
     */
    private $id;

    /**
     * @ORMColumn(type="string", length=180, unique=true)
     */
    private $email;

    /**
     * @ORMColumn(type="json")
     */
    private $roles = [];

    /**
     * @var string The hashed password
     * @ORMColumn(type="string")
     */
    private $password;

    /**
     * @ORMColumn(type="boolean")
     */
    private $isVerified = false;

    /**
     * @ORMColumn(type="string", length=50)
     */
    private $nom;

    /**
     * @ORMColumn(type="string", length=50)
     */
    private $prenom;

    /**
     * @ORMOneToMany(targetEntity=Article::class, mappedBy="users")
     */
    private $articles;

    /**
     * @ORMOneToMany(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 .

2

Answers


  1. Chosen as BEST ANSWER

    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.


  2. the error message says the users property of the article is null, which leads us to an error in the ORM mapping since you are saying the database field user_id of the article has the correct value (1).

    This means the error is likely in the annotation above the users property. By looking at your code, one thing that gets my attention is your syntax when pointing to the targetEntity. You are using User::class, but according to doctrine documentation, it should be like this targetEntity="User" or like this targetEntity="AppEntityUser"

        /**
         * @ORMManyToOne(targetEntity=User::class, inversedBy="articles")
         */
        private $users;
    

    https://www.doctrine-project.org/projects/doctrine-orm/en/2.7/reference/association-mapping.html

    I might be wrong, its possible that doctrine accept all those syntax but its worth checking that point I think

    EDIT- as the issue isnt the one above, another thing to check is the way to populate the Article object. I thought you must use the getData() method like this:

        $form = $this->createForm(ArticleType::class);
    
        $form->handleRequest($request);
    
        if ($form->isSubmitted() && $form->isValid()) {
            // new article object come back populated by the form
            $article = $form->getData();
    
            // record the new article
            $em = $this->getDoctrine()->getManager();
            $em->persist($article);
            $em->flush();
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search