Search code examples
jsfprimefacesuicomponents

Pass current UIComponent as "this" in action MethodExpression


Is there a possibility to pass current UIComponent as this in action's MethodExpression?

XHTML

<p:menuitem id="test" value="Test" action="#{controller.test(this)}" update="test" />

Java

public String test(MenuItem item) {
    // Do something with item
    return null;
}

Solution

  • You can use the implicit EL variable #{component} for this:

    <p:menuitem ... action="#{controller.test(component)}" />
    

    with

    public void test(UIComponent component) {
        // ...
    }
    

    Or if you're only interested in for example the id attribute:

    <p:menuitem ... action="#{controller.test(component.id)}" />
    

    with

    public void test(String id) {
        // ...
    }
    

    Or if you're only interested in for example the value attribute:

    <p:menuitem ... action="#{controller.test(component.value)}" />
    

    with

    public void test(String value) {
        // ...
    }
    

    You can alternatively also use UIComponent#getCurrentComponent() for this:

    <p:menuitem ... action="#{controller.test}" />
    

    with

    public void test() {
        UIComponent component = UIComponent.getCurrentComponent(FacesContext.getCurrentInstance());
        String id = component.getId();
        String value = ((MenuItem) component).getValue();
        // ...
    }