Special Ops 2.50
[specialops2.git] / lib / HTML_Select.php
blobb2e75c135f8b61677d3201408a6285b9911b04dc
1 <?php
2 /**
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)
7 * @version 2.15
8 */
9 class HTML_Select implements Countable
11 public $name;
12 public $indent;
13 public $default;
14 public $attributes;
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 = '')
27 if ( !$name ) {
28 $name = $value;
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]);
38 } else {
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);
56 function __toString()
58 $t = str_repeat(" ", $this->indent);
60 // Concat attributes into a string
61 $attribs = '';
62 foreach ( $this->attributes as $name => $value ) {
63 $attribs .= sprintf(' %s="%s"', $name, $value);
66 // Concat options into another string (how exciting!)
67 $opts = '';
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);