Issue
- How to display dynamic data on bar and graph charts in Liferay DXP?
Environment
- Liferay DXP 7.4
Resolution
NOTE: The following resolution requires customization and should only be implemented at the discretion of your team. Liferay Support will not be able to assist with designing or implementing customizations.
- In the service.xml file, users need to add two columns that define an entity Bar with two fields: DataValue1 and DataValue2. The entity is configured to generate services for database operations.
<entity local-service="true" name="Bar" remote-service="true" uuid="true">
<column name="DataValue1" primary="true" type="long" />
<column name="DataValue2" type="long" />
</entity> -
The following processAction method retrieves two numeric values (data1 and data2) submitted by the user using the form. It generates a unique ID for a new Bar object using Liferay's counter service. The method then stores the user's data in this Bar object and saves it to the database using Liferay's service layer.
public void processAction(ActionRequest actionRequest, ActionResponse actionResponse) {
long data1 = ParamUtil.getLong(actionRequest, "data1");
long data2 = ParamUtil.getLong(actionRequest, "data2");
long barId = CounterLocalServiceUtil.increment(Bar.class.getName());
Bar bar = BarLocalServiceUtil.createBar(barId);
bar.setDataValue1(data1);
bar.setDataValue2(data2);
BarLocalServiceUtil.addBar(bar);
} -
Below render method fetches a list of all Bar entities from the database using BarLocalServiceUtil. It then iterates through the list, concatenating the DataValue1 and DataValue2 values into two comma-separated strings (data1 and data2). These values are set as request attributes (data1Input and data2Input) so they can be accessed in the JSP. Finally, it is called the superclass's render method to complete the rendering process.
public void render(RenderRequest renderRequest, RenderResponse renderResponse)
throws IOException, PortletException {
List<Bar> barList = BarLocalServiceUtil.getBars(-1, -1);
String data1 = "";
String data2 = "";
for (Bar eachBar : barList) {
if (Validator.isNotNull(data1) && Validator.isNotNull(data2)) {
data1 += "," + eachBar.getDataValue1();
data2 += "," + eachBar.getDataValue2();
} else {
data1 = String.valueOf(eachBar.getDataValue1());
data2 = String.valueOf(eachBar.getDataValue2());
}
}
renderRequest.setAttribute("data1Input", data1);
renderRequest.setAttribute("data2Input", data2);
super.render(renderRequest, renderResponse);
} -
Below JSP code splits the
data1Inputanddata2Inputstrings into arrays, converts them to integer lists and adds these values as columns to anBarChartConfigthe object for rendering a bar chart.