Home > Software design >  Display the name of the category of an article
Display the name of the category of an article

Time:11-18

I am new to symfony and Twig. I can display my articles by categories but I cannot display the category name of an article. I want to display the category name of an article but I cannot. I do like this knowing that I have a Category entity and an Article entity: I thank you for your help.

My HomeController

    <?php

namespace App\Controller;

use App\Entity\Article;
use App\Entity\Category;
use App\Repository\ArticleRepository;
use App\Repository\CategoryRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

class HomeController extends AbstractController
{
    private $repoArticle;
    private $repoCategory;

    public function __construct(ArticleRepository $repoArticle, CategoryRepository $repoCategory)
    {
        $this->repoArticle = $repoArticle;
        $this->repoCategory = $repoCategory;
    }

    /**
     * @Route("/", name="home")
     */
    //HOME
    public function index(CategoryRepository $repoCategory): Response

    {
        $repoArticle = $this->getDoctrine()->getRepository(Article::class);
        $repoCategory = $this->getDoctrine()->getRepository(Category::class);

        $categories = $repoCategory->findAll();
        // dd($repoCategory);

        $articles = $repoArticle->findAll();
        // dd($articles);   

        return $this->render("home/index.html.twig", [
            'articles' => $articles,
            'categories' => $categories,
        ]);
    }

    //SHOW
    /**
     * @Route("/show/{id}", name="show")
     */
    public function show($id): Response
    {

        $repoArticle = $this->getDoctrine()->getRepository(Article::class);

        $article = $repoArticle->find($id);
        // dd($articles);   

        if (!$article){
            return $this->redirectToRoute('home');
         }

        return $this->render("show/index.html.twig", [
            'article' => $article,
        ]);
    }

    //SHOW ARTICLE
    /**
     * @Route("/showArticles/{id}", name="show_article")
     */
    public function showArticle(?Category $category, Article $article): Response
    {
        // $articles = $category->getArticles()->getValues();
        // $catArticle = $article->getCategory()->getValues();
        // dd($catArticle);

        if($category){
            $articles = $category->getArticles()->getValues();
        }
        else{
            $articles = null;
            return $this->redirectToRoute('home');
        }
        $categories = $this->repoCategory->findAll();
        $catArticle = $article->getCategory()->getValues();
        return $this->render("home/index.html.twig", [
            'articles' => $articles,
            'categories' => $categories,
            'catArticle' => $catArticle,
        ]);
    }
}

My index.html.twig

