Adding Custom CMS component in Hybris

In this requirement, we are going to create a completely new component type and add it to the page.

Let’s say the requirement is to display the Offers on the Home page, where Offers component should include the attributes like images,header text of the offer,footer text of the offer.


So Our aim is to create a new CMS component type to add these attributes into it and display it in the page


Lets see the steps below to achieve the same.

1) Create a new CMS component type by defining in the *items.xml
hybris\bin\custom\training\trainingcore\resources\trainingcore-items.xml

2)Write an impex statements for adding the new component item type instance and to add the newly created CMS component to a home page by assigning it to the right content slot

3)Create the controller and JSP page for the new component

4)Add this new component into the Home page JSP using CMS tags

5)Open the Home page and Verify to check new component


Step 1

Create a new CMSComponent in *items.xml

  1. <itemtype code="CustomOffersComponent" extends="SimpleCMSComponent" generate="true" autocreate="true"
  2.             jaloclass="org.training.core.jalo.CustomOffersComponent">
  3.             <description>Used to display offers on homepage</description>
  4.                 <attributes>
  5.                     <attribute type="localized:java.lang.String" qualifier="headrerText">
  6.                         <modifiers read="true" write="true" optional="false" />
  7.                         <persistence type="property" />
  8.                     </attribute>
  9.                     <attribute type="localized:java.lang.String" qualifier="footerText">
  10.                         <modifiers read="true" write="true" optional="false" />
  11.                         <persistence type="property" />
  12.                     </attribute>
  13.                     <attribute type="Media" qualifier="offerImage">
  14.                         <modifiers read="true" write="true" optional="false" />
  15.                         <persistence type="property" />
  16.                     </attribute>
  17.                     <attribute type="CustomOfferLinksList" qualifier="offerImageLink">
  18.                         <persistence type="property" />
  19.                         <description>List of CMS Link Component</description>
  20.                         <modifiers read="true" write="true" />
  21.                     </attribute>
  22.                 </attributes>
  23.             </itemtype>
<itemtype code="CustomOffersComponent" extends="SimpleCMSComponent" generate="true" autocreate="true"
			jaloclass="org.training.core.jalo.CustomOffersComponent">
			<description>Used to display offers on homepage</description>
				<attributes>
					<attribute type="localized:java.lang.String" qualifier="headrerText">
						<modifiers read="true" write="true" optional="false" />
						<persistence type="property" />
					</attribute>
					<attribute type="localized:java.lang.String" qualifier="footerText">
						<modifiers read="true" write="true" optional="false" />
						<persistence type="property" />
					</attribute>
					<attribute type="Media" qualifier="offerImage">
						<modifiers read="true" write="true" optional="false" />
						<persistence type="property" />
					</attribute>
					<attribute type="CustomOfferLinksList" qualifier="offerImageLink">
						<persistence type="property" />
						<description>List of CMS Link Component</description>
						<modifiers read="true" write="true" />
					</attribute>
				</attributes>
			</itemtype>

Add below collection type for CMSLinkComponent Collection type attribute in the same items.xml file under collectiontypes tag

  1. <collectiontype code="CustomOfferLinksList" elementtype="CMSLinkComponent" autocreate="true" generate="true" type="list" />
<collectiontype code="CustomOfferLinksList" elementtype="CMSLinkComponent" autocreate="true" generate="true" type="list" />

Do ant all and refresh the platform after build success.

We can now see that CustomOffersComponentModel.java class created with all the attributes as we defined in *items.xml file

Now only java class is generated but table for this new component is not yet created.

So do the update system, so that table will be created for this new item type


Step 2

We need to write an impex to add the data for this new component type.

Since new component item type has some of the composed types(like CMSLinkComponent,Media),
lets define the impex for those composed types first.

Note: Write all these impexes in the file specified below
hybris\bin\ext-data\apparelstore\resources\apparelstore\import\sampledata\contentCatalogs\apparel-ukContentCatalog\cms-content.impex

Impex for CMSLinkComponent

  1. #Custom offers components
  2. INSERT_UPDATE CMSLinkComponent;$contentCV[unique=true];uid[unique=true];name;url;&linkRef;&componentRef;target(code)[default='sameWindow'];$category;
  3.  
  4. ;;MenOfferLink;Men Offer Link;/MenOfferLink;MenOfferLink;MenOfferLink;;;;
  5.  
  6. ;;WomenOfferLink;Women Offer Link;/WomenOfferLink;WomenOfferLink;WomenOfferLink;;;;
  7.  
  8. ;;KidsOfferLink;Kids Offer Link;/KidsOfferLink;KidsOfferLink;KidsOfferLink;;;;
#Custom offers components
INSERT_UPDATE CMSLinkComponent;$contentCV[unique=true];uid[unique=true];name;url;&linkRef;&componentRef;target(code)[default='sameWindow'];$category;

;;MenOfferLink;Men Offer Link;/MenOfferLink;MenOfferLink;MenOfferLink;;;;

;;WomenOfferLink;Women Offer Link;/WomenOfferLink;WomenOfferLink;WomenOfferLink;;;;

;;KidsOfferLink;Kids Offer Link;/KidsOfferLink;KidsOfferLink;KidsOfferLink;;;;

Impex for Media

  1. INSERT_UPDATE Media;$contentCV[unique=true];code[unique=true];@media[translator=de.hybris.platform.impex.jalo.media.MediaDataTranslator];mime[default='image/jpeg'];&imageRef;folder(qualifier)[default='images'];altText
  2. ;;customOffersMedia;$siteResource/images/banners/homepage/offers.jpeg;;offers.jpeg;;
INSERT_UPDATE Media;$contentCV[unique=true];code[unique=true];@media[translator=de.hybris.platform.impex.jalo.media.MediaDataTranslator];mime[default='image/jpeg'];&imageRef;folder(qualifier)[default='images'];altText
;;customOffersMedia;$siteResource/images/banners/homepage/offers.jpeg;;offers.jpeg;;

Impex for CustomOffersComponent

  1. INSERT_UPDATE CustomOffersComponent;$contentCV[unique=true];uid[unique=true];name;headrerText[lang=$lang];footerText[lang=$lang];offerImage(code);&componentRef;offerImageLink(&linkRef);
  2. ;;summerOfferComponent;Summer offer Component;"up to 70 % off";"Grab this offer on all summer<br>Collections";customOffersMedia;summerOfferComponent;MenOfferLink,WomenOfferLink,KidsOfferLink
INSERT_UPDATE CustomOffersComponent;$contentCV[unique=true];uid[unique=true];name;headrerText[lang=$lang];footerText[lang=$lang];offerImage(code);&componentRef;offerImageLink(&linkRef);
;;summerOfferComponent;Summer offer Component;"up to 70 % off";"Grab this offer on all summer<br>Collections";customOffersMedia;summerOfferComponent;MenOfferLink,WomenOfferLink,KidsOfferLink

Note: Copy any image to the below path to have media reference, the same image appears on the Home page after completing the requirement
Make sure the name of the image should be offers.jpeg, else change the impex accordingly.

hybris\bin\ext-data\apparelstore\resources\apparelstore\import\sampledata\contentCatalogs\apparel-ukContentCatalog\images\banners\homepage


Now define the content slot and link the component to it


Impex for defining content slot name

  1. INSERT_UPDATE ContentSlotName;name[unique=true];template(uid,$contentCV)[unique=true][default='LandingPage2Template'];validComponentTypes(code);compTypeGroup(code)
  2. ;SummerOffersSlotName;;CustomOffersComponent
INSERT_UPDATE ContentSlotName;name[unique=true];template(uid,$contentCV)[unique=true][default='LandingPage2Template'];validComponentTypes(code);compTypeGroup(code)
;SummerOffersSlotName;;CustomOffersComponent

Impex for defining content slot

  1. INSERT_UPDATE ContentSlot;$contentCV[unique=true];uid[unique=true];name;active;cmsComponents(&componentRef)
  2. ;;summerOfferContentSlot;Summer offer slot;true;summerOfferComponent
INSERT_UPDATE ContentSlot;$contentCV[unique=true];uid[unique=true];name;active;cmsComponents(&componentRef)
;;summerOfferContentSlot;Summer offer slot;true;summerOfferComponent

