На этот раз будем делать древовидный вывод пунктов навигации сайта. Данный способ будет работать на Symfony 2.4 и выше, включая Symfony 3.
Для начала создадим сущность MenuItem:
#AppBundle/Resources/config/doctrine/MenuItem.orm.yml
AppBundle\Entity\MenuItem:
type: entity
table: MenuItem
repositoryClass: AppBundle\Entity\Repository\MenuItemRepository
id:
id:
type: integer
id: true
generator:
strategy: AUTO
fields:
title:
type: string
length: 255
url:
type: string
length: 255
nullable: true
oneToMany:
childs:
targetEntity: MenuItem
mappedBy: parent
manyToOne:
parent:
targetEntity: MenuItem
inversedBy: childs
joinColumn:
name: parent
referencedColumnName: id
lifecycleCallbacks: { }
И выполним команду в консоли:
php app/console doctrine:generate:entities AppBundle
Теперь нужно обновить схему базы данных:
php app/console doctrine:schema:update --force
Писать экшены контроллера для CRUD операций в этой статье я не буду. Напишу экшен для вывода блока ссылок:
<?php
namespace AppBundle\Controller;
use AppBundle\Entity\MenuItem;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class MenuController extends Controller
{
public function blockAction()
{
$em = $this->getDoctrine()->getManager();
$menuItems = $this->em->getRepository('AppBundle:MenuItem')->findAll();
return $this->render('AppBundle:Menu:block.html.twig', array(
'menuItems' => $menuItems
));
}
}
Создадим 2 twig файла:
block.html.twig для отображения блока:
{% block Navigation %}
<ul>
{% for item in menuItems %}
{% if(item.parent == null) %}
<li>
<a href="{{ item.url }}">{{ item.title }}</a>
{% include 'AppBundle:Menu:sub-items.html.twig' with {'menuItems': item.childs} %}
</li>
{% endif %}
{% endfor %}
</ul>
{% endblock %}
sub-items.html.twig для отображения вложенных пунктов меню:
{% block subItems %}
<ul>
{% for item in menuItems %}
<li>
<a href="{{ item.url }}">{{ item.title }}</a>
{% if item.ParentToMenuItem != null %}
{% include 'AppBundle:Menu:sub-items.html.twig' with {'menuItems': item.childs} %}
{% endif %}
</li>
{% endfor %}
</ul>
{% endblock %}
В результате получим древовидый вывод навигации сайта, как показано ниже.
Если вы используете Symfony 3, то будет одно различие — консольная команда для генерации сущностей:
php bin/console doctrine:generate:entities AppBundle