Tuesday, June 12, 2012

CQ5 : Creating new page and adding content

In this article, I am going to explain how to create new page and content using SlingHttpRequest Object

<%@page import="com.day.cq.dam.api.Rendition"%>
<%@page import="com.day.cq.dam.api.Asset"%>
<%@page import="org.apache.sling.api.SlingHttpServletRequest"%>
<%@include file="/libs/foundation/global.jsp"%>
<%@page import="org.apache.sling.api.resource.ResourceResolver"%>

<%@page import="com.day.cq.wcm.api.Template"%>

<%
ResourceResolver resolverPage = slingRequest.getResourceResolver();
Resource resPage = resolverPage.getResource("/content/geometrixx");


We are going to read page class, so we need to adapt our Resource to Page.class

Page geoPages = resPage.adaptTo(Page.class);
if(geoPages!=null) {
Resource res2 = resolverPage.getResource(geoPages.getPath());

//The PageManager class helps us to create new pages

PageManager pm = geoPages.getPageManager();

if(pm!=null) {
pm.create("/content/","MspBoxhomeName","/apps/mspbox/templates/contentpage","MspBoxTitle");
Page newPage = pm.getPage("/content/MspHome/");
if(newPage != null)
{
Node newNode = newPage.adaptTo(Node.class);
Node cont = newNode.getNode("jcr:content");
if(newNode != null)
{
cont.addNode("par").setProperty("sling:resourceType","foundation/components/parsys");
Node parNode = cont.getNode("par");
parNode.addNode("image");
Node imageNode = parNode.getNode("image");
imageNode.setProperty("sling:resourceType","foundation/components/image");
imageNode.setProperty("fileReference","/content/dam/geometrixx/shapes/tri_equilateral.png");
parNode.addNode("text");
Node textNode = parNode.getNode("text");
textNode.setProperty("sling:resourceType","foundation/components/text");
textNode.setProperty("text","<p>With at least two equal sides, isoceles is sometimes equilateral and visa versa. Or as the ancient Greeks would say, iso skelos!</p><p></p>");
cont.save();

}
}
}
}
%>

0 comments:

Post a Comment