Skip to content
Advertisement

Issue with Category tree in symfony

I created a Category Tree in symfony 5

I’ve following:

Category.php Entity:

/**
 * @ORMId()
 * @ORMGeneratedValue()
 * @ORMColumn(type="integer")
 */
private $id;

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

/**
 * @ORMManyToOne(targetEntity="AppEntityCategory", inversedBy="children")
 */
private $parent;

/**
 * @ORMOneToMany(targetEntity="AppEntityCategory", mappedBy="parent")
 */
private $children;

public function __construct()
{
    $this->children = 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 getParent(): ?self
{
    return $this->parent;
}

public function setParent(?self $parent): self
{
    $this->parent = $parent;

    return $this;
}

/**
 * @return Collection|self[]
 */
public function getChildren(): Collection
{
    return $this->children;
}

public function addChild(self $child): self
{
    if (!$this->children->contains($child)) {
        $this->children[] = $child;
        $child->setParent($this);
    }

    return $this;
}

CategoryReponsitory.php

public function getAllCategory()
{
    $query = $this->createQueryBuilder('c')
        ->where('c.parent IS NULL');

    return $query->getQuery()->getResult();
}

Controller.php

public function index(CategoryRepository $categoryRepository): Response
{
    return $this->render('category/index.html.twig', [
        'categories' => $categoryRepository->getAllCategory(),
    ]);
}

And the twig template file index.html.twig

{% macro menu_categories(categories) %}
    {% import _self as macros %}
    {% for category in categories %}
        <li>
            <a href="cate/{{ category.id }}">{{ category.name }}</a>
            {% if category.children %}
                <ul class="children">
                    {{ macros.menu_categories(category.children) }}
                </ul>
            {% endif %}
        </li>
    {% endfor %}
{% endmacro %}

<ul class="menu-category">
    {{ _self.menu_categories(categories) }}
</ul>

It render is correctly, But if the children don’t have any children, it still renders html like image bellow:

enter image description here

I don’t want it, for some reason. How can I fix that. Thank you.

Advertisement

Answer

The behavior for collections seems to be different than for arrays. Since children is an ArrayCollection it’ll always be set. You should check if it contains elements.

{% if category.children is not empty %}
    <ul class="children">
        {{ macros.menu_categories(category.children) }}
    </ul>
{% endif %}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement