Search code examples
formsentitysymfony4sql-null

Form submission : value is set on null


I am making an ad platform, I have just created a Booking entity and its form, but after that the form has been submitted, the value 'amount' is set on null while it should not be null.

I have created a prePersist function to set the amount property before flushing.

Here is the prePersist function in my entity Booking

     * @ORM\PrePersist
     * 
     * @return void
     */
    public function prePersist()
     {
         if(empty($this->createdAt))
         {
             $this->createdAt = new \DateTime();

         }

         if(empty($this->amount))
         {
            $this->amount = $this->ad->getPrice() * $this->getDuration();
         }
     }

public function getDuration()
     {
        $diff = $this->endDate->diff($this->startDate);
        return $this->days;
     }

My BookingController

    /**
     * @Route("/annonces/{id}/booking", name="ad_booking")
     * @IsGranted("ROLE_USER")
     */
    public function booking(Ad $ad, Request $request, ObjectManager $manager)
    {
        $booking = new Booking;        

        $form = $this->createForm(BookingType::class, $booking);

        $user = $this->getUser();

        $booking->setBooker($user) 
                        ->setAd($ad);

        $form->handleRequest($request);

        if($form->isSubmitted() && $form->isValid())
        {

            $manager->persist($booking);

            $manager->flush();

            return $this->redirectToRoute('booking_success', [
                'id' => $booking->getId() 
            ]);
        }

        return $this->render('booking/booking.html.twig', [
            'ad' => $ad,
            'bookingForm' => $form->createView()
        ]);
    }
}

It does not work when the user is defined with $this->getUser(); in the submission and validity check. That's the first time it happens since I've started learning Symfony. I am sure I must have forgotten something but I spent so much time on thinking about what, that I can't see the answer.

and my BookingType form

public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('startDate', DateType::class, [
                'label' => 'Date de début de prestatation',
                'widget' => 'single_text'
            ])
            ->add('endDate', DateType::class, [
                'label' => 'Date de fin de prestatation',
                'widget' => 'single_text'

            ])
        ;
    }

While the form is submitted, it should call the prePersist function and then set the amount property, but it returns to be null. I really don't understand what I missed.


Solution

  • I just found out that was wrong. It was linked to the automatic validation : in the validator.yaml I commented the auto_mapping with

                App\Entity\Booking: true
                App\Entity\User: true
    

    Now everything works fine !