Impex for defining content slot for page

  1. INSERT_UPDATE ContentSlotForPage;$contentCV[unique=true];uid[unique=true];position[unique=true];page(uid,$contentCV)[unique=true][default='homepage'];contentSlot(uid,$contentCV)[unique=true]
  2. ;;summerOfferslotforpage-Homepage;SummerOffersSlotName;;summerOfferContentSlot
INSERT_UPDATE ContentSlotForPage;$contentCV[unique=true];uid[unique=true];position[unique=true];page(uid,$contentCV)[unique=true][default='homepage'];contentSlot(uid,$contentCV)[unique=true]
;;summerOfferslotforpage-Homepage;SummerOffersSlotName;;summerOfferContentSlot

Make sure below lines are added at the beginning of the cms-content.impex to avoid any errors

  1. $contentCatalog=apparel-ukContentCatalog
  2. $contentCV=catalogVersion(CatalogVersion.catalog(Catalog.id[default=$contentCatalog]),CatalogVersion.version[default=Staged])[default=$contentCatalog:Staged]
  3. $productCatalog=apparelProductCatalog
  4. $productCatalogName=Apparel Product Catalog
  5. $productCV=catalogVersion(catalog(id[default=$productCatalog]),version[default='Staged'])[unique=true,default=$productCatalog:Staged]
  6. $picture=media(code, $contentCV) ;
  7. $siteResource=jar:de.hybris.platform.apparelstore.constants.ApparelstoreConstants&/apparelstore/import/sampledata/contentCatalogs/$contentCatalog
  8. $jarResourceCms=jar:de.hybris.platform.apparelstore.constants.ApparelstoreConstants&/apparelstore/import/sampledata/cockpits/cmscockpit
  9. # Load the storefront context root config param
  10. $storefrontContextRoot=$config-storefrontContextRoot
  11. $lang=en
  12. $category=category(code, $productCV)
$contentCatalog=apparel-ukContentCatalog 
$contentCV=catalogVersion(CatalogVersion.catalog(Catalog.id[default=$contentCatalog]),CatalogVersion.version[default=Staged])[default=$contentCatalog:Staged] 
$productCatalog=apparelProductCatalog 
$productCatalogName=Apparel Product Catalog 
$productCV=catalogVersion(catalog(id[default=$productCatalog]),version[default='Staged'])[unique=true,default=$productCatalog:Staged] 
$picture=media(code, $contentCV) ;
$siteResource=jar:de.hybris.platform.apparelstore.constants.ApparelstoreConstants&/apparelstore/import/sampledata/contentCatalogs/$contentCatalog
$jarResourceCms=jar:de.hybris.platform.apparelstore.constants.ApparelstoreConstants&/apparelstore/import/sampledata/cockpits/cmscockpit
# Load the storefront context root config param
$storefrontContextRoot=$config-storefrontContextRoot
$lang=en
$category=category(code, $productCV)

Note:
We are defining the content slot directly for page rather than template, doing so will just add this slot only to the page not to the template


Step 3


Create the custom controller and JSP for the new component

We can either extend the AbstractCMSComponentController or DefaultCMSComponentController for our custom controller.

AbstractCMSComponentController has no implementation for fillModel() method whereas DefaultCMSComponentController has overridden it and provided the definition for fillModel() method.

Note:If we dont provide our own controller, then above controllers will be called by Hybris automatically but its not a good practice to use like that for new component

Let’s extend our class with AbstractCMSComponentController as we are going to write our own implementation for fillModel() method as below

