问题描述
父实体与子实体之间存在一对多关系,如下所示:
/**
* @ORM\OnetoMany(targetEntity=Child::class,mappedBy="parent")
*/
private $children;
我需要限制可以与父母关联的孩子的数量,所以我添加了一个 count constraint。
/**
* @ORM\OnetoMany(targetEntity=Child::class,mappedBy="parent")
* @Assert\Count(max=10 maxMessage = "You cannot add more than ten children")
*/
private $children;
问题是,我用来创建新子记录的表单有一个Child::class
的数据类,新的子实体只根据自己的约束进行验证,而不包括父实体的约束,所以我可以为父实体创建更多的子实体。
在我用来编辑父级的表单中,如果关联的子级过多,验证将失败,所以我知道约束通常有效,但我不确定如何在创建时验证它单独的子记录。
我知道我可以制作一个自定义验证器来完成我需要做的事情,这是我的下一步,但我觉得我可能缺少一种更明显的方法来完成这项工作。
创建新子记录的控制器方法:
/**
* @Route("/new-child",name="child_new",methods={"GET","POST"})
*/
public function newChild(Request $request): Response
{
$parent = $this->getParent();
$child = new Child();
$form = $this->createForm(ChildType::class,$child);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entityManager = $this->getDoctrine()->getManager();
$child->setParent($parent);
$entityManager->persist($child);
$entityManager->flush();
return $this->redirectToRoute('home');
}
return $this->render('public/new-child.html.twig',[
'child' => $child,'form' => $form->createView(),]);
}
子窗体类:
class ChildType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder,array $options)
{
$builder
->add('firstName')
->add('lastName');
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Child::class,]);
}
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)