2015-03-02 53 views
0

我想在此刻使用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兑现新增元素的约束条件?

+0

我一直无法重现这个问题从您的示例 - 动态字段上使用的约束在我的测试中得到尊重。你可以在你的问题中包含'$ data'的输出吗?除非您错误地认为您的_content_字段的'required'=> true'属性意味着NotBlank()约束? – 2015-03-02 22:49:06

+0

'$ data'就像'['_tb_1'=>'','_ title_1'=>'','_ img_url_1'=>'','_ img_alt_1'=>'','_ content_1'=>'' ]'。所以我期待'_content_1'上的错误,因为它不能为空。我错过了什么吗? – Optimus 2015-03-02 23:01:53

回答

1

表单组件和验证可能会非常棘手。一个容易误解的情况是表单类型选项“required”意味着NotBlank验证约束。情况并非如此,the docs explain that option仅与表单元素呈现(HTML5需要attr,标签等)有关,是“表面且独立于验证”。

为了使事情更复杂,即指定了最小长度约束,可以假设没有(或零)长度被认为是无效的。这也不是这种情况。长度验证器仅关注non-null/non-empty values。 : -/

所以!修改文本区域字段包括NotBlank()应该做的伎俩:

$form->add('_content_' . $id, 'textarea', [ 
    'required' => true, 
    'attr'  => [ 
     'data-role' => '_richeditor' 
    ], 
    'constraints' => [ 
     new NotBlank(), 
     new Length(['min' => 100]), 
    ] 
]); 
+0

这就是问题所在!这是我第一次使用这个组件,并猜测我仍然有读取负载。非常感谢你。 – Optimus 2015-03-02 23:39:46