我想在此刻使用Symfony表单组件与Silex框架。我在我的表单类类的buildForm
方法中添加了一些字段。用户也可以点击一个按钮,并在前端使用javascript添加无限制的textarea
元素。现在PRE_SUBMIT
事件,我做了以下这些字段添加到表单在PRE_SUBMIT上向Symfony表单添加动态元素
$data = $event->getData();
$form = $event->getForm();
foreach ($data as $key => $value) {
if (stristr($key, '_tb_') !== false) {
$id = str_ireplace('_tb_', '', $key);
$form->add('_tb_' . $id, 'hidden');
$form->add('_title_' . $id, 'text', [
'required' => false,
'label' => 'Title',
'constraints' => [
new Length(['min' => 6]),
]
]);
$form->add('_img_url_' . $id, 'text', [
'required' => false,
'label' => 'Image Url',
'constraints' => [
new Url(),
]
]);
$form->add('_img_alt_' . $id, 'text', [
'required' => false,
'label' => 'Image Alt',
'constraints' => []
]);
$form->add('_content_' . $id, 'textarea', [
'required' => true,
'attr' => [
'data-role' => '_richeditor'
],
'constraints' => [
new Length(['min' => 100]),
]
]);
}
}
我可以看到这些字段添加到窗体和填充一旦提交表单的第一次,但由于某种原因,所有的只有这些新添加的字段才会忽略约束。有没有办法强制Form
兑现新增元素的约束条件?
我一直无法重现这个问题从您的示例 - 动态字段上使用的约束在我的测试中得到尊重。你可以在你的问题中包含'$ data'的输出吗?除非您错误地认为您的_content_字段的'required'=> true'属性意味着NotBlank()约束? – 2015-03-02 22:49:06
'$ data'就像'['_tb_1'=>'','_ title_1'=>'','_ img_url_1'=>'','_ img_alt_1'=>'','_ content_1'=>'' ]'。所以我期待'_content_1'上的错误,因为它不能为空。我错过了什么吗? – Optimus 2015-03-02 23:01:53