Wednesday, January 21, 2009

Pass action as Facelets-Parameter

There is a problem to pass an action as a Facelet-Parameter to a Fragment via ui:include an ui:param.
With the J4Fry-Action-Wrapper (http://www.j4fry.org/jsfErrorhandling.shtml) as a part of the J4Fry-JSF-Components (http://www.j4fry.org/jsfComponents.shtml) you've got the possibility to pass the action (e.g. for a h:commandButton) to a Facelets-Fragment.

Example
Main-Page

...
<ui:include src="Fragments/myFragment.xhtml">
<ui:param name="myAction" value="myBean.doSomething" />
</ui:include>
...

Fragment

<h:commandButton value="Execute doSomething" action="#{action[myAction].trigger}" />

To use that solution you have to download the J4Fry-JSF-Components (with dependencies described here: http://www.j4fry.org/jsfComponents.shtml) and place the JAR-File into your lib-directory from the webapplication. Thats it!

2 comments:

  1. Thanks a lot for providing this feature.
    I am looking for this feature in my application.

    One question:

    How do I pass agruments to the action?

    ReplyDelete
  2. For JSF 1.x you can use the "Map-Hack" for passing arguments. Unfortunately it isn't possible to pass arguments directly to an action.

    So here's the Map hack:

    1. Create a class that implements the java.util.Map interface (or extends one of the Map implementations e.g. java.util.HashMap)

    public class MapHack implements Map<Object, Object> {
    ...
    }

    2. You have to implement the "get(Object key)" method

    public Object get(Object key) {
    // key will be your argument
    // put the argument in a bean via a value expression or call a method via a method expression
    ...
    }

    3. Declare your "Map" in the faces-config.xml
    <managed-bean>
    <managed-bean-name>mapHack</managed-bean-name>
    <managed-bean-class>org.j4fry.MapHack</managed-bean-class>
    <managed-bean-scope>request</managed-bean-scope>
    </managed-bean>

    4. Use the map in EL (e.g in a "value"-attribute of a h:inputText)
    #{mapHack['myArgument']}

    5. Or you can pass a property of another bean which is declared in your faces-config
    #{mapHack[myBean.myProperty]}

    6. You have to cast the argument in the get Method of your Map to a String.
    _________________________________________

    For JSF 2.0 a new method invocation is supported (for EE 6). To read more see http://blogs.sun.com/kchung/entry/jsr_245_mr_part_i

    Alex

    ReplyDelete