In this blog article, we take a look at the creation of custom Sitecore SXA renderingds and components. The blog post example has been created on following versions:
Below we will see the steps to create SXA compatible custom rendering and SXA compatibility should have the following features:
Here, we're taking an example of a custom carousel where we have the following requirements and global settings:
Each carousel slide can have:
Creating the Carousel
Following steps are required to create the above carousel.
Step 1 - Creating Sitecore Templates for Required Custom Fields
SXA is created from Helix principles, we've chosen "Media" as a feature to create the carousel in. The media folder will have 2 sub folders, Datasource and Rendering Parameters.
Datasource will have the Carousel Folder where all carousels will be created; the Carousel Template will have the global carousel properties like background colour and Carousel Slide with each slide properties.
Rendering Parameters folder will have Carousel rendering parameters and can inherit from OOTB templates like:
Step 2 - Create a Custom Carousel Controller Rendering
And we need to add this rendering to the list of available renderings to make it appear in the SXA toolbox:
Now jumping to the code.
Step 3 - We Need to add a Controller "CustomCurouselController" to Feature Media
As we can see in the above screenshot the controller needs to be inherited from "StandardContoller", which can be found under namespace "Sitecore.XA.Foundation.Mvc.Controllers".
You may have noted that we did not add any "ActionResult" to the controller class and nor did we have it in the Sitecore rendering. This is because the Standard controller will take care of your routing from the controller to view with default action result "Index". We can also add and override "Index" Actionresult here in the controller if required.
Step 4 - We need a Carousel Model to Create / Fetch Custom Carousel Properties
Our custom model should inherit from "VariantRenderingModel" which will hold some base SXA properties like: Datasource item, css class, heading tag, IsEdit etc.
Step 5 - The Repository will be as Follows
Should inherit from "VariantsRepository", which will make our custom carousel rendering extendible through variants.
"FillBaseProperties" is an OOB SXA method found under namespace "Sitecore.XA.Foundation.RenderingVariants.Repositories" which will fill the base SXA properties in our model.
Step 6 - Adding a View to the Media Project for Custom Carousel
Note: Every SXA component should be wrapped inside a div "component" and "component-content". Also, "Model.Attribute" will be used to add styles from the rendering parameters. (Refer any existing SXA view). That should be it!
We can see the new custom carousel in the toolbox and drag and drop it. Add a new partial view to quickly test it:
We can see the rendering in the toolbox: