Skip to content

Instantly share code, notes, and snippets.

@ain
Created November 28, 2012 22:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ain/4165050 to your computer and use it in GitHub Desktop.
Save ain/4165050 to your computer and use it in GitHub Desktop.
sfWidgetFormSelectRadioSingleable Symfony widget lets you render just one option at a time. Extends sfWidgetFormSelectRadio.
<?php
class sfWidgetFormSelectRadioSingleable extends sfWidgetFormSelectRadio
{
public function formatChoices($name, $value, $choices, $attributes)
{
$onlyChoice = !empty($attributes['only_choice']) ? $attributes['only_choice'] : false;
unset($attributes['only_choice']);
if ($onlyChoice)
{
if (!isset($choices[$onlyChoice]))
{
throw new Exception("Option '$onlyChoice' doesn't exist.");
}
$key = $onlyChoice;
$option = $choices[$key];
$baseAttributes = array(
'name' => substr($name, 0, -2),
'type' => 'radio',
'value' => self::escapeOnce($key),
'id' => $id = $this->generateId($name, self::escapeOnce($key)),
);
if (strval($key) == strval($value === false ? 0 : $value))
{
$baseAttributes['checked'] = 'checked';
}
return $this->renderTag('input', array_merge($baseAttributes, $attributes));
}
else
{
return parent::formatChoices($name, $value, $choices, $attributes);
}
}
}
@ain
Copy link
Author

ain commented Nov 28, 2012

Example usage in a template:

<?php echo $form['item']->render(array('only_choice' => 'item_choice_key')) ?>

@piotrplenik
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment