微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用 OneToMany 关系上的内置计数约束来验证新的子实体?

如何解决如何使用 OneToMany 关系上的内置计数约束来验证新的子实体?

父实体与子实体之间存在一对多关系,如下所示:

/**
 * @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 举报,一经查实,本站将立刻删除。