Search code examples
jsfdisabled-input

enable / disable based on the null value for p:inputText


I want to create a JSF application. In the application the user will search for the user records from the database and set the values in the form, and then submit the form. I have a small issue where I need to enable / disable based on the null value for p:inputText

  • If a null value is set for the field from the database, then enable the input for the p:inputText
  • If a value is set for the field from the database, then disable or make it read only the p:inputText

This way the user will be able to enter values if no value is set into the field. How this can be implemented?

<p:inputText id="firstName"  value="#{javaMB.infoEntity.firstName}"/>
<p:inputText id="lastName"  value="#{javaMB.infoEntity.lastName}"/>
<p:inputText id="age"  value="#{javaMB.infoEntity.age}"/>

this.infoEntity.setFirstName(view.getFirstName());
this.infoEntity.setLastName(view.getLastName());
this.infoEntity.setAge(view.getAge());

        DB 

        Mark   XYZ   45
        Sav    NULL  23
        NULL   Jones 33

If we set the second row then p:inputText for first name is disabled, p:inputText for last name is enabled, p:inputText for age is disabled. If we set the third row then p:inputText for first name is enabled, p:inputText for last name is disabled, p:inputText for age is disabled


What I have tried

Using a readonly="true" did not work as I need to enter the p:inputText if a null value is set for it.

<p:inputText id="lastName"  value="#{javaMB.infoEntity.lastName}"  disabled="{!check}"/>                    
public Boolean check{set;} 

Let me know if any clarifications are required,


Solution

  • You can use power of Java EE EL (Expression Language).

    In your case, following declarations will generate disabled p:inputText if value of lastName is not null

    <p:inputText id="lastName" value="#{javaMB.infoEntity.lastName}"  
                 disabled=#{not empty javaMB.infoEntity.lastName}/>
    

    or

    <p:inputText id="lastName" value="#{javaMB.infoEntity.lastName}"  
                 disabled=#{javaMB.infoEntity.lastName != null}/>