วิธีรับวัตถุผู้ใช้ภายใน Repository ของแบบฟอร์มใน Symfony 2.8.1

ฉันกำลังพัฒนาเว็บแอปบน Symfony ฉันมี 2 เอนทิตีที่มีคำถามเกี่ยวกับ "Line" และ "Dosier" ดังนั้น 1 โดซิเยร์สามารถมีได้หลายบรรทัด ตอนนี้ฉันกำลังใช้ CRUD สำหรับเอนทิตี Line ดังนั้นเอนทิตี Line จึงมี "ดรอปดาวน์" พร้อม Dosiers ทั้งหมดจาก DataBase ปัญหาคือว่าในดรอปดาวน์คือเอกสารทั้งหมดจากผู้ใช้ใด ๆ แต่ฉันต้องการให้มีตัวเลือกที่มี 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

My LineType (ตัวสร้างแบบฟอร์ม)

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';
    }


}

My 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'); 
    }
}

ฉันจะรับผู้ใช้ปัจจุบันหรืออย่างน้อยรหัสผู้ใช้ปัจจุบันเพื่อสร้างแบบสอบถามเช่น ... เลือกจาก Dosier โดยที่ dosier.user_id = $???


person new_newB1e    schedule 30.10.2017    source แหล่งที่มา


คำตอบ (1)


ในคอนโทรลเลอร์ที่คุณกำลังสร้างแบบฟอร์มคุณต้องส่งวัตถุผู้ใช้ไปยังประเภทแบบฟอร์มของคุณ

$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'); 
    }
}
person M Khalid Junaid    schedule 30.10.2017
comment
ขอบคุณสำหรับคำตอบของคุณ ทุกอย่างดูดี ยกเว้นข้อผิดพลาดนั้น: ตัวโหลดอัตโนมัติคาดว่าคลาส AppBundle\Form\LineType ที่จะกำหนดในไฟล์ /home/computer/project/src/AppBundle/Form/LineType.php พบไฟล์แต่ไม่มีคลาสอยู่ในนั้น ชื่อคลาสหรือเนมสเปซอาจมีการพิมพ์ผิด ถ้าฉันใส่ LineRepository หรือ DosierRepository ลงในโฟลเดอร์ Form มันทำให้ฉันมีข้อผิดพลาดเดียวกันหรือถ้าฉันเปลี่ยนที่อยู่ไดเรกทอรีใน entert/Loan.php ... เหมือนกัน - person new_newB1e; 31.10.2017
comment
@ new_newB1e อาจมีบางอย่างผิดปกติกับเนมสเปซหรือชื่อคลาสของคุณ โปรดดูที่ stackoverflow.com/questions/19080796/ และอันที่คล้ายกันโดย google - person M Khalid Junaid; 31.10.2017
comment
โอ้ ฉันขอโทษ ฉันเพิ่งสังเกตว่าในหลายไฟล์นี้... LineType.php ของฉันไม่มีคำสั่งเนมสเปซ ทุกอย่างทำงานได้ดี ขอบคุณสำหรับความช่วยเหลือของคุณ! - person new_newB1e; 31.10.2017