我遇到类似的问题: Replace an object with Null value Using Form Builder in Symfony2
我有一个名为Classification的实体,它与另一个名为TypeClassification的实体有一个ManyToOne关系(一个分类属于一个类型分类,或者没有类型分类)。
Classification.php:
/**
* @ORM\ManyToOne(targetEntity="TypeClassification", inversedBy="classifications", fetch="EAGER")
*/
private $typeclassification;
TypeClassification.php:
/**
* @ORM\OneToMany(targetEntity="Classification", mappedBy="typeclassification")
*/
private $classifications;
symfony默认生成的分类表单有效,这里是代码:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name')
->add('namejapanese')
->add('ldapid')
->add('typeclassification','entity', array('class' => 'ACMEMyBundle:TypeClassification','required' => false));
}
我的问题依赖于实体选择字段。我想允许Null值,并将关系设置为Null。
正如我所说的那样,到目前为止,但只要我向实体分类添加验证约束,即使它们与关系完全无关:
validation.yml:
ACME\MyBundle\Entity\Classification:
#If I commend this constraints, everything works properly.
constraints:
- Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity: { fields: name, message: unique.name }
- Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity: { fields: ldapid, message: unique.ldapid }
#For this properties doesn't matter if they are here or not
properties:
name:
- NotBlank:
message: not.blank
namejapanese:
- NotBlank:
message: not.blank
ldapid:
- NotBlank:
message: not.blank
然后我无法将关系设置回Null。但如果我评论约束部分,那么我可以将其设置为Null。
为什么会这样?我怎样才能让它具有这种验证和将关系设置为Null的能力?