我有一个"标准" OneToMany关系。
我之前从未使用过这个设置有问题:我想从关系的反面添加/编辑/删除,但是我遇到了错误。
我有这个:问题0,n - 1,1命题
我在问题表单中设置了一个集合来添加命题。我使用"standard" symfony setup进行集合管理。
当我创建一个问题并添加一个或多个命题时,数据会被保存好。
但是当我删除该问题表单中的一个或多个命题并点击保存时,我有错误"命题名称必须设置为#34;,来自Propostion name属性!
从一般情况来说,我从拥有方管理这种形式,我是否错过了实体设置中的重要内容#34;反向"使用 ?或者我应该在控制器中做些什么?
控制器
class QuestionController extends BaseController
{
public function editAction(Request $request, Question $question)
{
$errors = null;
$form = $this->createForm(QuestionType::class, $question);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($question);
$em->flush();
}
...
}
}
我设置了我的实体
class Question
{
/**
@ORM\OneToMany(targetEntity="Proposition", mappedBy="question", cascade={"persist", "remove"}, orphanRemoval=TRUE)
* @Assert\Valid
*/
protected $propositions;
public function __construct()
{
$this->propositions = new ArrayCollection();
}
public function addProposition(Proposition $proposition)
{
$this->propositions[] = $proposition;
$proposition->setQuestion($this); //because this is the inversed side
return $this;
}
public function removeProposition(Proposition $proposition)
{
$this->propositions->removeElement($proposition);
}
public function getPropositions()
{
return $this->propositions;
}
}
并且
class Proposition
{
/**
* @var string
*
* @ORM\Column(name="name", type="string", length=255, nullable=false)
* @Assert\NotBlank(message="the proposition name must be set")
*/
protected $name;
/**
* @ORM\ManyToOne(targetEntity="Question", inversedBy="propositions")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="questionId", referencedColumnName="id")
* })
*/
private $question;
//+ other attributes to be set
public function setQuestion(Question $question)
{
$this->question = $question;
return $this;
}
public function getQuestion()
{
return $this->question;
}
}
表格
class QuestionType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
...
->add('propositions', CollectionType::class, [
'label' => 'propositions',
'required' => false,
'attr' => [
'class' => 'collectiondata',
],
'constraints' => new Valid(),
'prototype_name' => '__proposition_prot__',
'entry_type' => PropositionType::class,
'entry_options' => [],
'by_reference' => false,
'allow_add' => true,
'allow_delete' => true,
]);
}
}
class PropositionType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', TextType::class, [
'label' => 'name',
'label_attr' => ['class' => 'mandatory'],
'required' => true,
'attr' => [
'class' => 'form-control',
],
])
->add('correctAnswer', CheckboxType::class, [
'label' => 'proposition.correctAnswer',
'required' => false,
])
;
}
}
我看到了this post,但它没有帮助