My JSF Books/Videos My JSF Tutorials OmniFaces/JSF PPTs
JSF 2.3 Tutorial
JSF Caching Tutorial
JSF Navigation Tutorial
JSF Scopes Tutorial
JSF Page Author Beginner's Guide
OmniFaces 2.3 Tutorial Examples
OmniFaces 2.2 Tutorial Examples
JSF Events Tutorial
OmniFaces Callbacks Usages
JSF State Tutorial
JSF and Design Patterns
JSF 2.3 New Features (2.3-m04)
Introduction to OmniFaces
25+ Reasons to use OmniFaces in JSF
OmniFaces Validators
OmniFaces Converters
JSF Design Patterns
Mastering OmniFaces
Reusable and less-verbose JSF code

My JSF Resources ...

Java EE Guardian
Member of JCG Program
Member MVB DZone
Blog curated on ZEEF
OmniFaces is an utility library for JSF, including PrimeFaces, RichFaces, ICEfaces ...

.

.

.

.

.

.

.

.


[OmniFaces Utilities] - Find the right JSF OmniFaces 2 utilities methods/functions

Search on blog

Petition by Java EE Guardians

Twitter

duminică, 26 iulie 2015

[JSF Page Author Beginner's Guide] JSF <selectBooleanCheckbox> / HTML5 <input> [checkbox]

The <h:selectBooleanCheckbox> renders an  HTML "input" element of "type" "checkbox"

Common/basic usage in JSF (I) - without label defined via <h:outputLabel>:

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://xmlns.jcp.org/jsf/html">
 <h:head>
  <title>JSF selectBooleanCheckbox examples</title>        
 </h:head>
 <h:body>
  <h:form>          
   Remember me:
   <h:selectBooleanCheckbox value="#{playerBean.rememberme}"/>
   <h:commandButton value="Submit" action="data"/>
  </h:form>
 </h:body>
</html>

The <h:selectBooleanCheckbox> will be rendered in HTML as:
<input type="checkbox" name="j_idt6:j_idt8" checked="checked" />

Common/basic usage in JSF (II) - with label defined via <h:outputLabel>:

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://xmlns.jcp.org/jsf/html">
 <h:head>
  <title>JSF selectBooleanCheckbox examples</title>        
 </h:head>
 <h:body>
  <h:form>                      
   <h:selectBooleanCheckbox id="checkboxId" value="#{playerBean.rememberme}"/>
   <h:outputLabel for="checkboxId">Remember me</h:outputLabel>
   <h:commandButton value="Submit" action="data"/>
  </h:form>
 </h:body>
</html>

The <h:selectBooleanCheckbox> will be rendered in HTML as:
<input id="j_idt11:checkboxId" type="checkbox" name="j_idt11:checkboxId" checked="checked" />

The PlayerBean will be:

package beans;

import java.io.Serializable;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;

@Named
@SessionScoped
public class PlayerBean implements Serializable {

 private boolean rememberme = true;

 public boolean isRememberme() {
  return rememberme;
 }

 public void setRememberme(boolean rememberme) {
  this.rememberme = rememberme;
 }
}

At initial request, the checkbox is selected (ticked) because the its value is initialized from bean with true. If rememberme will be initially set to false, then at initial request the checkbox will be unselected (unticked).

The data.xhtml page is:

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"    
      xmlns:h="http://xmlns.jcp.org/jsf/html">
 <h:head>
  <title></title>        
 </h:head>
 <h:body>
  <!-- View submitted data -->           
   Remember: #{playerBean.rememberme}     
 </h:body>
</html>

Data flow in image:
More examples:

Add xmlns:pt="http://xmlns.jcp.org/jsf/passthrough" for pass-through attributes

Styling messages with CSS class

<h:form>
 Remember me:
 <div class="slide">                                 
  <h:selectBooleanCheckbox id="slide" value="#{playerBean.rememberme}"/>
  <h:outputLabel for="slide"></h:outputLabel>
 </div>
 <h:commandButton value="Submit" action="data"/>
</h:form>
<h:form>
 Remember me:
 <div class="rounded">                
  <h:selectBooleanCheckbox id="rounded" value="#{playerBean.rememberme}"/>
  <h:outputLabel for="rounded"></h:outputLabel>
 </div>
 <h:commandButton value="Submit" action="data"/>
</h:form>
The used CSS are available in the complete source code.

Use valueChangeListener with <h:selectBooleanCheckbox>

<h:form>
 Remember me:
 <h:selectBooleanCheckbox value="#{playerBean.rememberme}" onchange="this.form.submit();"
                          valueChangeListener="#{playerBean.rememberAction}"/>                      
</h:form>
#{playerBean.rememberme}

In PlayerBean we need to add the rememberAction() method, as below (the ValueChangeEvent is optional, you can use a void method without arguments also):

private static final Logger LOG = Logger.getLogger(PlayerBean.class.getName());
public void rememberAction(ValueChangeEvent event) {
 LOG.log(Level.INFO, "rememberAction() called, {0}", event.getOldValue() + " - " + event.getNewValue());
}

AJAXify <h:selectBooleanCheckbox>

<h:form>
 Remember me:
 <h:selectBooleanCheckbox value="#{playerBean.rememberme}">                      
  <f:ajax execute="@this" render="@form"/>
 </h:selectBooleanCheckbox>   
 #{playerBean.rememberme}
</h:form>       

AJAXify <h:selectBooleanCheckbox> with valueChangeListener

<h:form>
 Remember me:
 <h:selectBooleanCheckbox value="#{playerBean.rememberme}" valueChangeListener="#{playerBean.rememberAction}">                      
  <f:ajax execute="@this" render="@form"/>
 </h:selectBooleanCheckbox>   
 #{playerBean.rememberme}
</h:form>  

In PlayerBean we need to add the rememberAction() method, as below (the ValueChangeEvent is optional, you can use a void method without arguments also):

private static final Logger LOG = Logger.getLogger(PlayerBean.class.getName());
public void rememberAction(ValueChangeEvent event) {
 LOG.log(Level.INFO, "rememberAction() called, {0}", event.getOldValue() + " - " + event.getNewValue());
}

Indeterminate checkbox, see https://css-tricks.com/indeterminate-checkboxes/ 

<h:form id="indeterminateForm">          
 <ul>
  <li>
   <h:selectBooleanCheckbox id="basic"/>
   <h:outputLabel for="basic">Install</h:outputLabel>
   <ul>
    <li>
     <h:selectBooleanCheckbox id="basic-1"/>
     <h:outputLabel for="basic-1">Demos</h:outputLabel>
    </li>
    <li>
     <h:selectBooleanCheckbox id="basic-2"/>
     <h:outputLabel for="basic-2">Development</h:outputLabel>
     <ul>
      <li>
       <h:selectBooleanCheckbox id="basic-2-1"/>
       <h:outputLabel for="basic-2-1">Simple</h:outputLabel>
      </li>
      <li>
       <h:selectBooleanCheckbox id="basic-2-2"/>
       <h:outputLabel for="basic-2-2">Advance</h:outputLabel>
      </li>
     </ul>
    </li>
    <li>
     <h:selectBooleanCheckbox id="basic-3"/>
     <h:outputLabel for="basic-3">Debug</h:outputLabel>
    </li>
   </ul>
  </li>
  <li>
   <h:selectBooleanCheckbox id="repair"/>
   <h:outputLabel for="repair">Repair</h:outputLabel>
   <ul>
    <li>
     <h:selectBooleanCheckbox id="repair-1"/>
     <h:outputLabel for="repair-1">Demos</h:outputLabel>
    </li>
    <li>
     <h:selectBooleanCheckbox id="repair-2"/>
     <h:outputLabel for="repair-2">Tools</h:outputLabel>
    </li>
    <li>
     <h:selectBooleanCheckbox id="repair-3"/>
     <h:outputLabel for="repair-3">Kit</h:outputLabel>
    </li>
   </ul>
  </li>
 </ul>
 <h:commandButton value="Submit" action="data"/>
</h:form>  
Notice that indeterminate is not a checkbox attribute, is a JavaScript property. With other words, we can't make a checkbox indeterminate through HTML by design. The below snippet of JS (based on jQuery) can control this property in our case (the original source code is available at https://css-tricks.com/indeterminate-checkboxes/):

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">
 // see https://css-tricks.com/indeterminate-checkboxes/
 $(function () {               
   $('input[type="checkbox"]').change(function (e) {
     var checked = $(this).prop("checked"),
         container = $(this).parent(),
         siblings = container.siblings();

     container.find('input[type="checkbox"]').prop({
         indeterminate: false,
         checked: checked
     });

     function checkSiblings(el) {
         var parent = el.parent().parent(),
         all = true;

         el.siblings().each(function () {
             return all = ($(this).children('input[type="checkbox"]').prop("checked") === checked);
         });
         //<![CDATA[
         if (all && checked) {
         //]]>
                 parent.children('input[type="checkbox"]').prop({
                     indeterminate: false,
                     checked: checked
                 });
                 checkSiblings(parent);
         //<![CDATA[
         } else if (all && !checked) {
         //]]>
                 parent.children('input[type="checkbox"]').prop("checked", checked);
                 parent.children('input[type="checkbox"]').prop("indeterminate",
                        (parent.find('input[type="checkbox"]:checked').length > 0));
                 checkSiblings(parent);
         } else {
                 el.parents("li").children('input[type="checkbox"]').prop({
                     indeterminate: true,
                     checked: false
                 });
         }
     }

     checkSiblings(container);
   });
 });
</script>

Require the user to tick the desired checkbox (use OmniFaces)

<h:form>                       
 <h:panelGrid columns="3">
  <h:outputLabel for="termsId" value="Tick terms and conditions:" />
  <h:selectBooleanCheckbox id="termsId" value="#{playerBean.terms}" requiredMessage="You must accept terms and conditions!">
   <f:validator validatorId="omnifaces.RequiredCheckboxValidator" />
  </h:selectBooleanCheckbox>
  <h:commandButton value="Submit" action="#{playerBean.termsAction()}"/>               
 </h:panelGrid>           
 <h:message for="termsId" />           
</h:form> 

 Require the user to tick the desired checkbox (use HTML 5)

<h:form>                        
 <h:panelGrid columns="3">
  <h:outputLabel for="termsId" value="Tick terms and conditions:" />
  <h:selectBooleanCheckbox id="termsId" value="#{playerBean.terms}" pt:required="true" 
                           pt:x-moz-errormessage="You must accept terms and conditions!" title="You must accept terms and conditions!" />
  <h:commandButton value="Submit" action="#{playerBean.termsAction()}"/>               
 </h:panelGrid>           
 <h:message for="termsId" />           
</h:form>
For both cases, just add the field terms and method termsAction() in PlayerBean:

private boolean terms;

public boolean isTerms() {
 return terms;
}

public void setTerms(boolean terms) {
 this.terms = terms;
}  

public String termsAction(){
 return "data";
}

You can simply display the terms value in data.xhtml:

Terms: #{playerBean.terms}

Check on client side (via JS) if a checkbox is selected

<h:form id="formId">          
 Remember me:
 <h:selectBooleanCheckbox id="rememberId" value="#{playerBean.rememberme}"/>
 <h:commandButton value="Submit" action="data" onclick="isSelected();"/>
</h:form>
<script type="text/javascript">
 function isSelected() {
          alert($('#formId:rememberId'.replace(/:/g, "\\:")).is(':checked'));
 }
</script>

Complete source code on GitHub.
See also Mkyong.com

More resources on Constantin Alin, ZEEF page.
BooleanCheckbox in JSF Extension on JSF ShowCase ZEEF page.

Niciun comentariu :

Trimiteți un comentariu

JSF BOOKS COLLECTION

Postări populare

OmniFaces/JSF Fans

Visitors Starting 4 September 2015

Locations of Site Visitors