1 24 package org.riotfamily.forms.element; 25 26 import java.io.PrintWriter ; 27 28 import org.riotfamily.common.markup.Html; 29 import org.riotfamily.common.markup.TagWriter; 30 import org.riotfamily.forms.AbstractEditorBase; 31 import org.riotfamily.forms.Editor; 32 import org.riotfamily.forms.ErrorUtils; 33 import org.riotfamily.forms.request.FormRequest; 34 35 36 39 public class Checkbox extends AbstractEditorBase implements Editor { 40 41 private static final String TYPE_CHECKBOX = "checkbox"; 42 43 private boolean checked; 44 45 private Object checkedValue = Boolean.TRUE; 46 47 private Object uncheckedValue = Boolean.FALSE; 48 49 private boolean checkedByDefault = false; 50 51 public Checkbox() { 52 setStyleClass(TYPE_CHECKBOX); 53 } 54 55 59 public void setCheckedValue(Object checkedValue) { 60 this.checkedValue = checkedValue; 61 } 62 63 67 public void setUncheckedValue(Object uncheckedValue) { 68 this.uncheckedValue = uncheckedValue; 69 } 70 71 public void setCheckedByDefault(boolean checkedByDefault) { 72 this.checkedByDefault = checkedByDefault; 73 } 74 75 public boolean isCheckedByDefault() { 76 return this.checkedByDefault; 77 } 78 79 public void setChecked(boolean checked) { 80 this.checked = checked; 81 } 82 83 public boolean isChecked() { 84 return checked; 85 } 86 87 public void renderInternal(PrintWriter writer) { 88 TagWriter inputTag = new TagWriter(writer); 89 inputTag.startEmpty(Html.INPUT) 90 .attribute(Html.INPUT_TYPE, TYPE_CHECKBOX) 91 .attribute(Html.INPUT_NAME, getParamName()) 92 .attribute(Html.COMMON_ID, getId()) 93 .attribute(Html.COMMON_CLASS, getStyleClass()) 94 .attribute(Html.INPUT_CHECKED, checked) 95 .end(); 96 } 97 98 101 public void setValue(Object value) { 102 if (value != null) { 103 this.checked = checkedValue.equals(value); 104 } 105 else { 106 this.checked = checkedByDefault; 107 } 108 } 109 110 118 public Object getValue() { 119 return checked ? checkedValue : uncheckedValue; 120 } 121 122 public void processRequest(FormRequest request) { 123 Object newValue = request.getParameter(getParamName()); 124 checked = newValue != null; 125 validate(); 126 } 127 128 protected void validate() { 129 if (isRequired() && !isChecked()) { 130 ErrorUtils.reject(this, "required"); 131 } 132 } 133 134 } | Popular Tags |