Get widgetVar by Id

I have many cases in my apps where I needed to get the widgetVar object in Javascript by the component Id.
I have made this helpful function in order to achieve that goal .

function getWidgetVarById(id) {
    for (var propertyName in PrimeFaces.widgets) {
      if (PrimeFaces.widgets[propertyName].id === id) {
        return PrimeFaces.widgets[propertyName];
      }
    }
}

Usage

getWidgetVarById('form:dialogId');

This will return the object, in the previous case a dialog widgetVar object is returned, to show it simply call show()  right away.

getWidgetVarById('form:dialogId').show();

– Conclusion

All the widgetVars are stored in the PrimeFaces.widgets. namespace.
Iterating over that namespace and comparing the given Id with the object’s is the way to find your widgetVar.

Note: this equals to the expression  #{p:widgetVar(‘form:dialogId’)}  (Server-side evaluation)

 

If you think something is wrong please feel free to comment :)
  1. One hell of a helpful function. Thanks for sharing.

    Reply
  2. This doesn’t work on PrimeFaces 3.5, because ‘PrimeFaces.widgets’ was not yet introduced.

    Reply
  3. Barna Adrian says:

    Any solution for Primefaces 3.5?

    Reply
  4. Your function is quite useful, but need to be improved.
    Sometimes PrimeFaces.widgets map contains empty (null) values for particular widget ID. In this case next JavaScript error throws: “Cannot read property ‘id’ of null”. Checked for PrimeFaces 5.2.
    To avoid this function should be modified like this:

    function getWidgetVarById(id) {
    var widgets = PrimeFaces.widgets;
    for (var propertyName in widgets) {
    var widget = widgets[propertyName];
    if (widget && widget.id === id) {
    return widget;
    }
    }
    return null;
    }

    Reply
  5. Esteban says:

    Hey there! great post on widgetvar!

    I have a question, if I have a tabView with tabs generated dynamically and each one of this tabs have a editor component, is it posible to assign a dynamic widgedvar as well?
    Could it be something like:

    <p:editor widgetvar="#{bean.language'_editor'}"

    ?

    Thanks in advance!

    Reply

Reply to Barna Adrian