Symfony 4 以表单类型获取当前用户?

Symfony 4 get current user in form type?

我想知道如何恢复 FormType (EntityType) 中的当前用户?

目前,我只能检索注册用户列表,不能检索当前(已连接)用户。

我现在的FormType

<?php

namespace App\Form;

use App\Entity\User;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

class OneNewCarType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add(
                'author',
                EntityType::class, [
                    'label' => 'Ville',
                    'class' => User::class,
                    'attr' => [
                        'class' => 'selectpicker'
                    ],
                    'choice_label' => function ($author) {
                        return $author->getCity();
                    }
                ]
            );
    }

    public function getBlockPrefix()
    {
        return 'oneNewCarType';
    }
}

我知道如何直接在我的控制器中恢复它。但是,我不知道如何使用步进包 CraueFormFlowBundle

这是我当前的控制器

/**
 * @Route("/classified/{id}/edit", name="classified_edit")
 * @param CarVehicle $carVehicle
 * @param ObjectManager $manager
 * @param CreateVehicleFlow $createVehicleFlow
 * @return RedirectResponse|Response
 */
public function edit(CarVehicle $carVehicle, ObjectManager $manager, CreateVehicleFlow $createVehicleFlow)
{
    $flow = $createVehicleFlow;
    $flow->bind($carVehicle);

    $form = $flow->createForm();
    if ($flow->isValid($form)) {
        $flow->saveCurrentStepData($form);
        if ($flow->nextStep()) {
            $form = $flow->createForm();
        } else {
            $manager->persist($carVehicle);
            $manager->flush();

            $flow->reset();

            $this->addFlash(
                'success',
                "Votre annonce <i>{$carVehicle->getId()}</i> a bien été mise à jour"
            );

            return $this->redirect($this->generateUrl('account_index'));
        }
    }

    return $this->render('front/classified/edit_vehicle.html.twig', [
        'form' => $form->createView(),
        'flow' => $flow,
        'carVehicle' => $carVehicle,
    ]);
}

感谢您的帮助!

使用 Symfony\Component\Security\Core\Security,您可以将用户带到您想要的地方。将其注入 FormType 并使用 $user = $this->security->getUser();

private $security;

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

在 Symfony 5 中,使用

Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface

你可以在你想要的地方获得用户。将其注入 FormType 并使用

$user = $this->token->getToken()->getUser();

private $token;

public function __construct(TokenStorageInterface $token)
{
   $this->token = $token;
}