Set defaults in the Select option in Symfony?

I am using a widget

sfWidgetFormChoice(array (
  'choices' => CountryPeer::getAllCountry(),
))

and validator as

sfValidatorChoice(array (
  'choices' => array_keys(CountryPeer::getAllCountry()),
))

I get the select element as

<select id="country" name="reg_form[country]">
  <option value="1">India</option>
  <option value="2">Srilanka</option>
</select>

I want to add a --Select Countries--default option :

<option value="">--Select Countries--</option>

so that it produces the required error if I do not select any country.

+3
source share
2 answers

First, add the parameter to the array of options, but not to the validator, so it will throw an error:

$def_val = array(-1=>"--Select Countries--");

$sel_choices = array_merge($def_val,CountryPeer::getAllCountry());

sfWidgetFormChoice(array (
  'choices' => $sel_choices,
))

sfValidatorChoice(array (
  'choices' => array_keys(CountryPeer::getAllCountry()),
))

And then set the value to “-1” as the default value:

 $your_form->setDefault('country', -1);

Must do it.

+5
source

You can set the required option to false

sfValidatorChoice (array ('required' => false, 'choice' => array_keys (CountryPeer :: getAllCountry ()),))

.

+1

Source: https://habr.com/ru/post/1723335/


All Articles