123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129 |
- <?php
- class sfWidgetFormSelect extends sfWidgetForm
- {
-
- protected function configure($options = array(), $attributes = array())
- {
- $this->addRequiredOption('choices');
- $this->addOption('multiple', false);
- }
-
- public function render($name, $value = null, $attributes = array(), $errors = array())
- {
- if ($this->getOption('multiple'))
- {
- $attributes['multiple'] = 'multiple';
- if ('[]' != substr($name, -2))
- {
- $name .= '[]';
- }
- }
- $choices = $this->getOption('choices');
- if ($choices instanceof sfCallable)
- {
- $choices = $choices->call();
- }
- return $this->renderContentTag('select', "\n".implode("\n", $this->getOptionsForSelect($value, $choices))."\n", array_merge(array('name' => $name), $attributes));
- }
-
- protected function getOptionsForSelect($value, $choices)
- {
- $mainAttributes = $this->attributes;
- $this->attributes = array();
- if (!is_array($value))
- {
- $value = array($value);
- }
- $value = array_map('strval', array_values($value));
- $value_set = array_flip($value);
-
- $options = array();
- foreach ($choices as $key => $option)
- {
- if (is_array($option))
- {
- $options[] = $this->renderContentTag('optgroup', implode("\n", $this->getOptionsForSelect($value, $option)), array('label' => self::escapeOnce($key)));
- }
- else
- {
- $attributes = array('value' => self::escapeOnce($key));
- if (isset($value_set[strval($key)]))
- {
- $attributes['selected'] = 'selected';
- }
- $options[] = $this->renderContentTag('option', self::escapeOnce($option), $attributes);
- }
- }
- $this->attributes = $mainAttributes;
- return $options;
- }
- public function __clone()
- {
- if ($this->getOption('choices') instanceof sfCallable)
- {
- $callable = $this->getOption('choices')->getCallable();
- if (is_array($callable))
- {
- $callable[0] = $this;
- $this->setOption('choices', new sfCallable($callable));
- }
- }
- }
- }
|