php - Rendering nested category entities from Doctrine 2 -
i'm working self-referencing entity , have build small list structure (<ul><li>
) based on entity. however, list must take depth account, need use parent/children relationship base renderer. here's original entity:
<?php use doctrine\common\collections\arraycollection; use doctrine\common\collections\collection; use doctrine\orm\mapping orm; /** * @orm\entity() * @orm\table(name="categories") */ class category { /** * @orm\id * @orm\generatedvalue(strategy="auto") * @orm\column(type="integer") */ protected $id; /** * @orm\column(type="string", length=255) */ protected $name; /** * @var category * * @orm\manytoone(targetentity="category", inversedby="children") * @orm\joincolumn(name="category_id", referencedcolumnname="id", nullable=true, ondelete="cascade") */ protected $parent; /** * @var collection * * @orm\onetomany( * targetentity="category", * mappedby="parent", * cascade={"all"} * ) */ protected $children; public function __construct() { $this->children = new arraycollection(); } public function getid(): { return $this->id; } public function setid(int $id) { $this->id = $id; } public function getname() { return $this->name; } public function setname(string $name) { $this->name = $name; } public function getparent() { return $this->parent; } public function setparent(category $parent) { $this->parent = $parent; } public function setchildren(array $children) { $this->children = $children; } public function getchildren() { return $this->children; } public function addchild(category $category) { if (!$this->children->contains($category)) { $category->setparent($this); $this->children->add($category); } } public function removechild(category $category) { if ($this->children->contains($category)) { $this->children->removeelement($category); } } }
i have implemented naive implementation inspired this: https://wildlyinaccurate.com/simple-nested-sets-in-doctrine-2/
however, depth-based padding logic doesn't me <ul><li>
structure. recommend way of rendering self-referencing objects html lists?
here how print out 3 levels of unordered categories list () based tree:
<?php $rootcategories = $em->getrepository('entity\category')->findby(['parent' => null]) ?> // root categories container <ul> <?php foreach ($rootcategories $rootcategory): ?> <li> <?= $rootcategory->getname() ?> <?php if ($rootcategory->getchildren()): ?> // first child categories container <ul> <?php foreach ($rootcategory->getchildren() $firstchildcategory): ?> <li> <?= $firstchildcategory->getname() ?> <?php if ($firstchildcategory->getchildren()): ?> // second child categories container <ul> <?php foreach ($firstchildcategory->getchildren() $secondchildcategory): ?> <li><?= $secondchildcategory->getname() ?></li> <?php endforeach ?> </ul> <?php endif ?> </li> <?php endforeach ?> </ul> <?php endif ?> </li> <?php endforeach ?> </ul>
Comments
Post a Comment