Looking for a JavaEE Architect or Potential Tech Co-Founder?
Please don't hesitate to contact me.

Avoid the JSF preRenderView on CRUD edit mode

Long time ago I learned that the usual approach in CRUD is list, add, edit, delete. And right now I'm implementing the same thing in JavaEE6, Glassfish, JSF 2.1, Primefaces. So what I did was:

1.) Create a single backing bean that will handle all the operations.

2.) Create a list page, where add, edit and delete action is defined. Delete do not need a page but a backing bean action that will delete the selected object and refresh the page.

3.) Create an edit page that will be render when the edit action is clicked on the list page. Now this edit page must submit the id of the object. And the id must be converted to object. See the code below.

On the list page we have a definition for the edit action:
<p:column headerText="#{msgs['common.update']}" style="width:50px">
 <p:commandButton action="update.xhtml" ajax="false"
  icon="ui-icon-pencil">      
  <f:param name="marketingCode" value="#{code.id}"></f:param>
 </p:commandButton>
</p:column>

On the update.xhtml, we have to define a preRenderView event:
<f:metadata>
 <f:param name="dummy"></f:param>
 <f:viewParam name="marketingCode"
  value="#{marketingCodeBean.marketingCode}"
  converter="#{marketingCodeConverter}" />
 <f:event listener="#{marketingCodeBean.preRenderViewEdit()}"
  type="preRenderView" />
</f:metadata>

Define the event on the backing bean:
public void preRenderViewEdit() {
 log.debug("preRenderViewEdit");
 if (marketingCode == null) {
  marketingCode = new MarketingCode();
 }
}

And finally we have a save button on the edit page. But with this approach we will encounter the famous problem with the preRenderView event being called when the save action is invoke and validation failed. Or when a partial form is submitted. So you see we have to implement several checks on the preRender event method just to get away with it. My simple solution, that fits my requirement is to set a backing bean property inside the edit action definition. So in my case it'll be:
<p:commandButton action="update.xhtml" ajax="false"
      icon="ui-icon-pencil">
 <f:setPropertyActionListener
  target="#{marketingCodeBean.marketingCode}" value="#{code}"></f:setPropertyActionListener>
</p:commandButton>

And that solves my problem of transferring the id of the selected object from list page to update page.
Avoid the JSF preRenderView on CRUD edit mode Avoid the JSF preRenderView on CRUD edit mode Reviewed by Edward Legaspi on Wednesday, January 02, 2013 Rating: 5

No comments:

Powered by Blogger.