Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current bundle in Symfony 2?

Tags:

symfony

How can I detect in which bundle am I?

for exemple, when I'm in web.com/participants/list, I want to read "participants".

like image 858
Bernat Avatar asked May 11 '12 07:05

Bernat


3 Answers

In order to get the bundle name in the controller:

// Display "AcmeHelloBundle"
echo $this->getRequest()->attributes->get('_template')->get('bundle');

And inside a Twig template:

{{ app.request.get('_template').get('bundle') }}

In order to get the controller name in the controller:

// Display "Default"
echo $this->getRequest()->attributes->get('_template')->get('controller');

And inside a Twig template:

{{ app.request.get('_template').get('controller') }}

In order to get the action name in the controller:

// Displays "index"
echo $this->getRequest()->attributes->get('_template')->get('name');

And inside a Twig template:

{{ app.request.get('_template').get('name') }}
like image 87
Racem Mohamed Zouaghi Avatar answered Nov 09 '22 07:11

Racem Mohamed Zouaghi


AFAIK it's not yet possible (at least in a easy way). You should use reflection. I wrote a quick and dirty service to do get bundle name ang guess entity/repository/form names based on my conventions. Can be buggy, take a look at: http://pastebin.com/BzeXAduH

It works only when you pass a class that inherits from Controller (Symfony2). Usage:

entity_management_guesser:
  class: Acme\HelloBundle\Service\EntityManagementGuesser

In your controller:

$guesser = $this->get('entity_management_guesser')->inizialize($this);

$bundleName  = $guesser->getBundleName();      // Acme/HelloBundle
$bundleShort = $guesser->getBundleShortName(); // AcmeHelloBundle

Another possibility would be using kernel to get all bundles: Get a bundle name from an entity

like image 20
gremo Avatar answered Nov 09 '22 08:11

gremo


Well you can get the controller of the current route by,

$request->attributes->get('_controller');

You can parse the bundle name from it.

like image 6
Mun Mun Das Avatar answered Nov 09 '22 08:11

Mun Mun Das