Create the below class in the same package where AbstractCMSComponentController is available

  1. package org.training.storefront.controllers.cms;
  2.  
  3. import javax.servlet.http.HttpServletRequest;
  4.  
  5. import org.springframework.context.annotation.Scope;
  6. import org.springframework.stereotype.Controller;
  7. import org.springframework.ui.Model;
  8. import org.springframework.web.bind.annotation.RequestMapping;
  9. import org.training.core.model.CustomOffersComponentModel;
  10. import org.training.storefront.controllers.ControllerConstants;
  11. @Controller("CustomOffersComponentController")
  12. @Scope("tenant")
  13. @RequestMapping(value = ControllerConstants.Actions.Cms.CustomOffersComponent)
  14. public class CustomOffersComponentController extends AbstractCMSComponentController<CustomOffersComponentModel>
  15. {
  16.     @Override
  17.     protected void fillModel(final HttpServletRequest request, final Model model, final CustomOffersComponentModel component)
  18.     {
  19.         model.addAttribute("offerImageLinks", component.getOfferImageLink());
  20.  
  21.         model.addAttribute("offerImage", component.getOfferImage());
  22.  
  23.         model.addAttribute("headerText", component.getHeadrerText());
  24.  
  25.         model.addAttribute("footerText", component.getFooterText());
  26.     }
  27. }
package org.training.storefront.controllers.cms;

import javax.servlet.http.HttpServletRequest;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.training.core.model.CustomOffersComponentModel;
import org.training.storefront.controllers.ControllerConstants;
@Controller("CustomOffersComponentController")
@Scope("tenant")
@RequestMapping(value = ControllerConstants.Actions.Cms.CustomOffersComponent)
public class CustomOffersComponentController extends AbstractCMSComponentController<CustomOffersComponentModel>
{
	@Override
	protected void fillModel(final HttpServletRequest request, final Model model, final CustomOffersComponentModel component)
	{
		model.addAttribute("offerImageLinks", component.getOfferImageLink());

		model.addAttribute("offerImage", component.getOfferImage());

		model.addAttribute("headerText", component.getHeadrerText());

		model.addAttribute("footerText", component.getFooterText());
	}
}

Also make sure the RequestMapping value is defined in the ControllerConstants.java file(\hybris\bin\custom\training\trainingstorefront\web\src\org\training\storefront\controllers\ControllerConstants.java)

add new constant value inside Actions Interface and inside CMS interface,it should be something like as below

  1. public interface ControllerConstants
  2. {
  3. interface Actions
  4.     {
  5.         interface Cms
  6.         {
  7.             //All the existing lines goes here
  8.  
  9.             String CustomOffersComponent = _Prefix + CustomOffersComponentModel._TYPECODE + _Suffix;
  10.         }
  11.     }
  12. //All the existing lines goes here
  13. }
public interface ControllerConstants
{
interface Actions
	{
		interface Cms
		{
			//All the existing lines goes here

			String CustomOffersComponent = _Prefix + CustomOffersComponentModel._TYPECODE + _Suffix;
		}
	}
//All the existing lines goes here
}

Create a new jsp page called customOffersComponent.jsp as below
(/trainingstorefront/web/webroot/WEB-INF/views/desktop/cms/customOffersComponent.jsp)

  1. <%@ page trimDirectiveWhitespaces="true" %>
  2. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
  3. <%@ taglib prefix="template" tagdir="/WEB-INF/tags/desktop/template" %>
  4. <%@ taglib prefix="theme" tagdir="/WEB-INF/tags/shared/theme" %>
  5. <%@ taglib prefix="nav" tagdir="/WEB-INF/tags/desktop/nav" %>
  6. <%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
  7. <%@ taglib prefix="cms" uri="http://hybris.com/tld/cmstags" %>
  8. <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
  9. <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
  10. <%@ taglib prefix="ycommerce" uri="http://hybris.com/tld/ycommercetags" %>
  11. <%@ taglib prefix="common" tagdir="/WEB-INF/tags/desktop/common" %>
  12. <%@ taglib prefix="breadcrumb" tagdir="/WEB-INF/tags/desktop/nav/breadcrumb" %>
  13. <div class="customOffersComponent">
  14. <p class="customOffersComponent_header_text">${headerText}</p>
  15. <img alt="Offer Image" src="${offerImage.url}" class="offers_image">
  16. <ul class="offers_list">
  17. <c:forEach items="${offerImageLinks}" var="offerImageLink">
  18. <li class="offers_list_element"><a href="${offerImageLink.url}">${offerImageLink.name}</a></li>
  19. </c:forEach>
  20. </ul>
  21. <p class="customOffersComponent_header_text">${footerText}</p>
  22. </div>
