GroupedDropdownField.php
2.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
<?php
/**
 * Grouped dropdown, using <optgroup> tags.
 * 
 * $source parameter (from DropdownField) must be a two dimensional array.
 * The first level of the array is used for the <optgroup>, and the second
 * level are the <options> for each group.
 * 
 * Returns a <select> tag containing all the appropriate <option> tags, with
 * <optgroup> tags around the <option> tags as required.
 * 
 * <b>Usage</b>
 * 
 * <code>
 * new GroupedDropdownField(
 *    $name = "dropdown",
 *    $title = "Simple Grouped Dropdown",
 *    $source = array(
 *       "numbers" => array(
 *       		"1" => "1",
 *       		"2" => "2",
 *       		"3" => "3",
 *       		"4" => "4"
 *    		),
 *       "letters" => array(
 *       		"1" => "A",
 *       		"2" => "B",
 *       		"3" => "C",
 *       		"4" => "D",
 *       		"5" => "E",
 *       		"6" => "F"
 *    		)
 *    )
 * )
 * </code>
 * 
 * <b>Disabling individual items</b>
 * 
 * <code>
 * $groupedDrDownField->setDisabledItems( 
 *    array(
 *       "numbers" => array(
 *       		"1" => "1",
 *       		"3" => "3"
 *    		),
 *       "letters" => array(
 *       		"3" => "C"
 *    		)
 *    )
 * )
 * </code>
 * 
 * @package forms
 * @subpackage fields-basic
 */
class GroupedDropdownField extends DropdownField {
	public function Field($properties = array()) {
		$options = '';
		foreach($this->getSource() as $value => $title) {
			if(is_array($title)) {
				$options .= "<optgroup label=\"$value\">";
				foreach($title as $value2 => $title2) {
					$disabled = '';
					if( array_key_exists($value, $this->disabledItems)
							&& is_array($this->disabledItems[$value]) 
							&& in_array($value2, $this->disabledItems[$value]) ){
						$disabled = 'disabled="disabled"';
					}
					$selected = $value2 == $this->value ? " selected=\"selected\"" : "";
					$options .= "<option$selected value=\"$value2\" $disabled>$title2</option>";
				}
				$options .= "</optgroup>";
			} else { // Fall back to the standard dropdown field
				$disabled = '';
				if( in_array($value, $this->disabledItems) ){
					$disabled = 'disabled="disabled"';
				}
				$selected = $value == $this->value ? " selected=\"selected\"" : "";
				$options .= "<option$selected value=\"$value\" $disabled>$title</option>";
			}
		}
		return FormField::create_tag('select', $this->getAttributes(), $options);
	}
	public function Type() {
		return 'groupeddropdown dropdown';
	}
	
}