【发布时间】:2019-11-27 17:08:12
【问题描述】:
我有 2 个实体 A 和 B 共享公共字段,我使用 trait 来设置基于 (Doctrine inheritance for entities common fields) 的公共字段,因为我不想使用 MappedSuperClass。
为实体B 设置一个restful post 路由,我实例化一个FormBType,data_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