Symfony: Add custom template parameters in EasyAdmin

When creating a customized admin backend with EasyAdmin you might want to add custom parameters to a template. Lets say you want to add additional parameters to the editAction(), you will find out that the template parameters are hard coded in the AdminController.php and can not be extended.

The AdminController.php has a method “renderTemplate()” which can be extended to inject custom parameters into the template.

protected function renderTemplate($actionName, $templatePath, array $parameters = [])
return $this->render($templatePath, $parameters);

EasyAdmin suggests to extend this method and use the $actionName parameter to do a switch(). So you will have to add all parameters for all templates for all actions in one single method. This will get a mess very quick. There was already a discussion to add better template parameter support and it was added as “Might be implemented” to the Feature Board of the EasyAdmin project.

As a cleaner approach I came up with a custom renderTemplate() method which replaces the original one. It will check if an action-specific render method exists in your custom controller and will use it instead. For example if you have a CustomController.php which has a renderEditTemplate() method, it will be automatically used and you can inject your template parameters as needed.

You will have to extend the original AdminController.php of EasyAdmin, implement the customized renderTemplate() method. Then all your custom controllers have the extended from the custom AdminController. In your custom controllers you can define any render[ACTION]template() method. The custom render method will be automatically called before the template is rendered.

Please find the complete code in the following gist: