Today I would like to address such a topic.
How to provide alternative CMS component controller logic without creation of new CMS component type?
Let’s assume you have a CMS component item with a dedicated controller executing some logic within the fillModel method. For many pages this logic is correct but there is one or more when you have to do some additional actions.
Let’s also assume that the presentation/JSP of this component is the same (Model returned to storefront layer is the same) you only need to e.g. do some additional checks.
In common SAP Commerce solution you would have to define additional CMS component item (probably extending one which logic you want to adjust) and declare different controllers with different JSP which includes original one from an existing component
… more or less.
I came up with such need multiple times and thought that this is not good solution. I don’t want to define additional CMS item with additional controller and additional JSP when I only want modification on a controller level.
I came across a solution that meet my requirements and was easy to manage.
Modifications encloses in 3 major steps.
What I did was I extended general component render logic to allow redefine controller on each CMS component instance level. This allowed me to prepare common CMS component logic but for some cases, I was able to redeclare controller bean on CMS component instance and such instance I used on pages where the difference was needed.
- The first step is to extend AbstractCMSComponent item with the String attribute containing a controller name (this will allow us to define different that common controller for each component instance).
- Next step, optional but from my perspective nedded. ValidateInterceptor that checks if controller name attribute value matches proper syntax.
- The last step is to create a new CMSComponentRenderer which resolves controller bean based on the component controller view attribute.
And what’s your opinion about this topic. Give me some feedback in the comments section below or write if you would like some more code details about the solution.