3 * Object-oriented HTML selectbox with validation
5 * @author Ant P <p@cpi.merseine.nu>
6 * @license http://specialops.ath.cx/repos/so2/trunk/COPYING (New BSD Licence)
9 class HTML_Select
implements Countable
15 private $values = array();
17 function __construct($name, $indent = 0, $default = null, $attributes = array())
19 $this->indent
= $indent;
20 $this->default = $default;
21 $this->attributes
= $attributes;
22 $this->attributes
['name'] = $name;
25 function add_item($value, $name = '')
30 $this->values
[$name] = $value;
33 function array_fill(array $items)
35 foreach ( $items as $row ) {
36 if ( is_array($row) ) {
37 $this->add_item($row[0], $row[1]);
39 $this->add_item($row);
44 function set_default($value)
46 $this->default = $value;
49 function check_value(&$value)
51 if ( !isset($value) ||
!in_array($value, $this->values
) ) {
52 throw new OutOfBoundsException('Bad value given for selectbox "'.$this->attributes
['name'].'": '.$value);
58 $t = str_repeat(" ", $this->indent
);
60 // Concat attributes into a string
62 foreach ( $this->attributes
as $name => $value ) {
63 $attribs .= sprintf(' %s="%s"', $name, $value);
66 // Concat options into another string (how exciting!)
69 foreach ( $this->values
as $name => $value ) {
70 $opts .= sprintf('%s <option value="%s"%s>%s</option>'."\n",
71 $t, $value, ( $value == $this->default ?
' selected="selected"' : '' ), $name);
73 return "\n$t<select".$attribs.">\n".$opts.$t."</select>\n$t";
76 public function count()
78 return count($this->values
);