1. sfWidgetFormSelect.class.php
  2. /** * sfWidgetFormSelect represents a select HTML tag. * * @package symfony * @subpackage widget * @author Fabien Potencier * @version SVN: $Id: sfWidgetFormSelect.class.php 23994 2009-11-15 22:55:24Z bschussek $ */
  3. class sfWidgetFormSelect extends sfWidgetFormChoiceBase
  4. {
  5. /**
  6. * Constructor.
  7. *
  8. * Available options:
  9. *
  10. * * choices: An array of possible choices (required)
  11. * * multiple: true if the select tag must allow multiple selections
  12. *
  13. * @param array $options An array of options
  14. * @param array $attributes An array of default HTML attributes
  15. *
  16. * @see sfWidgetFormChoiceBase
  17. */
  18. protected function configure($options = array(), $attributes = array())
  19. {
  20. parent::configure($options, $attributes);
  21. $this->addOption('multiple', false);
  22. }
  23. /**
  24. * @param string $name The element name
  25. * @param string $value The value selected in this widget
  26. * @param array $attributes An array of HTML attributes to be merged with the default HTML attributes
  27. * @param array $errors An array of errors for the field
  28. *
  29. * @return string An HTML tag string
  30. *
  31. * @see sfWidgetForm
  32. */
  33. public function render($name, $value = null, $attributes = array(), $errors = array())
  34. {
  35. if ($this->getOption('multiple'))
  36. {
  37. $attributes['multiple'] = 'multiple';
  38. if ('[]' != substr($name, -2))
  39. {
  40. $name .= '[]';
  41. }
  42. }
  43. $choices = $this->getChoices();
  44. return $this->renderContentTag('select', "\n".implode("\n", $this->getOptionsForSelect($value, $choices))."\n", array_merge(array('name' => $name), $attributes));
  45. }
  46. /**
  47. * Returns an array of option tags for the given choices
  48. *
  49. * @param string $value The selected value
  50. * @param array $choices An array of choices
  51. *
  52. * @return array An array of option tags
  53. */
  54. protected function getOptionsForSelect($value, $choices)
  55. {
  56. $mainAttributes = $this->attributes;
  57. $this->attributes = array();
  58. if (!is_array($value))
  59. {
  60. $value = array($value);
  61. }
  62. $value = array_map('strval', array_values($value));
  63. $value_set = array_flip($value);
  64. $options = array();
  65. foreach ($choices as $key => $option)
  66. {
  67. if (is_array($option))
  68. {
  69. $options[] = $this->renderContentTag('optgroup', implode("\n", $this->getOptionsForSelect($value, $option)), array('label' => self::escapeOnce($key)));
  70. }
  71. else
  72. {
  73. $attributes = array('value' => self::escapeOnce($key));
  74. if (isset($value_set[strval($key)]))
  75. {
  76. $attributes['selected'] = 'selected';
  77. }
  78. $options[] = $this->renderContentTag('option', self::escapeOnce($option), $attributes);
  79. }
  80. }
  81. $this->attributes = $mainAttributes;
  82. return $options;
  83. }
  84. }

Debug toolbar