首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

表单不在Symfony 4中呈现OneToMany关系的字段

在Symfony 4中,表单不直接呈现OneToMany关系的字段。OneToMany关系是指一个实体对象拥有多个关联的实体对象。在Symfony中,OneToMany关系通常通过CollectionType表单字段来表示。

CollectionType字段允许用户动态添加、删除和编辑关联实体对象。它通常与EntityType字段结合使用,用于选择关联实体对象。

要在Symfony 4中呈现OneToMany关系的字段,可以按照以下步骤进行操作:

  1. 在实体类中定义OneToMany关系。例如,假设有一个User实体类和一个Comment实体类,一个User可以拥有多个Comment:
代码语言:txt
复制
// src/Entity/User.php

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;

class User
{
    // ...

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\Comment", mappedBy="user")
     */
    private $comments;

    public function __construct()
    {
        $this->comments = new ArrayCollection();
    }

    // ...
}
  1. 创建一个表单类来表示User实体类。在表单类中,使用CollectionType字段来表示OneToMany关系的字段:
代码语言:txt
复制
// src/Form/UserType.php

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\FormBuilderInterface;

class UserType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            // ...

            ->add('comments', CollectionType::class, [
                'entry_type' => CommentType::class,
                'allow_add' => true,
                'allow_delete' => true,
                'by_reference' => false,
            ])
        ;
    }

    // ...
}

在上面的代码中,'entry_type'参数指定了关联实体对象的表单类型(例如CommentType),'allow_add'参数允许用户动态添加关联实体对象,'allow_delete'参数允许用户删除关联实体对象,'by_reference'参数设置为false,确保关联实体对象的变化能够正确保存到数据库中。

  1. 在控制器中使用表单类来处理表单数据:
代码语言:txt
复制
// src/Controller/UserController.php

use App\Entity\User;
use App\Form\UserType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

class UserController extends AbstractController
{
    /**
     * @Route("/user/new", name="user_new", methods={"GET", "POST"})
     */
    public function new(Request $request): Response
    {
        $user = new User();
        $form = $this->createForm(UserType::class, $user);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            // 保存用户和关联的评论到数据库中
            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->persist($user);
            $entityManager->flush();

            return $this->redirectToRoute('user_show', ['id' => $user->getId()]);
        }

        return $this->render('user/new.html.twig', [
            'form' => $form->createView(),
        ]);
    }

    // ...
}

在上面的代码中,'new'方法用于处理创建新用户的表单提交。首先创建一个User实体对象,然后使用UserType表单类创建表单对象。通过调用handleRequest方法处理表单数据,如果表单数据有效,则将用户和关联的评论保存到数据库中。

这样,就可以在Symfony 4中呈现OneToMany关系的字段。对于更多关于Symfony表单的信息,可以参考Symfony官方文档:Symfony Forms

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的视频

领券