首页 > 解决方案 > Symfony 4以表单类型获取当前用户?

问题描述

我想知道如何在我的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,
    ]);
}

谢谢您的帮助 !

标签: phpsymfonysymfony4

解决方案


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

private $security;

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

推荐阅读