Is it possible to dynamically generate the <f:validateBean> tag? - jsf

I am dynamically generating some Primefaces input and output components, and I need to be able to disable validation on these components in certain use cases, while still updating the model. (Like a save button). It looks like the proper way to do that in xhtml would be to use <f:validateBean disabled="#{myBean.someCondition}/>
However, I cannot figure out how to create this component dynamically. I searched through the javax.faces package and could not find any validateBean component. I thought maybe it would be a property that I need to set on the UIInput component, but none of the methods outlined in that API seem to what I need.
Is this possible?
Edit:
As a reference, here is the component I am creating:
UIInput input = new InputText();
input.setId(field.getFieldKey());
input.setValueExpression("value", expressionFactory.createValueExpression(elContext, field.getFieldValue(), String.class));
input.addClientBehavior("blur", ajaxBehavior);
input.addValidator(new BeanValidator());

You might want to explore these paths :
Set immediate to true on your input.
input.setImmediate(true);
Extend BeanValidator with an empty validate method and pass an instance to your input.
input.addValidator(new DummyBeanValidator());
Hope this helps.

Related

Required asterisk is not displayed in input fields Primefaces 6.0

I have created a form using Primefaces 6.0 and in the bean I have used constrained validators like #NotNull and #NotEmpty in the bean fields. However the asterisk near the label of the input text are not automatically rendered. The asterisk is only displayed when I set and an inputText as "required=true". My problem is that I would like to use the validation messages provided by the bean validation JSR so I would not like to put "required"to the input texts. I have also read that after primefaces 5.0 the validation constraints are automatically detected and the asterisk is rendered automatically. Has anyone faced a similar problem? Have I missed any configuration?
i think whatever you want is possible by some custom code, use CSS for asterisk (*) in read color, do not put required=true use custom validate. have look https://www.primefaces.org/showcase/ui/csv/custom.xhtml
if you did not put required=true your form will submmited to bean and you have to check and bean level for validation.
That is a nice to have feature that doesn't exist (yet).
If you want it implemented, log an enhancement feature.
Or extend bean validation component ;-)

Can JSF be configured to not invoke Entity setter unless the field actually changed?

When a JSF form field is wired into an entity bean field (which is mapped to a DB field), each setter in the entity bean is called regardless of whether the user changed the form field value in the front end, i.e. the setters on unchanged fields are invoked the same as those that have changed but their new value is the same as the old value.
My question is simple: Is there a way to configure JSF to only call the setters mapped to the fields that have changed in the front end? The reason for this is that I have a requirement by which I have to detect deltas on every persist and log them, more about which can be read in this question.
Maybe I didn't understand you clearly, but why are you mapping directly your entity beans to a JSF view ?! IMHO it would be better if you add managed beans between your JSF pages and the entities in order to better separate your business logic from data access.
Any way, I think the easiest solution to impelement for that case is by making use of Value Change Events which are invoked "normally" after the Process Validations phase (unless you make use of the immediate attribute).
The good news about Value Change Events (regarding your example) is they are invoked ONLY after you force form submit using JavaScript or Command components AND the new value is different from the old value.
So, as an example on how to use value change listeners, you can add valueChangeListner attribute to each of your JSF tags like following:
<h:inputText id="input" value="#{someBean.someValue}"
valueChangeListener="#{someBean.valueChanged} />
Then, implement your valueChanged() method to look something like:
public void valueChanged(ValueChangeEvent event) {
// You can use event.getOldValue() and event.getNewValue() to get the old or the new value
}
Using the above implementation, may help you to separate your logging code (it will be included in the listeners) from your managed properties setters.
NB: Value Change Listeners may also be implemetend otherwise using the f:valueChangeListener Tag, but this is not the best choice for your example (you can find some examples in the section below, just in case)
See also:
Valuechangelistener Doubt in JSF
JSF 2 valueChangeListener example
When to use valueChangeListener or f:ajax listener?

How to programmatically generate JSF components at run time?

