Skip to content

Commit

Permalink
Add id suffix generation to radio buttons.
Browse files Browse the repository at this point in the history
This preserves behavior FormHelper had where it prevents duplicate ids
in a single set of radio options.
  • Loading branch information
markstory committed Feb 15, 2014
1 parent 912a2ba commit 33fced8
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 1 deletion.
19 changes: 18 additions & 1 deletion src/View/Widget/Radio.php
Expand Up @@ -40,6 +40,13 @@ class Radio implements WidgetInterface {
*/
protected $_label;

/**
* A list of id suffixes used in the current rendering.
*
* @var array
*/
protected $_idSuffixes = [];

/**
* Constructor
*
Expand Down Expand Up @@ -97,6 +104,7 @@ public function render(array $data) {
}
unset($data['empty']);

$this->_idSuffixes = [];
$opts = [];
foreach ($options as $val => $text) {
$opts[] = $this->_renderInput($val, $text, $data);
Expand Down Expand Up @@ -206,6 +214,15 @@ protected function _renderLabel($radio, $label, $input, $escape) {
* @return string Generated id.
*/
protected function _id($radio) {
return mb_strtolower(Inflector::slug($radio['name'] . '_' . $radio['value'], '-'));}
$value = mb_strtolower(Inflector::slug($radio['name'], '-'));
$idSuffix = mb_strtolower(str_replace(array('@', '<', '>', ' ', '"', '\''), '-', $radio['value']));
$count = 1;
$check = $idSuffix;
while (in_array($check, $this->_idSuffixes)) {
$check = $idSuffix . $count++;
}
$this->_idSuffixes[] = $check;
return trim($value . '-' . $check, '-');
}

}
36 changes: 36 additions & 0 deletions tests/TestCase/View/Widget/RadioTest.php
Expand Up @@ -123,6 +123,42 @@ public function testRenderComplex() {
$this->assertTags($result, $expected);
}

/**
* Test that id suffixes are generated to not collide
*
* @return void
*/
public function testRenderIdSuffixGeneration() {
$label = new Label($this->templates);
$radio = new Radio($this->templates, $label);
$data = [
'name' => 'Thing[value]',
'options' => ['a>b' => 'First', 'a<b' => 'Second']
];
$result = $radio->render($data);
$expected = [
['input' => [
'type' => 'radio',
'name' => 'Thing[value]',
'value' => 'a&gt;b',
'id' => 'thing-value-a-b'
]],
['label' => ['for' => 'thing-value-a-b']],
'First',
'/label',
['input' => [
'type' => 'radio',
'name' => 'Thing[value]',
'value' => 'a&lt;b',
'id' => 'thing-value-a-b2',
]],
['label' => ['for' => 'thing-value-a-b2']],
'Second',
'/label',
];
$this->assertTags($result, $expected);
}

/**
* Test rendering the empty option.
*
Expand Down

0 comments on commit 33fced8

Please sign in to comment.