jimmybondy
jimmybondy

Reputation: 2152

Disable/enable commandButton depending on required fields of current form?

What is the best approach to disable a commandButton if the fields with required=true are not filled with values?

The button should be disabled on first page load, and only be enabled in case all required fields are fields with values.

By best approach i mean no javascript and minimum-code :-)

In addition it would be excellent if the commandButton is only enabled when all validators evaluate to true.

Using PF 3.2

EDIT

Upvotes: 0

Views: 3937

Answers (2)

Arjun
Arjun

Reputation: 1952

This is not possible for two reasons.

  1. For client side validation, you would definitely require javascript.
  2. The required attribute of components is stored server side ONLY, the client has no idea of which fields are required by default.

Without using required, you could achieve this in client-side as following. validateContent should contain the logic to disable the commandButton.

<h:inputText value="#{bean.text}" >
    <pe:javascript event="keyup" execute="validateContent();"/>
</h:inputText>

If going to server is okay, then you could do this:

<h:inputText id="test1" value="#{bean.text}" required="true" immediate="true">
    <f:ajax listener="#{bean.makeDisable()}" render="test2" />
</h:inputText>
</h:commandButton id="test2" value="commandButton1" disabled="#{bean.disable}" />

And in the bean:

  private String text;
  private boolean disable;

  // setter & getter of text

  public boolean isDisable()
  {
    return disable;
  }

  public void makeDisable(AjaxBehaviorEvent event)
  {
    if(text == null || text.equals(""))
      this.disable=true;
    else
      this.disable=false;
  }

This basically will load the commandButton disabled on initial load and it will only be enabled on entering any value in text field.

Upvotes: 2

maple_shaft
maple_shaft

Reputation: 10463

It is possible but I would hardly call it the "best way".

You would need to supply an ajax tag for change events on each field. Each field would have to be immediate to skip initial validation and process will need to be set to @this.

In an event listener you can check if values exist for each of the required fields and if so then set a boolean field that determines if the commandButton is disabled or not.

These ajax tags will need to render @this as well as the commandButton.

But even then there is a LOT of Javascript actually going on, just none that you would have to write directly.

Upvotes: 1

Related Questions