phpsymfony1formatter

How to change the behavior of sfWidgetFormSelectRadio in symfony?


new sfWidgetFormSelectRadio(
                array('choices' => $images)));

The above will render each option something like:

<input type="radio" name="name" value="image_path">

How to make it render this way with minimal code:

<input type="radio" name="name" value="image_path"><img src="image_path" />

Solution

  • This is untested and straight from me reading the Symfony API docs for that widget. You'll need to extend the sfWidgetFormSelectRadio class, call it something like myWidgetFormSelectRadio and stick it in lib/widget/myWidgetFormSelectRadio.class.php in your project.

    Override the formatChoices() method like so:

    class myWidgetFormSelectRadio extends sfWidgetFormSelectRadio
    {
      protected function formatChoices($name, $value, $choices, $attributes)
      {
        $inputs = array();
        foreach ($choices as $key => $option)
        {
          $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';
          }
    
          $inputs[$id] = array(
            'input' =>
              $this->renderTag('input', array_merge($baseAttributes, $attributes))
              . $this->renderTag('img', array('src' => self::escapeOnce($key))),
            'label' => $this->renderContentTag('label', self::escapeOnce($option), array('for' => $id)),
          );
        }
    
        return call_user_func($this->getOption('formatter'), $this, $inputs);
      }
    }
    

    so you're basically appending the img tag to the input.

    In your form's configure() method you'll then need to switch from using sfWidgetFormSelectRadio to using myWidgetFormSelectRadio to use the new widget.

    Let me know if this works ;-)