Reputation: 1536
I have a Booking form which I want to book a car, I want when sending the form value create a new Booking object and persist it in the db, car and Booking are related with OneToMany relationship.
Booking controller
/**
* @param Request $request
* @return Response
* @Route ("/booking/car/{id}", name="car.book")
*/
public function book(Request $request)
{
$booked_car = $request->query->get('id');
$booking = new Booking();
$booking->setCar($booked_car);
$form = $this->createForm(BookingType::class, $booking);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()){
$booking = $form->getData();
$this->em->persist($booking);
$this->em->flush();
$this->addFlash('success', 'Démande envoyée avec success');
return $this->redirectToRoute('car.index');
}
return $this->render('booking/book.html.twig',[
'booking' => $booking,
'form' => $form->createView()
]);
}
index where I list cars / only the button
<div class="col-2">
<a class="btn btn-dark mt-2 mb-2" style="border-radius: 0 !important;" href="{{ path('car.book', {id: car.id, car: car}) }}"> Réserver </a>
</div>
form.html.twig
<h3 class="mt-5 mb-5">Vos informations</h3>
<div class="row d-flex" >
<div class="col-6">
<div class="row d-flex">
<div class="col-4">
{{ form_row(form.driving_license_number) }}
</div>
<div class="col-4">
{{ form_row(form.national_id_card) }}
</div>
<div class="col-4">
{{ form_row(form.passeport_number) }}
</div>
</div>
</div>
</div>
{{ form_widget(form) }}
{{ form_end(form) }}
the id param is always give null, how to get it from request and search for the corresponding object car with id to set it into Booking object ?
Upvotes: 1
Views: 581
Reputation: 8161
You are using $booked_car = $request->query->get('id');
to retrieve the parameter in the url, but query
refers to query string parameters, which there are none. In that situation you want to use route attributes
: $request->attributes->get('id');
Even better, if your controller action has a variable named after the parameter, symfony will automatically bind it.
public function book(Request $request, $id)
When you are calling setCar
, you likely need the entity itself and not just the id, so you'll have to load it from the database. Symfony can also load it for you if you hint the variable with the correct entity as noted in the previous answer (because the parameter is called id
, it'll try to load it by primary key).
Upvotes: 1
Reputation: 11
your need to get the id from the annotation not from request.
Something Like this :
public function book(Request $request,CarEntityName $carEntityName)
{
$booked_car = $carEntityName;
//....
}
hope this can help.
Upvotes: 1