【问题标题】:Validation using entity for a FormType inside a form使用实体对表单内的 FormType 进行验证
【发布时间】:2016-03-22 17:36:29
【问题描述】:

我有两个实体:CompanyLocation。一家公司有一个地点(而一个地点可能“拥有”多家公司)。现在,当用户创建公司时,我希望他/她能够以相同的形式创建位置。所以我使用以下

    $builder
        ->add('name', TextType::class, ['label' => 'company.name'])
        ->add('size', IntegerType::class, ['label' => 'company.size'])
        ->add( $builder->create('location', FormType::class, [
                'label' => 'company.location',
                'by_reference' => true,
                'data_class' => 'AppBundle\Entity\Location',
            ])
            ->add('street', TextType::class, [
                'label' => 'location.street',
            ])
            ->add('number', TextType::class, [
                'label' => 'location.number',
            ])

这在创建表单时效果很好。现在谈到验证。我在各自的文件中为这两个实体添加了 @Assert 注释。虽然company 验证有效,但location 不会自动验证。

我设法通过将constraint 属性添加到新的$builder->create('location') 元素来获得验证,但这意味着重复的代码(在实体中一次,在需要location 的每个表单中至少一次)。

如何解决这个问题,以便通过使用实体的注释来验证表单?

【问题讨论】:

  • 创建自定义验证器不是更好(以处理位置已经存在或公司不能在该位置的情况......)?如果是这样,请参阅symfony.com/doc/current/cookbook/validation/…
  • @εEridani 好主意(我对 symfony 很陌生 ..)。现在错误在表单上方弹出并且没有映射到字段。我试过error_mapping,但似乎无法让它工作(在左侧使用.,仍然出现在表单上方)
  • 使用“类约束”然后在上下文中执行如下操作: public function validate($myLocationEntity, Constraint $constraint) { context->addViolationAt ( 'FIELD_NAME', "duplication area or some randome message" , 数组 (), 空); } 然后在树枝中你必须添加: {{ form_errors(form.FIELD_TO_VALIDATE) }}
  • @εEridani 会记住这一点,现在@Assert\Valid 做得很好

标签: php validation symfony-forms symfony


【解决方案1】:

默认情况下,验证不会遍历对象或集合的属性。使用valid constraint:

http://symfony.com/doc/current/reference/constraints/Valid.html

您也可以为集合设置遍历选项。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-05
    • 2020-12-11
    • 2011-07-05
    • 1970-01-01
    相关资源
    最近更新 更多