Is there a way to set my component focus after an function call to an other component with Primefaces RequestContex?
i tried:
RequestContex.getCurrentIns
Looks like you're under a couple of misconceptions here:
That you can execute Java code in RequestContext
API.
RequestContext.getCurrentInstance().execute("(((InputText) event.getComponent()).getWidgetVar()).Focus();");
You can't. The code above will not work. execute
is built for JavaScript only.
The function name you're looking for is focus()
. JS is case-sensitive. So Focus <> focus
. So I think what you should have there is
RequestContext.getCurrentInstance().execute("yourClientSideId.focus();");
Where yourClientSideId
should correspond to the widgetVar
attribute of the component you're interested in. I'm not sure what the PF
object you're referencing in your code is supposed to be. I've never seen it. Perhaps you meant the PrimeFaces
object?
In the event of failure of the above, you could always use the scrollTo
method on RequestContext
:
RequestContext.getCurrentInstance().scrollTo("yourComponentWidgetVar");
If the previous answer does not work, you can create a js function, for example:
function focusField(id){
$(id).focus();
}
Then in your bean, assuming u want set focus on field "input4" , it represents ID not Widgetvar
RequestContext.getCurrentInstance().execute("focusField('#input4');");
Using PrimeFaces 6.1, for reasons unknown, I was unable to get the primefaces p:focus to work. So, I just implemented an onload JQuery function to set focus to a p:commandButton. For the onload call, put the jQuery nested function below in the 'body'. This is to be sure to override any other primefaces onload functions.
<script>
jQuery(document).ready(function () {
jQuery(document).ready(function () {
// twice in document.ready to
// execute after Primefaces callbacks
PF('widget_home_page_form_command_button').getJQ().focus();
});
});
</script>
PrimeFaces creates widgetVar components for all of the primefaces components. Some features are available though the widgetVar such as disable or enable. But, I had to use the getJQ() function to obtain the jQuery object and used that object to set focus on the command button.
You can use <p:focus>
tag from primefaces, I used it for setting focus at run time as follows :
.xhtml code:
<p:focus id="focusID" for="#{yourBean.focusProperty}" />
.java code:
focusProperty="componentIDToSetFocus";
don't forget to update the ID of <p:focus>
tag