Home > Mobile >  how to get the id of the current user in symfony?
how to get the id of the current user in symfony?

Time:04-18

i try to get the userId and the event ID to insert into ReservatonEvenement table in database but it give me an error of :Argument #1 ($ID_user) must be of type ?App\Entity\User, int given. and when i do vardump ($this->getUser()->getId() ) i got the id of user but with an int() like int(2)

----------------------------ReservationEvenementController----------------------- /** * @param Request $request * @return Response * @Route("/n/d", name="app_res") */ public function Reserver(Request $request): Response {

    $user = new User();
    $evenement= new Evenement();
    $reservationEvenement = new ReservationEvenement();
    $id = $this->getUser()->getId();
    var_dump(  $id);
    var_dump($user->getId());
    
    $reservationEvenement->setIDUser($id);

    $em= $this->getDoctrine()->getManager();
    $em->persist($reservationEvenement);
    $em->flush();`enter code here`

    return new Response('Event Add it Succusfully ');
}

this the ReservationEvent.php entity

    **
 * @ORM\Entity(repositoryClass=ReservationEvenementRepository::class)
 */
class ReservationEvenement
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\ManyToOne(targetEntity=User::class, inversedBy="reservationEvenements")
     * @ORM\JoinColumn(nullable=false)
     */
    private $ID_user;

    /**
     * @ORM\ManyToOne(targetEntity=Evenement::class, inversedBy="reservationEvenements")
     * @ORM\JoinColumn(nullable=false)
     */
    private $ID_evenement;

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getIDUser(): ?User
    {
        return $this->ID_user;
    }

    public function setIDUser(?User $ID_user): self
    {
        $this->ID_user = $ID_user;

        return $this;
    }

    public function getIDEvenement(): ?Evenement
    {
        return $this->ID_evenement;
    }

    public function setIDEvenement(?Evenement $ID_evenement): self
    {
        $this->ID_evenement = $ID_evenement;

        return $this;
    }
}

and this is the class diagrame

enter image description here

CodePudding user response:

Try this: $reservationEvenement->setIDUser($this->getUser());

Explanation: as stated in the error message, the method setIDUser expect a User object as a parameter, but you are feeding it with an integer.

CodePudding user response:

you can use

$this->get('security.token_storage')->getToken()->getUser()->getId();
  • Related