我用 silex 框架构建了一个表单,其中包含一些复选框和一个文本字段。用户必须至少选中一个复选框或在文本字段中写一些东西。现在我不知道如何验证这样的依赖或更好地将验证逻辑放在哪里。我可以向单个字段添加约束,但是如何实现复选框或文本字段的依赖关系?
这是我在控制器类中的验证代码。
public function validateAction(Request $request, Application $app)
{
$form = $app['form.factory']->create(new ApplicationForm());
$form->bind($request);
if ($form->isValid()) {
return $app->json(array(
'success' => true,
));
}
}
ApplicationForm 类看起来像这样(简化):
class ApplicationForm extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('crafts', 'choice', array(
'choices' => array(
array('drywall' => 'Drywall'),
array('painter' => 'Painter'),
array('plasterer' => 'Plasterer'),
array('carpenter' => 'Carpenter'),
array('electrician' => 'Electrician'),
array('plumber' => 'Plumber'),
array('tiler' => 'Tiler'),
array('bricklayer' => 'Bricklayer'),
),
'multiple' => true,
'expanded' => true,
'required' => false,
))
->add('craftsOther', 'text', array(
'attr' => array('class' => 'textinput', 'placeholder' => 'Other', 'maxlength' => 256),
'constraints' => array(
new Assert\Length(array('max' => 256, 'maxMessage' => $this->_errorMessages['crafts_other_max'])),
),
'required' => false,
));
}
}
任何想法如何以优雅的方式做到这一点?