Symfony 1.4 - How to set default values on sfWidgetFormChoice (checkboxes)

afilina picture afilina · Mar 20, 2012 · Viewed 16.3k times · Source

The following code creates a field with multiple checkboxes. How do I set the default values of these checkboxes?

new sfWidgetFormChoice(array(
 "choices" => $choices,
 "label" => "Label",
 "multiple" => true,
 "expanded" => true
));

Answer

Mike Purcell picture Mike Purcell · Mar 20, 2012

You can set the defaults manually:

$countries = array(
    'Spain',
    'England',
    'France'
);

$this->widgetSchema['countries'] = new sfWidgetFormChoice(array('choices' => $countries, 'multiple' => true, 'expanded' => true));

// Form will render with Spain and England pre-selected
$this->widgetSchema['countries']->setDefault(array(0,1));

If the object to which the form is related is not new, the defaults will pre-selected based on stored values, so you may need to add a $this->getObject()->isModified() check around the last line.