May
22
2009

Building a modular component for Magnolia - Part 1

Let’s say: I would like to have  on my site a html component which let me see next days weather forecast.

This component can be configured for each instance (e.g.: on home I would like to see a summary and on other pages I would like to see a detailed forecast).

This component can also answer to specific parameters (e.g.: ?showTime=true / ?forecastDate=2009.05.23).

Ok, we are ready to start!

01 - Build an empty component

Create a new Java class, call it WeatherStation.java

package com.mycompany.magnolia.modules;
 
import javax.servlet.http.HttpServletRequest;
import info.magnolia.cms.core.Content;
 
public class WeatherStation {
 
  public WeatherStation((HttpServletRequest request, Content config)){
    //...
    System.out.println("component weather instantiated!");
  }
 
}

Now, create a new paragraph renderer, WeatherStationParagraphRenderer.java:

package com.mycompany.magnolia.modules;
 
import javax.servlet.http.HttpServletRequest;
import info.magnolia.cms.core.Content;
 
public class WeatherStationParagraphRenderer implements ParagraphRenderer{
 
  //...
 
  public void render(Content content, Paragraph paragraph, Writer out) throws IOException {
 
  //...
 
  HttpServletRequest request = ((WebContext)ctx).getRequest();
  WeatherStation weatherStationComponent = new WeatherStation (request, content);
 
  //..
  }
 
}

This because we want to “emulate” a MVC lifecycle, instantiating object outside the rendering JSP templates.

At this point we can log-in to Magnolia AdminCentral and configure a paragraph, making it pointing to the right paragraphRenderer (add one or use one you can edit, not the default one). Remember to add a paragraph and a dialog too.

config

Click on this picure to enlarge.

The corresponding eclipse project structure is the following:

eclipse-config

To complete, this is the code inside main.jsp

<%@ taglib prefix="cms" uri="cms-taglib"%>
<cms:editBar editLabel="Edit" moveLabel="Move" deleteLabel="Delete" showParagraphName="true" />
 
<p>Weather station is alive</p>

and inside weatherStationTest.jsp

<%@ taglib prefix="cms" uri="cms-taglib"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
 
<html>
	<head>
		<cms:links />
		<title>Test Weather Station</title>
	</head>
	<body>
		<p>Ready for testing</p>
		<cms:newBar contentNodeCollectionName="mainAreaComponents" paragraph="weather-station" newLabel="Add" />
 
		<cms:contentNodeIterator contentNodeCollectionName="mainAreaComponents">
			<cms:includeTemplate />
		</cms:contentNodeIterator>
	</body>
</html>

Ok, if everything is done correctly you can add a new page, add a template and add all Magnolia standard taglibs to handle paragraph instantiation:

website

And the output should be that:
ready

Of course, on the log file you should see the message: component weather instantiated!

Leave a Reply