2012-03-14 54 views
2

我有一个Symfony2中没有连接到任何实体的表单。它有一个子表单,其中1..n个实例可以在前端动态添加。验证未连接到Symfony 2中的实体的子表单

$builder 
    //car data 
     ->add('cars', 'collection', array(
      'label' => ' ', 
      'type' => new CarLeasingType(), 
      'allow_add' => true, 
      'prototype' => true, 
     )) 

父窗体有它的验证来验证窗体中的其他字段。

public function getDefaultOptions(array $options) 
{ 
    $collectionConstraint = new Collection(array(
     'fields' => array(
      //some fields an their validation 
     ), 
     'allowExtraFields' => true, 
    )); 

    return array('validation_constraint' => $collectionConstraint); 
} 

子窗体(CarLeasingType类型)有它自己的验证。我现在的问题有两个层次:

  • 我必须设置“allowExtraFields”为true父窗体验证约束,否则我得到了像The fields 0, 1 were not expected
  • 子窗体验证约束的消息完全不执行。

要解释为什么从子窗体的cars领域被确定为01这里是JavaScript函数我用从data-prototype属性动态生成的子窗体:

function add_dynamic_field(holderId) { 
    var collectionHolder = $('#' + holderId); 
    if (0 === collectionHolder.length) return false; 
    var prototype = collectionHolder.attr('data-prototype'); 
    form = prototype.replace(/<label class=" required">\$\$name\$\$<\/label>/, ''); 
    form = form.replace(/\$\$name\$\$/g, collectionHolder.children().length); 
    collectionHolder.append(form); 
} 

我如何可以验证也每个子表单动态添加?

回答

1

也许这些方针的东西可能有帮助:

public function somexAction() 
{ 

    //get objects through the $form object 

    //get validator service 
    $validator = $this->get('validator'); 

    //validate objects manually 
    foreach object as obj 
     $errors = $validator->validate($obj); 
    if (count($errors) > 0) { 
     //... 
    } else { 
     //.... 
    } 
} 

基本上,这意味着以验证服务的优势。

http://symfony.com/doc/current/book/validation.html

采取有关验证方法/详细信息等,检查出api