开发者

Set default values in Select option in Symfony?

开发者 https://www.devze.com 2022-12-12 12:16 出处:网络
I am using the widget sfWidgetFormChoice(array ( \'choices\' => CountryPeer::getAllCountry(), )) and validator as

I am using the widget

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

and validator as

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

I get a 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 option --Select Countries-- as default:

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

so that it should throw an required error, if i am not selecting any country.


First, add the option to the array of choices, but not into the validator, so it will throw the 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 "-1" option as the default value:

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

Should do it.


You can set required option to false

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

it should work.

0

精彩评论

暂无评论...
验证码 换一张
取 消