如何在 Symfony 2.8 中获取表单存储库中的用户对象

How to get user object inside form Repository in Symfony 2.8

我正在 Symfony 上开发网络应用程序。我有 2 个实体存在问题,"Line" 和 "Dosier"。因此,1 个 dosier 可以有很多行。 现在我正在为 Line 实体实现 CRUD,因此 Line 实体有一个 "dropdown",其中包含来自数据库的所有 Dosiers。 问题是在下拉列表中是来自任何用户的所有文件,但我需要在这个下拉列表中只有 user_id = currentUser_id.

的选项

所以,我的控制器动作:

/**
 * @Route("/add-line", name="addLine")
 */
public function createLineAction(Request $request)
{
  $em = $this->getDoctrine()->getManager();
  $user = $this->getUser();
  $line = new Line();
  $form = $this->createForm(LineType::class, $line);

  $form->handleRequest($request);

  if($form->isSubmitted() && $form->isValid()){
      $em->persist($line);
      $em->flush();

   return $this->redirectToRoute('homepage');
  }

  return $this->render('AppBundle:default:formLines.html.twig', array(
      'form' => $form->createView(),
  ));
}//create dossier action

我的线型(表单生成器)

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;

class LineType extends AbstractType
{


    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name')->add('dosier')
            ->add('dosier', EntityType::class, array(
                'class' => 'AppBundle:Dosier',
                'query_builder' => function($repo) {
                    return $repo->dosiersOfCurrentUser();
                },  
                'choice_label' => 'name',
                ))
            ->add('save', SubmitType::class, array(
                'label' => 'Save',
                 'attr'=> array('class'=>'btn btn-success submitButton') 
                 )
            );

    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\Line'
        ));
    }

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


}

我的Line.php(实体)

<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
 * Line
 *
 * @ORM\Table(name="line")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\LineRepository")
 */
class Line
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\ManyToOne(targetEntity="Dosier", inversedBy="lines")
     * @ORM\JoinColumn(name="dosier_id", referencedColumnName="id")
     */
    private $dosier;


    /**
     * @ORM\OneToMany(targetEntity="Loan", mappedBy="line")
     */
    private $loans;


    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=255)
     */
    private $name;


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


    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     *
     * @return Line
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Add loan
     *
     * @param \AppBundle\Entity\Loan $loan
     *
     * @return Line
     */
    public function addLoan(\AppBundle\Entity\Loan $loan)
    {
        $this->loans[] = $loan;

        return $this;
    }

    /**
     * Remove loan
     *
     * @param \AppBundle\Entity\Loan $loan
     */
    public function removeLoan(\AppBundle\Entity\Loan $loan)
    {
        $this->loans->removeElement($loan);
    }

    /**
     * Get loans
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getLoans()
    {
        return $this->loans;
    }

    /**
     * Set dosier
     *
     * @param \AppBundle\Entity\Dosier $dosier
     *
     * @return Line
     */
    public function setDosier(\AppBundle\Entity\Dosier $dosier = null)
    {
        $this->dosier = $dosier;

        return $this;
    }

    /**
     * Get dosier
     *
     * @return \AppBundle\Entity\Dosier
     */
    public function getDosier()
    {
        return $this->dosier;
    }
}

和我的存储库:DosierRepository.php

<?php

namespace AppBundle\Repository;


use Doctrine\ORM\EntityRepository;

class DosierRepository extends \Doctrine\ORM\EntityRepository
{
    public function dosiersOfCurrentUser() {
        return $this->createQueryBuilder('dosier')
            ->where('dosier.userId = 1 ')
            ->orderBy('dosier.name', 'DESC'); 
    }
}

如何获取当前用户,或者至少是当前用户 ID,以进行类似... select 来自 Dosier 的查询,其中 dosier.user_id = $???

在您构建表单的控制器中,您需要将用户对象传递给您的表单类型

$tokenStorage = $this->get('security.token_storage');
$form = $this->createForm(new LineType($tokenStorage), $line);
//... other stuff

现在在您的表单中输入接收此 tokenStorage 对象并检索用户对象并传递给您的 repo 函数

use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
//.. other use statements

class LineType extends AbstractType
{

    private $user;

    public function __construct(TokenStorageInterface $tokenStorage)
    {
        $this->user = $tokenStorage->getToken()->getUser();
    }
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $userId = $this->user->getId();
        $builder
            ->add('name')->add('dosier')
            ->add('dosier', EntityType::class, array(
                'class' => 'AppBundle:Dosier',
                'query_builder' => function($repo) use($userId) {
                    return $repo->dosiersOfCurrentUser($userId);
                },  
                'choice_label' => 'name',
                ))
            ->add('save', SubmitType::class, array(
                'label' => 'Save',
                 'attr'=> array('class'=>'btn btn-success submitButton') 
                 )
            );

    }
}

在 repo 中应用你的过滤器

class DosierRepository extends \Doctrine\ORM\EntityRepository
{
    public function dosiersOfCurrentUser($userId) {
        return $this->createQueryBuilder('dosier')
            ->where('dosier.userId = :userId ')
            ->setParameter('userId',$userId)
            ->orderBy('dosier.name', 'DESC'); 
    }
}