00001 <?php
00008 class ConditionalField extends CollectionField
00009 {
00010 private $activeOn;
00011 protected static $jsDrawn = false;
00012
00019 public function __construct($name, Form &$parentForm, array $attribs = array())
00020 {
00021 if(array_key_exists('fields', $attribs) === false)
00022 throw new Exception("key 'fields' must exist in attribs array");
00023
00024 if(count($attribs['fields']) != 1)
00025 throw new Exception("only one field can be added to a ConditionalField");
00026
00027 array_unshift($attribs['fields'], array('CheckboxField', "${name}_box", $attribs));
00028
00029 # Set a "normal" default
00030 $this->activeOn = true;
00031 parent::__construct($name, $parentForm, $attribs);
00032 }
00033
00034
00040 public function __set($name, $value)
00041 {
00042 if($name == 'activeOn')
00043 $this->activeOn = $value;
00044 else
00045 parent::__set($name, $value);
00046 }
00047
00048
00052 public function drawInput()
00053 {
00054 $subFieldArr = $this->subFieldsToJsArray();
00055 $this->fields[0]->onchange = "changeCondState(this, $subFieldArr, " . ($this->activeOn ? 'true' : 'false') . ');';
00056 parent::drawInput();
00057 }
00058
00063 public function getJs()
00064 {
00065 if(self::$jsDrawn)
00066 return null;
00067
00068 self::$jsDrawn = true;
00069
00070 return <<<EOJAVASCRIPT
00071 function changeCondState(chkbox, fields, activeOn)
00072 {
00073 var newDisabled;
00074
00075 if(chkbox.checked == activeOn)
00076 newDisabled = false;
00077 else
00078 newDisabled = true;
00079
00080
00081 for(var i = 0; i < fields.length; i++)
00082 {
00083 var fieldObj = document.getElementById(fields[i]);
00084 fieldObj.disabled = newDisabled;
00085 }
00086 }
00087 EOJAVASCRIPT;
00088 }
00089
00090
00095 protected function subFieldsToJsArray()
00096 {
00097 $fieldNames = array();
00098 foreach($this->fields as $field)
00099 {
00100 $fieldNames[] = $field->name;
00101 }
00102 array_shift($fieldNames); # don't include the checkbox (which should be the first field)
00103
00104 return 'new Array(\'' . implode('\', \'', $fieldNames) . '\')';
00105 }
00106 }
00107 ?>