Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the action name in a Symfony2 controller?

Is there a way to get the name of the action in a Symfony2 controller?

public function createAction(Request $request, $title) {

    // Expected result: create
    $name = $this->getActionName();

}
like image 712
Gottlieb Notschnabel Avatar asked Apr 04 '14 02:04

Gottlieb Notschnabel


2 Answers

use:

$request->attributes->get('_controller');
// will get yourBundle\Controller\yourController::CreateAction

$params = explode('::',$request->attributes->get('_controller'));
// $params[1] = 'createAction';

$actionName = substr($params[1],0,-6);
// $actionName = 'create';
like image 131
Leo Silence Avatar answered Sep 28 '22 08:09

Leo Silence


I found this snippet (here):

$matches    = array();
$controller = $this->getRequest()->attributes->get('_controller');
preg_match('/(.*)\\\(.*)Bundle\\\Controller\\\(.*)Controller::(.*)Action/', $controller, $matches);

which seems to be a promising approach. This regexp actually doesn't work. But it won't be hard to fetch the action name by using strstr(). Works!

And returns (see example)

Array
(
    [0] => Acme\MyBundle\Controller\MyController::myAction
    [1] => Acme
    [2] => My
    [3] => My
    [4] => my
)

If input was Acme\MyBundle\Controller\MyController::myAction.

like image 39
Gottlieb Notschnabel Avatar answered Sep 28 '22 06:09

Gottlieb Notschnabel