1010
1111abstract class ChoiceWidget extends Widget
1212{
13- const TEMPLATE_OPTION = '' ;
13+ const TEMPLATE_OPTION = "" ;
1414
1515 protected $ allow_multiple_selected = false ;
1616 protected $ input_type = null ;
1717 protected $ option_inherits_attrs = true ;
18+ protected $ selected_attribute = "selected " ;
1819 protected $ choices ;
1920
2021 /**
@@ -24,25 +25,26 @@ public function __construct(array $choices = array(), array $css_classes = null,
2425 {
2526 parent ::__construct ($ css_classes , $ attrs );
2627
27- $ this ->choices = $ choices ;
28+ $ this ->setChoices ( $ choices) ;
2829 }
2930
30- public function setChoices (array $ value )
31+ public function setChoices (array $ choices )
3132 {
3233 $ this ->choices = $ choices ;
3334 }
3435
3536 public function getContext (string $ name , $ value , array $ attrs = null )
3637 {
3738 $ context = parent ::getContext ($ name , $ value , $ attrs );
38- $ context ["options " ] = $ this ->renderOptions ($ context [' name ' ], $ context [' value ' ], $ attrs );
39+ $ context ["options " ] = $ this ->renderOptions ($ context [" name " ], $ context [" value " ], $ attrs );
3940
4041 return $ context ;
4142 }
4243
4344 public function renderOptions (string $ name , $ value , array $ attrs = null )
4445 {
45- $ options = '' ;
46+ $ options = "" ;
47+ $ index = 1 ;
4648 $ has_selected = false ;
4749
4850 foreach ($ this ->choices as $ choice_value => $ choice_label ) {
@@ -53,30 +55,43 @@ public function renderOptions(string $name, $value, array $attrs = null)
5355 $ has_selected = true ;
5456 }
5557
56- $ context = $ this ->getOptionContext ($ name , $ choice_value , $ choice_label , $ selected , $ attrs );
58+ $ context = $ this ->getOptionContext ($ name , $ choice_value , $ choice_label , $ selected , $ index , $ attrs );
5759
5860 $ options .= Formatter::format (static ::TEMPLATE_OPTION , $ context );
61+
62+ $ index ++;
5963 }
6064
6165 return $ options ;
6266 }
6367
64- public function getOptionContext (string $ name , $ value , string $ label , bool $ is_selected , array $ attrs = null )
65- {
68+ public function getOptionContext (
69+ string $ name ,
70+ $ value ,
71+ string $ label ,
72+ bool $ is_selected ,
73+ int $ index ,
74+ array $ attrs = null
75+ ) {
6676 if (!$ this ->option_inherits_attrs || is_null ($ attrs )) {
6777 $ attrs = array ();
6878 }
6979
80+ if ($ this ->option_inherits_attrs ) {
81+ $ attrs ["id " ] = $ this ->buildAutoId ($ name , $ index );
82+ }
83+
7084 if ($ is_selected ) {
71- $ attrs [" selected " ] = " selected " ;
85+ $ attrs [$ this -> selected_attribute ] = $ this -> selected_attribute ;
7286 }
7387
7488 return array (
89+ "for " => $ this ->buildAutoId ($ name , $ index ),
7590 "type " => $ this ->input_type ,
7691 "name " => $ name ,
7792 "value " => htmlentities ($ value ),
7893 "label " => htmlentities ($ label ),
79- "attrs " => Attributes::flatatt ($ attrs )
94+ "attrs " => Attributes::flatatt ($ attrs ),
8095 );
8196 }
8297
0 commit comments