We are a developing a travelling website using Symfony2. I am currently stuck on menu. The current design is a multi-level menu organised as such: continents-> countries -> regions.
Country sub-menus being grouped per continent and regions per country. I am using Knp menu bundle. I want to generate sub-menus dynamically using foreach loops as I don't want to generate each menu item by hand. For this I need to use a string variable as the array key but this doesn't work... The entities Continent and Country have a toString method that returns getSlug().
Clearly, using $menu['south-america']
works but not $menu[$continent]
with a foreach looping over Continent object slugs.
Here is the error message:
An exception has been thrown during the rendering of a template
("Warning: Illegal offset type in isset or empty in ***********\vendor
\knplabs\knp-menu\src\Knp\Menu\MenuItem.php line 346") in SiteBundle::layout.html.twig at line 11.
Here is the code in my menu builder:
public function createMenu(RequestStack $requestStack, EntityManager $em)
{
$menu = $this->factory->createItem('root');
$menu->addChild('my_account', array(
'label' => 'My Account'
));
$continents = $em->getRepository('CountryBundle:Continent')->getContinents();
foreach ($continents as $continent){
$menu->addChild( $continent, array(
'label'=> $continent->getName(),
));
$countries = $em->getRepository('CountryBundle:Country')->getCountriesByContinent($continent);
foreach($countries as $country)
$menu[$continent]->addChild($country, array(
'label'=> $country->getName(),
));
}
Thank you for your suggestions.
Solution found:
I may have been a bit too fast in posting this question as the solution jumped to me minutes after posting ( after hours of tests) It seems that the objects $country and $continent are not automatically converted to Strings, like I expected them to be when used as array keys. Using $menu[$continent->getSlug()] did the trick. My bad.