Symfony 5:如何使用 OneToMany 关系向会话中经过身份验证的用户添加数据?

Symfony 5 : how to add data to a user authenticated in a session, using OneToMany relation?

我想通过 title 字段向策略 table 添加数据,并将其关联到在 会话中通过身份验证的用户user_id外键。

下面的代码通过 select 选项 (choice_label) 将数据添加到关系有效的策略 table在我的 FormType 文件中,列出我视图中的所有用户。

我想将 select 选项 替换为在会话中对用户进行身份验证的代码。

我查看了文档的 Security and Session 部分,但无法正常工作。

我的 table :Database

我的控制器文件:

public function create(Strategy $strategy = null, Request $request, EntityManagerInterface $em)
{
    $strategy = new Strategy();
    
    $form = $this->createForm(StrategyType::class, $strategy);
    $form->handleRequest($request);

    if($form->isSubmitted() && $form->isValid()){
        $em->persist($strategy);
        $em->flush();
        return $this->redirectToRoute("frStrategy");
    }

    return $this->render('strategy/updateStrategy.html.twig', [
        "strategy" => $strategy,
        "form" => $form->createView()
    ]);

我的 FormType 文件:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('title')
        ->add('user', EntityType::class,[
            'class' => User::class,
            'choice_label' => 'username'
        ])
    ;
}

要么将当前用户传递给表单选项,要么在表单中注入安全组件并从那里使用它。如果您知道其中始终只有一个选项,我认为添加 select 有点奇怪,但这是另一个主题。

private $security;

public function __construct(Security $security)
{
    $this->security = $security
}    

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('title')
        ->add('user', EntityType::class,[
            'class' => User::class,
            'choice_label' => 'username',
            'choices' => [$this->security->getUser()],
        ])
    ;
}