Monday, November 22, 2010

Symfony : Radio Widgets with formatting

symfony provides concept of widget. it's just like a sub-framework that provide classes to output HTML fields like input, textarea, select, radio etc...

Suppose you want to create widgets for the set of radio buttons with the option of html formatting of the radio button. creating a form class in module lib directory say Itinerary.Form.class.php
// Itinerary.Form.class.php
class ItineraryForm extends sfForm

  public static function radioFormatter($widgets, $inputs)
    $rows = array();
    foreach ($inputs as $input)
      $rows[] = $input['input'].$input['label'];
    return "".implode("", $rows)."";

  public function configure()
      $tourTipChoice    =    array(
                                                         'tourItinerary'                => 'Itinerary',
                                                         'InclusionsExclusions'=> 'Inclusions/ Exclusions',
                                                         'sightSeeing'                 => 'Sightseeing'

    $this->setWidgets(array( 'tourTip'   => new sfWidgetFormSelectRadio(array(
'choices'                => $tourTipChoice,
                                                                              'formatter'            => array($this, 'radioFormatter')

    $this->validatorSchema->setOption('allow_extra_fields', true);      
    $this->validatorSchema->setOption('filter_extra_fields', false);
    $this->setDefault('tourTip', 'Itinerary');

after that just creating the object this class in action.class.php.
suppose you want to render the widget in your index file. so just create object inside the index funciton like as :
public function executeIndex(sfWebRequest $request)
      $this->form = new ItineraryTourForm();  //Used to call form widgets

now you have to call only the function inside template i.e. in indexSuccess.php

echo $form['tourTip']->render();

It will render the  radio button list in the vertical format as we set in formatter. If we want to add other event on the radio button like onclick(), onsubmit() etc... i.e.

echo $form['tourTip']->render( array('onclick'=> 'showtourTip(this.value);'));