symfony 1.4动态添加窗体小部件而不使用嵌入的形式
问题描述:
我有一个symfony窗体,我需要通过jquery动态添加几个字段(小部件)。比方说,我有一个用户表单,我希望用户能够设置多个电子邮件地址,symfony 1.4动态添加窗体小部件而不使用嵌入的形式
“电子邮件”只是一个简单的小部件,而不是像使用嵌入式表单那样的表单,就像大多数教程一样在网络中可用,没有意义。
这是最好的方法是什么?
答
建议的方式是使用嵌入式表单,但是我看到这对您没有用处(因为表单输入是通过Javascript添加的)。
一个解决方案,我建议(同时渴望看到人们将如何解决等这)是从小部件架构删除的email
领域,只有将其添加到您的验证模式(通过自定义的回调)。
未经测试,但沿线的东西作为指导。
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
}
}
}
而且你会在你的模板领域(手动是)。
<input type="text" name="email[]" />
<input type="text" name="email[]" />
<input type="text" name="email[]" />
<input type="text" name="email[]" />
我仍然希望看到其他人的建议,因为这对我来说也很不好。
+0
有趣的解决方案。 – brpaz 2011-02-11 19:28:20
我宁愿将我所有的代码放在表单类中,而不是手动创建表单元素。 – brpaz 2011-02-12 12:17:18