I've got to create screens to display a lot of JPA entities in the View. It would be great to create one facelet and pass to it a collection of fields e.g. List<Object>.
The facelet/custom component would need to convert each element of the list into the appropriate tag for display e.g. an enum field to h:selectOneMenu, String field to h:inputText, etc. This would need to be done at run time.
What's the easiest way to do this?
Worked on a project previously that created entire pages dynamically from stored configuration. There are two basic things you need
A BackingBean. You'll used this to get access to the UIComponent on the facelet which will act as the parent to the generated UIComponents. Something like a panelGroup. But, you'll need to bind the UIComponent to the backing bean, in order to have a parent against which you'll add the dynamically-created UIComponents
Access to the Application component. Typically FacesContext.getApplication() (I worked on this in JavaEE 5, so it might look a little different with injection). Once you have the Application component, you call the createComponent method, passing in the type of component you want to create.
It then becomes an activity of creating components dynamically, configuring them in code and adding them to the parent UIComponent defined via a binding bean. It can be tricky, but it can be done.

XPages Rich Text Component

Is there any chance to get the html content (mime) from a rich text component without any datasource. I would like to grab the content from the field like this. getComponent("FieldName").value but this dosen't work.
thanks.
You can bind the control to a scoped variable; for example, #{viewScope.comments}. You can then retrieve the submitted value from the scope instead of from the component itself; for example, viewScope.get("comments").
Alternatively, you can set a dataContext variable to a JS expression, e.g. <dataContext var="richText" value="#{javascript:return {value:""};}" />. Then you can bind the control to #{richText.value} and retrieve it via the same expression.
And, of course, you could define a managed bean and bind the control to one of its properties. This option provides the most flexibility, but isn't quite as simple as the other two options above.
The solution for my problem is
getComponent("FieldName").getValue()
thanks for your help.

best approach to do jsf form validation

If I have many input controls in a form (There are separate validators for each of these input controls - like required,length and so on ) , there is a command button which submits the form and calls an action method. The requirement is - though the input control values are , say , individually okay - the combination of these values should be okay to process them together after the form submission - Where do i place the code to validate them together?
1) Can i add a custom validator for the command button and validate the combination together? like validate(FacesContext arg0, UIComponent arg1, Object value) but even then I will not have values of the other input controls except for the command button's/component's value right ?
2) can i do the validation of the combination in the action method and add validation messages using FacesMessage ?
or do you suggest any other approach?
Thanks for your time.
Point 2 is already answered by Bozho. Just use FacesContext#addMessage(). A null client ID will let it land in <h:messages globalOnly="true">. A fixed client ID like formId:inputId will let it land in <h:message for="inputId">.
Point 1 is doable, you can grab the other components inside the validator method using UIViewRoot#findComponent():
UIInput otherInput = (UIInput) context.getViewRoot().findComponent("formId:otherInputId");
String value = (String) otherInput.getValue();
You however need to place f:validator in the last UIInput component. Placing it in an UICommand component (like the button) won't work.
True, hardcoding the client ID's is nasty, but that's the payoff of a bit inflexible validation mechanism in JSF.
I've just landed on your post after having the same question.
Articles I have read so far identify that there are four types of validation for the following purposes:
Built into the Components (subscribe to individual fields; required=true, LengthValidator, etc)
'Application Validation' added to the Action in the Backing Bean (Business Logic)
Custom Validators (subscribe to individual fields)
Method in the Backing Bean used as a Custom Validator (subscribe to individual fields).
With reference to Validators: The validation mechanism in JSF was designed to validate a single component. (See S/O Question here)
In the case where you want to validate a whole form as a logical grouping of fields, it appears with standard JSF/Apache MyFaces that the most appropriate to do it is as Application Validation, as the set of individual fields take on a collective business meaning at this point.
BalusC has come up with a way of shoehorning form validation into a single validator attached to the last form item (again, see S/O Question here and another worked example on his website here) however it isn't necessarily extensible/reusable, as the references to the ID's of the form have to be hardcoded as you can't append to the validate() method's signature. You'll get away with it if you're only using the form once, but if it pops up a few times or if you generate your ID's programmatically, you're stuck.
The JSF implementation portion of Seam has a <s:validateForm /> control which can take the IDs of fields elsewhere in your form as parameters. Unfortunately, it doesn't appear that any of the MyFaces/Mojara/Sun JSF implementations have an equivalent as it isn't part of the standard.
I've successfully used the 2nd approach:
FacesMessage facesMessage =
new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, msg);
FacesContext.getCurrentInstance().addMessage(null, facesMessage);

Resources