<%@ page trimDirectiveWhitespaces="true" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="template" tagdir="/WEB-INF/tags/desktop/template" %>
<%@ taglib prefix="theme" tagdir="/WEB-INF/tags/shared/theme" %>
<%@ taglib prefix="nav" tagdir="/WEB-INF/tags/desktop/nav" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@ taglib prefix="cms" uri="http://hybris.com/tld/cmstags" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ taglib prefix="ycommerce" uri="http://hybris.com/tld/ycommercetags" %>
<%@ taglib prefix="common" tagdir="/WEB-INF/tags/desktop/common" %>
<%@ taglib prefix="breadcrumb" tagdir="/WEB-INF/tags/desktop/nav/breadcrumb" %>
<div class="customOffersComponent">
<p class="customOffersComponent_header_text">${headerText}</p>
<img alt="Offer Image" src="${offerImage.url}" class="offers_image">
<ul class="offers_list">
<c:forEach items="${offerImageLinks}" var="offerImageLink">
<li class="offers_list_element"><a href="${offerImageLink.url}">${offerImageLink.name}</a></li>
</c:forEach>
</ul>
<p class="customOffersComponent_header_text">${footerText}</p>
</div>

In the above JSP file, we have just added the new component attributes for display.

Add the CSS properties in CSS file for UI change

Add the below lines at the end to landingLayout2Page.css file for the same as below
(hybris\bin\custom\training\trainingstorefront\web\webroot\_ui\desktop\common\css\landingLayout2Page.css)

  1. .customOffersComponent{
  2.     border:1px dotted #a5a5a5;
  3.     border-width:1px 0 ;
  4.     position:relative;
  5. }
  6.  
  7. .customOffersComponent_header_text .customOffersComponent_header_text{
  8.     border-bottom:1px solid #a5a5a5;
  9.     height:30px;
  10.     line-height:30px;
  11.     text-transform:uppercase;
  12.     font-weight:bold;
  13.     font-size:1em;
  14.     white-space: nowrap;
  15.     display:block;
  16.     margin:0 0 10px 0;
  17. }
  18. .offers_list{
  19.     margin: 20px 0;
  20.     padding: 5px;
  21.     border: 1px dotted #000;   
  22. }
  23. .offers_list_element{
  24.     vertical-align:top;
  25.     border-bottom:1px dotted #a5a5a5;
  26.     padding:20px 0 0 0;
  27. }
  28.  
  29. .offers_image{
  30.     float:left;
  31.     text-align:center;
  32.    
  33. }
.customOffersComponent{
	border:1px dotted #a5a5a5;
	border-width:1px 0 ;
	position:relative;
}

.customOffersComponent_header_text .customOffersComponent_header_text{
	border-bottom:1px solid #a5a5a5;
	height:30px;
	line-height:30px;
	text-transform:uppercase;
	font-weight:bold;
	font-size:1em;
	white-space: nowrap;
	display:block;
	margin:0 0 10px 0;
}
.offers_list{
	margin: 20px 0;
	padding: 5px;
	border: 1px dotted #000;	
}
.offers_list_element{
	vertical-align:top;
	border-bottom:1px dotted #a5a5a5;
	padding:20px 0 0 0;
}

.offers_image{
	float:left;
	text-align:center;
	
}


Step 4

Add this component into the Home page jsp using CMS tags

Open landingLayout2Page.jsp and add the below code(for now , add it below Section5 pageSlot)

  1. <cms:pageSlot position="SummerOffersSlotName" var="feature" element="div" class="span-24 section5 cms_disp-img_slot">
  2. <cms:component component="${feature}" />
  3. </cms:pageSlot>
<cms:pageSlot position="SummerOffersSlotName" var="feature" element="div" class="span-24 section5 cms_disp-img_slot">
<cms:component component="${feature}" />
</cms:pageSlot>

Note: position that we have added here should be same as content slot name in the impex.


Step 5

Do ant all, Update system and make sure the content catalog is copied from Staged to Online(if not done then synchronize it)

Open the Home page in the site and check the output

Homepage after adding new offer component

In the Home Page, we are getting our custom component displayed and highlighted the 4 attributes of the component rendered as we defined.

About the Author

Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on