symfony 1.4 dynamic add form widgets without using embeded forms
I have a symfony form and i need to add a couple of fields(widgets) dynamicly via jquery. Let´s say i have an User form and I want the user to be able to set multiple emails addresses,
The "email" is just a simple widget and not a form so using embeded forms ,like most of the tutorials avaliable in th开发者_开发问答e net, doesn´t make sense.
What is the best approach to this?
The suggested way would be to use the embedded form, but I see how that could not be useful to you (given the form inputs are added via Javascript).
One solution I suggest (while eager to see how other people would solve this) is to remove the email
field from the widget schema and only add it to your validation schema (with custom callback).
Not tested but something along the lines as a guide.
class YourForm extends sfForm {
public function configure() {
$this->setValidators(array(
'email' => new sfValidatorCallback(array(
'callback' => array($this, 'my_email_validator')
))
));
}
public function my_email_validator($validator, $value) {
$email_validator = new sfValidatorEmail();
try {
foreach($value as $email) { // multiple fields with the same name
$email_validator->clean($email); // throws exception when not valid
}
}
catch(sfValidatorError $e) {
// $email is invalid - notify user or whatever
// you could also rethrow a sfValidatorError so that the form->isValid
// would return false
}
}
}
And you would have in your template the field (manually yes).
<input type="text" name="email[]" />
<input type="text" name="email[]" />
<input type="text" name="email[]" />
<input type="text" name="email[]" />
I would still like to see others suggestion, because this looks hackish to me as well.
精彩评论