Send parameter to request on every action for composite component - jsf

I have a composite component, which has an id I would like to send as a parameter when executing one of many posiible actions inside the composite component. I know I can use something like;
<h:form id="testForm">
<p:commandButton value="#{testReqBean.label}"
actionListener="#{testReqBean.perform()}"
process="#this or #form" update="#form" ajax="true" >
<f:param value="#{cc.attrs.id}" name="CC-Id" />
</p:commandButton>
</h:form>
now, imagine I have many forms or buttons with specific actions inside the composite component... is there a way to define the parameter I want to send in the request just once ? I mean not adding an f:param inside each form/button (depending on the process #form or #this) but one for the whole composite component?
Thanks in advance!

Maybe one solution would be to use viewparam but this only works if you can add a request parameter.
<f:metadata>
<f:viewParam value="#{your_bean.your_property_name}" name="request_param"/>
</f:metadata>
The only problem here is that whoever implements your composite component would have to set the above when needed, but it still an abstraction to this problem of having to set the same property for all components in same page.

I gather that the <h:form> is enclosed in the composite component itself.
Just use a plain HTML hidden input field.
<h:form>
<input type="hidden" name="CC-Id" value="#{cc.attrs.id}" />
...
<p:commandButton />
<p:commandButton />
<p:commandButton />
...
</h:form>
Unrelated to the concrete problem, having an entire form in a composite is kind of strange. This is then food for read: When to use <ui:include>, tag files, composite components and/or custom components?

Related

Required = "true" function is causing problems [duplicate]

What exactly are process and update in PrimeFaces p:commandXxx components and execute and render in f:ajax tag?
Which works at the time of validation? What does update attribute do rather than updating value to component from back end? Do process attribute bind value to model? What exactly do #this, #parent, #all and #form in both attributes?
The example below is working fine, but I am a little confused in basic concepts.
<p:commandButton process="#parent"
update="#form"
action="#{bean.submit}"
value="Submit" />
<p:commandXxx process> <p:ajax process> <f:ajax execute>
The process attribute is server side and can only affect UIComponents implementing EditableValueHolder (input fields) or ActionSource (command fields). The process attribute tells JSF, using a space-separated list of client IDs, which components exactly must be processed through the entire JSF lifecycle upon (partial) form submit.
JSF will then apply the request values (finding HTTP request parameter based on component's own client ID and then either setting it as submitted value in case of EditableValueHolder components or queueing a new ActionEvent in case of ActionSource components), perform conversion, validation and updating the model values (EditableValueHolder components only) and finally invoke the queued ActionEvent (ActionSource components only). JSF will skip processing of all other components which are not covered by process attribute. Also, components whose rendered attribute evaluates to false during apply request values phase will also be skipped as part of safeguard against tampered requests.
Note that it's in case of ActionSource components (such as <p:commandButton>) very important that you also include the component itself in the process attribute, particularly if you intend to invoke the action associated with the component. So the below example which intends to process only certain input component(s) when a certain command component is invoked ain't gonna work:
<p:inputText id="foo" value="#{bean.foo}" />
<p:commandButton process="foo" action="#{bean.action}" />
It would only process the #{bean.foo} and not the #{bean.action}. You'd need to include the command component itself as well:
<p:inputText id="foo" value="#{bean.foo}" />
<p:commandButton process="#this foo" action="#{bean.action}" />
Or, as you apparently found out, using #parent if they happen to be the only components having a common parent:
<p:panel><!-- Type doesn't matter, as long as it's a common parent. -->
<p:inputText id="foo" value="#{bean.foo}" />
<p:commandButton process="#parent" action="#{bean.action}" />
</p:panel>
Or, if they both happen to be the only components of the parent UIForm component, then you can also use #form:
<h:form>
<p:inputText id="foo" value="#{bean.foo}" />
<p:commandButton process="#form" action="#{bean.action}" />
</h:form>
This is sometimes undesirable if the form contains more input components which you'd like to skip in processing, more than often in cases when you'd like to update another input component(s) or some UI section based on the current input component in an ajax listener method. You namely don't want that validation errors on other input components are preventing the ajax listener method from being executed.
Then there's the #all. This has no special effect in process attribute, but only in update attribute. A process="#all" behaves exactly the same as process="#form". HTML doesn't support submitting multiple forms at once anyway.
There's by the way also a #none which may be useful in case you absolutely don't need to process anything, but only want to update some specific parts via update, particularly those sections whose content doesn't depend on submitted values or action listeners.
Noted should be that the process attribute has no influence on the HTTP request payload (the amount of request parameters). Meaning, the default HTML behavior of sending "everything" contained within the HTML representation of the <h:form> will be not be affected. In case you have a large form, and want to reduce the HTTP request payload to only these absolutely necessary in processing, i.e. only these covered by process attribute, then you can set the partialSubmit attribute in PrimeFaces Ajax components as in <p:commandXxx ... partialSubmit="true"> or <p:ajax ... partialSubmit="true">. You can also configure this 'globally' by editing web.xml and add
<context-param>
<param-name>primefaces.SUBMIT</param-name>
<param-value>partial</param-value>
</context-param>
Alternatively, you can also use <o:form> of OmniFaces 3.0+ which defaults to this behavior.
The standard JSF equivalent to the PrimeFaces specific process is execute from <f:ajax execute>. It behaves exactly the same except that it doesn't support a comma-separated string while the PrimeFaces one does (although I personally recommend to just stick to space-separated convention), nor the #parent keyword. Also, it may be useful to know that <p:commandXxx process> defaults to #form while <p:ajax process> and <f:ajax execute> defaults to #this. Finally, it's also useful to know that process supports the so-called "PrimeFaces Selectors", see also How do PrimeFaces Selectors as in update="#(.myClass)" work?
<p:commandXxx update> <p:ajax update> <f:ajax render>
The update attribute is client side and can affect the HTML representation of all UIComponents. The update attribute tells JavaScript (the one responsible for handling the ajax request/response), using a space-separated list of client IDs, which parts in the HTML DOM tree need to be updated as response to the form submit.
JSF will then prepare the right ajax response for that, containing only the requested parts to update. JSF will skip all other components which are not covered by update attribute in the ajax response, hereby keeping the response payload small. Also, components whose rendered attribute evaluates to false during render response phase will be skipped. Note that even though it would return true, JavaScript cannot update it in the HTML DOM tree if it was initially false. You'd need to wrap it or update its parent instead. See also Ajax update/render does not work on a component which has rendered attribute.
Usually, you'd like to update only the components which really need to be "refreshed" in the client side upon (partial) form submit. The example below updates the entire parent form via #form:
<h:form>
<p:inputText id="foo" value="#{bean.foo}" required="true" />
<p:message id="foo_m" for="foo" />
<p:inputText id="bar" value="#{bean.bar}" required="true" />
<p:message id="bar_m" for="bar" />
<p:commandButton action="#{bean.action}" update="#form" />
</h:form>
(note that process attribute is omitted as that defaults to #form already)
Whilst that may work fine, the update of input and command components is in this particular example unnecessary. Unless you change the model values foo and bar inside action method (which would in turn be unintuitive in UX perspective), there's no point of updating them. The message components are the only which really need to be updated:
<h:form>
<p:inputText id="foo" value="#{bean.foo}" required="true" />
<p:message id="foo_m" for="foo" />
<p:inputText id="bar" value="#{bean.bar}" required="true" />
<p:message id="bar_m" for="bar" />
<p:commandButton action="#{bean.action}" update="foo_m bar_m" />
</h:form>
However, that gets tedious when you have many of them. That's one of the reasons why PrimeFaces Selectors exist. Those message components have in the generated HTML output a common style class of ui-message, so the following should also do:
<h:form>
<p:inputText id="foo" value="#{bean.foo}" required="true" />
<p:message id="foo_m" for="foo" />
<p:inputText id="bar" value="#{bean.bar}" required="true" />
<p:message id="bar_m" for="bar" />
<p:commandButton action="#{bean.action}" update="#(.ui-message)" />
</h:form>
(note that you should keep the IDs on message components, otherwise #(...) won't work! Again, see How do PrimeFaces Selectors as in update="#(.myClass)" work? for detail)
The #parent updates only the parent component, which thus covers the current component and all siblings and their children. This is more useful if you have separated the form in sane groups with each its own responsibility. The #this updates, obviously, only the current component. Normally, this is only necessary when you need to change one of the component's own HTML attributes in the action method. E.g.
<p:commandButton action="#{bean.action}" update="#this"
oncomplete="doSomething('#{bean.value}')" />
Imagine that the oncomplete needs to work with the value which is changed in action, then this construct wouldn't have worked if the component isn't updated, for the simple reason that oncomplete is part of generated HTML output (and thus all EL expressions in there are evaluated during render response).
The #all updates the entire document, which should be used with care. Normally, you'd like to use a true GET request for this instead by either a plain link (<a> or <h:link>) or a redirect-after-POST by ?faces-redirect=true or ExternalContext#redirect(). In effects, process="#form" update="#all" has exactly the same effect as a non-ajax (non-partial) submit. In my entire JSF career, the only sensible use case I encountered for #all is to display an error page in its entirety in case an exception occurs during an ajax request. See also What is the correct way to deal with JSF 2.0 exceptions for AJAXified components?
The standard JSF equivalent to the PrimeFaces specific update is render from <f:ajax render>. It behaves exactly the same except that it doesn't support a comma-separated string while the PrimeFaces one does (although I personally recommend to just stick to space-separated convention), nor the #parent keyword. Both update and render defaults to #none (which is, "nothing").
See also:
How to find out client ID of component for ajax update/render? Cannot find component with expression "foo" referenced from "bar"
Execution order of events when pressing PrimeFaces p:commandButton
How to decrease request payload of p:ajax during e.g. p:dataTable pagination
How to show details of current row from p:dataTable in a p:dialog and update after save
How to use <h:form> in JSF page? Single form? Multiple forms? Nested forms?
If you have a hard time remembering the default values (I know I have...) here's a short extract from BalusC's answer:
Component
Submit
Refresh
f:ajax
execute="#this"
render="#none"
p:ajax
process="#this"
update="#none"
p:commandXXX
process="#form"
update="#none"
By process (in the JSF specification it's called execute) you tell JSF to limit the processing to component that are specified every thing else is just ignored.
update indicates which element will be updated when the server respond back to you request.
#all : Every component is processed/rendered.
#this: The requesting component with the execute attribute is processed/rendered.
#form : The form that contains the requesting component is processed/rendered.
#parent: The parent that contains the requesting component is processed/rendered.
With Primefaces you can even use JQuery selectors, check out this blog: http://blog.primefaces.org/?p=1867
JSF 2.0+ keywords
#this Current component.
#all Whole view.
#form Closest ancestor form of current component.
#none No component.
JSF 2.3+ keywords
#child(n) nth child.
#composite Closest composite component ancestor.
#id(id) Used to search components by their id ignoring the component tree structure and naming containers.
#namingcontainer Closest ancestor naming container of current component.
#parent Parent of the current component.
#previous Previous sibling.
#next Next sibling.
#root UIViewRoot instance of the view, can be used to start searching from the root instead the current component.
PrimeFaces specific keywords
#row(n) nth row.
#widgetVar(name) Component with given widgetVar.
And you can even use something called "PrimeFaces Selectors" which allows you to use jQuery Selector API. For example to process all inputs in a element with the CSS class myClass:
process="#(.myClass :input)"
See:
https://primefaces.github.io/primefaces/12_0_0/#/core/searchexpression
PrimeFaces 10+ Observer / Event
This allows you to update components based on a custom event name, set by the #obs(event) keyword. For example:
<p:commandButton update="#obs(myEvent)"/>
<h:panelGroup>
<p:autoUpdate on="myEvent"/>
</h:panelGroup>
See:
https://www.primefaces.org/showcase/ui/ajax/observer.xhtml
These are PrimeFaces features to provide partial view processing and partial rendering. You can control what to execute in lifecycle and what to render with ajax.
When using backing bean properties in expression language
process attribute calls SETTER methods
update attribute calls GETTER methods
primefaces forum

Use either action or actionListener based on a condition in a PF datatable composite component

I am trying to create a datatable composite component, this component needs to be used by two groups of developers, one who are using Spring web flow and they need an action attribute for the command link inside the composite component datatable and the others need the actionListener attribute.
I would like to use the same xhtml for both cases. Is that feasible?
<composite:attribute name="isWebFlow" />
Would an attribute like above help me configure? The problem is that I have many command links in the datatable composite component and hence I cannot repeat them / render them based on the condition like :
<c:if test="#{cc.attrs.isWebFlow eq 'true'}">
<p:commandLink styleClass="filter #{cc.attrs.styleClass}" action="#{cc.attrs.action}"/>
</c:if>
<c:if test="#{cc.attrs.isWebFlow eq 'false'}">
<p:commandLink styleClass="filter #{cc.attrs.styleClass}" actionListener="#{cc.attrs.actionListener}"/>
</c:if>
Is there any other way to do this and re use the xhtml? Thanks in advance.
Try using rendered attribute:
<p:commandLink styleClass="filter #{cc.attrs.styleClass}" action="#{cc.attrs.action}" rendered="#{isWebFlow}"/> <p:commandLink styleClass="filter #{cc.attrs.styleClass}" action="#{cc.attrs.action}" rendered="#{!isWebFlow}"/>

Javascript error in XHTML page in JSF 2

I have the following code in an xhtml page in JSF 2. But when the page loads I get an javascript error that
document.getElementById("country") is null or not an object.
Why is this happening?
<h:form>
<h:panelGrid columns="2">
Selected country locale :
<h:inputText id="country" value="#{country.localeCode}" size="20" />
Select a country {method binding}:
<h:selectOneMenu value="#{country.localeCode}" onchange="submit()"
valueChangeListener="#{country.countryLocaleCodeChanged}">
<f:selectItems value="#{country.countryInMap}" />
</h:selectOneMenu>
<script>
alert("hi");
document.getElementById("country").disabled=true;
</script>
</h:panelGrid>
</h:form>
It's not finding your component. Since your <h:inputText> is inside of an <h:form> the id will have the following pattern
formName:componentName. Since you did not specify an id for <h:form>, JSF will generate one for you. That's why you are seeing j_id1926454887_72d35e53:country where j_id1926454887_72d35e53 is the form id. If you want to deal with simpler id, then you should add an id value to your <h:form>. For example
<h:form id="form">
<h:inputText id="country" value="#{country.localeCode}" size="20" />
</h:form>
The id for <h:inputText> will now be form:country.
Even simpler, you could simply add prependId = "false" to your form
<h:form prependId="false">
and now your id for <h:inputText> will simply be country.
How can I get this id dynamically?
I'm going to modify your code slightly to achieve what you want (I'm thinking that you want to disable the input based on a specific event). Consider this simpler example
<h:form>
<h:inputText id="country" value="#{country.localeCode}" size="20" onclick="disableInputText(this.form)" />
</h:form>
Here I'm attaching a javascript function to an HTML DOM Event handler. In this case, I want the input to be disabled when I click on it (hence onclick). I'm also passing the form as a reference in the function. Then, define your Javascript like this.
<script>
function disableInputText(form) {
form[form.id + ":country"].disabled = true;
}
</script>
We simply grab the input in the javascript with the corresponding id via the object form and set its disabled attribute to true. (You can sort of view the form object as Map).
Also check the link below for more attributes of <h:inputText> and the different handlers you can use (the ones with on as prefix).
inputText Tag Attribute.
Also, check out the answer with the most votes to get a bigger picture on how ids are generated and other ways on how they can be determined.
How can I know the id of a JSF component so I can use in Javascript
It's seems to be a naming issue. the id of the field is not rendered as country.
i found a question that seems relevant. Composite components & ID

Losing inputs submitted in composite component

I have a problem with submitting composite components.
Most of my composite components contain both the input components and the "submit" button.
When I tried to put the button still in the same h:form but not in the same composite component, the submitted value seemed to be "lost" somewhere. And, for instance, my validators got called on original values.
Example :
<composite:interface>
<composite:attribute name="titreContext" required="true"/>
</composite:interface>
<composite:implementation>
<p:outputPanel id="selectionTitreDetailsPanel" styleClass="selectionTitreDetails">
<p:outputPanel id="selectionTitreDetailsPanelInner" rendered="#{not empty cc.attrs.titreContext.selected}">
<p:panelGrid columns="2" id="panelId">
<h:outputText id="idLabel" value="Id :"/>
<h:outputText id="id" value="#{cc.attrs.titreContext.selected.titeluid}"/>
<p:tooltip for="id" value="Identifiant unique"/>
</p:panelGrid>
<p:panelGrid columns="2" id="titelePanel">
<p:outputLabel for="selectTitele" value="Titre :"/>
<p:selectOneMenu id="selectTitele" value="#{cc.attrs.titreContext.selected.titele}" effect="fold" styleClass="fullWidth">
<f:selectItems value="#{constants.getTitelesForTypman(cc.attrs.titreContext.selected.titele.typman)}" var="titele" itemLabel="#{titele.titelelil}" itemValue="#{titele}" styleClass="fullWidth"/>
<p:column styleClass="fullWidth">#{titele.titelelil}</p:column>
</p:selectOneMenu>
</p:panelGrid>
[...]
<p:commandButton id="confirmerModifications" icon="small_edit" type="submit" value="Confirmer les modifications"
action="#{elutersEditionContext.confirmeModifsSelection}" process="mandatsTerritorial"
update="mandatsTerritorial #{cc.attrs.notifUpdates}"/>
</composite:implementation>
works.
But putting the p:commandButton out of the composite :
<h:form>
<mylib:mycomponent /*parameters *//>
<p:commandButton /*parameters*/ />
</h:form>
does not work. When I debug my validators, I can see that the modified values where not even submitted. Neither getLocalValue, getSubmittedValue nor getValue is changed.
Is there a syntax in composite component declaration to use to correct this situation ?
By the way : when I was writing my components as composite components rather than custom components, retrieving #{asen} in the backing bean just worked.
Thanks in advance.
I am using :
PrimeFaces 3.4.1
CODI 1.0.5
OpenWebBeans 1.1.6
MyFaces 2.1.9
Tomcat 7.0.32
(update) This very strange problem was caused by h:form nesting.
Very strange because h:form nesting did not perturbate the processing of the first level of composite components, but caused this strange "input lost" in nested composite.
Nesting looked like this :
<h:form>
...
<p:tabView ...>
<p:tab>
<h:form>
<my:composite ....>
</h:form>
</p:tabView>
</h:form>
You're using a relative client ID in the process attribute of the <p:commandButton>:
<p:commandButton ... process="mandatsTerritorial" />
A relative client ID is relative to the parent NamingContainer component. It will be searched as direct child of the NamingContainer component. If the child is by itself a NamingContainer, then its children would not be searched.
Composite components are by itself in fact also NamingContainer components. If the button is placed in the composite, then this will be searched as direct child of the <cc:implementation>. In your particular case, only the component with id="mandatsTerritorial" will be processed on form submit, including all of its children (note that this component is nowhere visible in the code posted so far, but I'd imagine that you omitted it for brevity).
If the button is placed in <h:form>, then this will be searched as direct child of the <h:form>. However as this is apparently been placed inside the composite (which is, as said, another NamingContainer component), it wouldn't be found and hence basically nothing would be processed. You'd need to fix the process to point to the right client ID. E.g.
<h:form>
<mylib:mycomponent id="mycomponent" />
<p:commandButton ... process="#this mycomponent:mandatsTerritorial" />
</h:form>
This way it will process itself (mandatory to invoke the action!) and the component with id="mandatsTerritorial" inside the <cc:implementation> of the composite with id="mycomponent".
As a completely different alternative, which would work just fine in this particular construct, is to remove the process attribute altogether. It defaults to #form already which will thus process the entire form.
Update as per your question update: nesting forms is invalid in HTML. Using the JSF <h:form> representation doesn't change that; you'd still end up with nested forms in HTML. The browser behaviour is unspecified as to which data would be submitted to the server. Make sure that you don't nest <h:form> in JSF as well.

How to do client side updates in JSF 2.0

I'd like to do client side component updates. Example: disable a button when a checkbox is clicked:
<h:selectBooleanCheckbox value="true" onchange="button.disabled=true" />
<h:commandButton id="button" value="Save" />
The above doesn't work. Is there a way to do this declaratively in JSF?
It doesn't work because the JSF component ID is not necessarily the same as the generated HTML ID. JSF composes the HTML element ID and form element name based on the ID's of all UINamingContainer components in the tree -if any. The UIForm component is one of them. Rightclick the page in webbrowser and choose View Source. See and learn.
There are two ways to solve this problem:
Set prependId attribtue of <h:form> to false.
<h:form prependId="false">
<h:selectBooleanCheckbox value="true" onclick="button.disabled=true" />
<h:commandButton id="button" value="Save" />
</h:form>
Note that I'd rather use onclick="button.disabled=!checked" instead. The onchange is only fired when the input element loses focus and that is non-intuitive in case of checkboxes and radiobuttons. Also, you'd like to turn it back on when the checkbox is checked again, right?
Give the <h:form> a fixed ID so that you know how the generated form element name look like:
<h:form id="form">
<h:selectBooleanCheckbox value="true" onclick="form['form:button'].disabled=true" />
<h:commandButton id="button" value="Save" />
</h:form>
The brace notation is mandatory because the : is an illegal identifier character and just onclick="form:button.disabled=true" won't work. Also here, I'd rather use onclick="form['form:button'].disabled=!checked instead.
The same problem applies on document.getElementById() as well. So simply replacing button by document.getElementById('button') alone won't fix the problem.
simply use javascript
document.getElementById("buttonId").disabled="true";
Check this

Resources