【问题标题】:Symfony form common fields inheritance/compositionSymfony 表单公共字段继承/组合
【发布时间】:2019-11-27 17:08:12
【问题描述】:

我有 2 个实体 AB 共享公共字段,我使用 trait 来设置基于 (Doctrine inheritance for entities common fields) 的公共字段,因为我不想使用 MappedSuperClass

为实体B 设置一个restful post 路由,我实例化一个FormBTypedata_class 映射到B::class,扩展FormCType(包含公共字段和'data_class' 映射到任何内容) .

我尝试对https://symfony.com/doc/current/form/inherit_data_option.html 使用inherit_data 方法,但我不想在我的表单中使用额外的键/嵌套层(我想要一个扁平的)。

我的问题是没有考虑使用 Assert 对特征中的公共字段进行验证,并且表单通过 validation 并带有空字符串。

class B {
use CTrait;
}


//trait that has the common fields with ORM mapping and Assert
trait CTrait {
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;

/**
* @ORM\Column(type="string")
* @ORM\Assert\Length(min="2")
*/
private $name;
}


//Common fields formType
class CType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('name');
    }
}

//Form using the common fields formType
class BType extends CType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        parent::buildForm($builder, $options);
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => B::class,
            'csrf_protection' => false,
        ]);
    }
}

【问题讨论】:

    标签: php forms symfony inheritance composition


    【解决方案1】:

    在进一步检查 Length 之后,我意识到空字符串被认为是有效值,并且它仍然通过使用 name: "" 的验证,即使我有 Assert\Length(min=2),在添加 NotBlank 后验证工作。

    【讨论】:

      猜你喜欢
      • 2015-07-15
      • 2017-04-12
      • 2012-11-15
      • 1970-01-01
      • 1970-01-01
      • 2011-01-12
      • 2011-01-05
      • 2018-10-15
      • 1970-01-01
      相关资源
      最近更新 更多