{% for article in articles %}
                <div class="col">
                    <div class="card p-0 col-md-4 mb-3" style="width: 25rem;">
                        <div class="cardImg">
                            <a href="{{ path('show', {'id':article.id}) }}"><img src="/assets/uploads/articles/{{ article.image }}" hljs-string">" alt="{{ article.image }}"></a>
                            <div hljs-string">">
                                {% for category in categories %}
                                {% if category.articles | length >=1 %}<span hljs-string">">Category: {{ category.name }}</span>
                                {% else %}
                                {% endif %}
                                {% endfor %}
                              </div>
                        </div>
                    <div hljs-string">">
                        <div hljs-number">0">
                            <p hljs-number">3">Publié le: {{ article.createdAt | date("d/m/Y")}} à {{ article.createdAt | date("H:i")}} par {{ article.author }}</p>
                            <a href="{{ path('show', {'id':article.id}) }}"><h5 hljs-number">2">{{ article.title | u.truncate(50, '...', false)  }}</h5></a>
                            <p hljs-number">3">{{ article.description | striptags | u.truncate(200, '...', false) }}</p>
                        </div>
                        {# <a href="" hljs-number">3 mb-5 w-100">En savoir plus</a> #}
                    </div>

                    </div>
                </div>  
                {% endfor %}

My entity Article

    <?php

namespace App\Entity;

use App\Repository\ArticleRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;

/**
 * @ORM\Entity(repositoryClass=ArticleRepository::class)
 */
class Article
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $title;

    /**
     * @ORM\Column(type="text")
     */
    private $description;

    /**
     * @ORM\Column(type="datetime_immutable")
     * @Gedmo\Timestampable(on="create")
     */
    private $createdAt;

    /**
     * @ORM\Column(type="datetime_immutable")
     * @Gedmo\Timestampable(on="update")
     */
    private $updatedAt;

    /**
     * @ORM\Column(type="boolean")
     */
    private $published;

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

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $tags;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $image;

    /**
     * @ORM\ManyToMany(targetEntity=Category::class, inversedBy="articles")
     */
    private $category;

    /**
     * @ORM\ManyToOne(targetEntity=User::class, inversedBy="articles")
     * @ORM\JoinColumn(nullable=false)
     */
    private $author;

    public function __construct()
    {
        $this->category = new ArrayCollection();
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getTitle(): ?string
    {
        return $this->title;
    }

    public function setTitle(string $title): self
    {
        $this->title = $title;

        return $this;
    }

    public function getDescription(): ?string
    {
        return $this->description;
    }

    public function setDescription(string $description): self
    {
        $this->description = $description;

        return $this;
    }

    public function getCreatedAt(): ?\DateTimeImmutable
    {
        return $this->createdAt;
    }

    public function setCreatedAt(\DateTimeImmutable $createdAt): self
    {
        $this->createdAt = $createdAt;

        return $this;
    }

    public function getUpdatedAt(): ?\DateTimeImmutable
    {
        return $this->updatedAt;
    }

    public function setUpdatedAt(\DateTimeImmutable $updatedAt): self
    {
        $this->updatedAt = $updatedAt;

        return $this;
    }

    public function getPublished(): ?bool
    {
        return $this->published;
    }

    public function setPublished(bool $published): self
    {
        $this->published = $published;

        return $this;
    }

    public function getSlug(): ?string
    {
        return $this->slug;
    }

    public function setSlug(string $slug): self
    {
        $this->slug = $slug;

        return $this;
    }

    public function getTags(): ?string
    {
        return $this->tags;
    }

    public function setTags(string $tags): self
    {
        $this->tags = $tags;

        return $this;
    }

    public function getImage(): ?string
    {
        return $this->image;
    }

    public function setImage(string $image): self
    {
        $this->image = $image;

        return $this;
    }

    /**
     * @return Collection|Category[]
     */
    public function getCategory(): Collection
    {
        return $this->category;
    }

    public function addCategory(Category $category): self
    {
        if (!$this->category->contains($category)) {
            $this->category[] = $category;
        }

        return $this;
    }

    public function removeCategory(Category $category): self
    {
        $this->category->removeElement($category);

        return $this;
    }

    public function getAuthor(): ?User
    {
        return $this->author;
    }

    public function setAuthor(?User $author): self
    {
        $this->author = $author;

        return $this;
    }
}

My entity Category

    <?php

namespace App\Entity;

use App\Repository\CategoryRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass=CategoryRepository::class)
 */
class Category
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $name;

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     */
    private $description;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $image;

    /**
     * @ORM\ManyToMany(targetEntity=Article::class, mappedBy="category")
     */
    private $articles;

    public function __construct()
    {
        $this->articles = new ArrayCollection();
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getName(): ?string
    {
        return $this->name;
    }

    public function setName(string $name): self
    {
        $this->name = $name;

        return $this;
    }

    public function getDescription(): ?string
    {
        return $this->description;
    }

    public function setDescription(?string $description): self
    {
        $this->description = $description;

        return $this;
    }

    public function getImage(): ?string
    {
        return $this->image;
    }

    public function setImage(string $image): self
    {
        $this->image = $image;

        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->addCategory($this);
        }

        return $this;
    }

    public function removeArticle(Article $article): self
    {
        if ($this->articles->removeElement($article)) {
            $article->removeCategory($this);
        }

        return $this;
    }
    public function __toString()
    {
        return $this->name;
    }
}

CodePudding user response:

You have many to many for your categories so it would be like this to show all article categories:

{% for category in article.category %}
   <span class="fontz-text glow">Category: {{ category.name }}</span>
{% endfor %}

For just one category you can do this:

<span class="fontz-text glow">Category: {{ article.category[0].name }}</span>
  • Related