views:

93

answers:

2

Hy,

How i try to do to validate that in a symfony form one of two fields is filled? In their database definition are'nt required fields but i need that one of two fields will be filled by the user.

Thanks

Like this???

$this->setValidator('phone', new sfValidatorAnd(
                                                      array(
                                                        new sfValidatorSchemaCompare('email', '==', ''),
                                                        new sfValidatorSchemaCompare('phone', '==', ''),
                                                      ),
                                                      array(),
                                                      array('invalid' => 'El e-mail no tiene un formato correcto',
                                                            'required'   => 'Campo obligatorio'
                                                            )
                                                    ));

it doesn't work... :(

A: 

I'm not sure if there is a better method but you could use sfValidatorOr to check if one of the fields validates (i.e set required to true).

More about sfValidatorOr: http://www.symfony-project.org/forms/1_2/en/B-Validators#chapter_b_sub_sfvalidatoror

Mariusz
+1  A: 

When comparing two separate fields you should use a global validator: http://www.symfony-project.org/forms/1_2/en/02-Form-Validation#chapter_02_global_validators. Your current approach will always mark the phone field as invalid when an error occurs. Also, the conditions you supply to the validator should return true when the values are valid so in your case you should be using a ValidatorOr with != comparisons like this:

$this->validatorSchema->setPostValidator(new sfValidatorOr(
  array(
    new sfValidatorSchemaCompare('email', '!=', ''),
    new sfValidatorSchemaCompare('phone', '!=', ''),
  ),
  array(),
  array('invalid' => 'Campo obligatorio')
));

Hope that helps.

Cryo
i try it but it never raise an error. not create register but neither show me the error. how can i show the error?thanks.
nebur85
http://www.symfony-project.org/forms/1_2/en/03-Forms-for-web-Designers#chapter_03_sub_handling_global_errorsYou can use $form->hasGlobalErrors() to check and echo $form->renderGlobalErrors() to print. If you'd like to do custom rendering you can iterate through $form->getGlobalErrors() for name/message pairs of all global errors as well.
Cryo
Cyro, thanks. It seems it work ok :)
nebur85