![]() |
|
Snippets |
|
The list view of the admin generator currently always displays all defined object actions for each object. There is no way to display an object action for an object only if some condition on this object is met.
In order to extend the admin generator with this functionality only a small enhancement is required. You can either apply this change per module or create a new admin generator theme as described in the Symfony book.
The templates/_list_td_actions.php has to be extended to look roughly like this, depending on whether you already have your own modifications in there:
<?php if ($this->getParameterValue('list.object_actions')): ?> <td> <ul class="sf_admin_td_actions"> <?php foreach ($this->getParameterValue('list.object_actions') as $actionName => $params): ?> <?php if ( isset( $params['condition'] ) ): ?> [?php if ( <?php echo ( isset( $params['condition']['invert'] ) && $params['condition']['invert'] ? '!' : '') . '$' . $this->getSingularName( ) . '->' . $params['condition']['function'] ?>( <?php echo ( isset( $params['condition']['params'] ) ? $params['condition']['params'] : '' ) ?> ) ): ?] <?php endif; ?> <?php echo $this->addCredentialCondition($this->getLinkToAction($actionName, $params, true), $params) ?> <?php if ( isset( $params['condition'] ) ): ?> [?php endif; ?] <?php endif; ?> <?php endforeach; ?> </ul> </td> <?php endif; ?>
With this enhancement you can now use conditions for your actions in the generator.yml. The syntax should be pretty self-explanatory. An example would look like this:
object_actions:
subscribe: { name: Notify when changed, action: subscribe, icon: pencil_add.png }
condition:
function: isUserSubscribed
params: "$sf_user, 'test'"
invert: true
As you can see each object action now also takes a condition parameter, which again takes a number of parameter.
function is the function of the object that will be called. It will be evaluated as boolean. Required!params is a string that will be passed verbatim to the function, so if you need several parameters make sure to enclose them in quotes. Since the function will be called from the view layer you have access to all data available there such as $sf_user. Defaults to an empty stringinvert will invert the return value of the function so saving you an additional function if you need something like subscribe / unsubscribe actions. Defaults to false.Enjoy!