简体   繁体   中英

I need to keep user's data in form fields after redirection

I'm writing simple carpark application for my assingment and one of the last things that I need to do is to keep user's data in form fields after it gets redirected. The redirection happens when spot that user wants to reserve is already taken.

I found out that you can do it using session but I can't it doesn't work the way I want because I can't retrieve the data.

Here's the method new in my Reservation Controller:

/**
     * New action.
     *
     * @param \Symfony\Component\HttpFoundation\Request $request    HTTP request
     * @param \App\Repository\ReservationRepository     $repository Reservation repository
     *
     * @return \Symfony\Component\HttpFoundation\Response HTTP response
     *
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     *
     * @Route(
     *     "/new",
     *     methods={"GET", "POST"},
     *     name="reservation_new",
     * )
     */
    public function new(Request $request, ReservationRepository $repository): Response
    {
        $reservation = new Reservation();
        $form = $this->createForm(ReservationType::class, $reservation);
        $form->handleRequest($request);


        if ($form->isSubmitted() && $form->isValid()) {
            if ($repository->findOneBy(['spot' => $reservation->getSpot()])) {

//                $occupied_from = $form['occupied_from']->getData();
//                $occupied_to = $form['occupied_to']->getData();
//                $payment = $form['payment']->getData();
//                $spot = $form['spot']->getData();

                dump($request->request->get('reservation'));

//                $occupied_from = $this->session->get('occupied_from', []);
//                $occupied_to = $this->session->get('occupied_to', []);
//                $payment = $this->session->get('payment', []);
//                $spot = $this->session->get('spot', []);

//                if ($reservation->getOccupiedFrom() == )

                $this->addFlash('error', 'message.spot_taken');

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

            $reservation->setClient($this->getUser());
            $repository->save($reservation);


            $this->addFlash('success', 'message.updated_successfully');

            return $this->redirectToRoute('reservation_index');

        }

        if ($form->isSubmitted() && $form->isValid() && $reservation->getOccupiedFrom() < new \DateTime('now') ) {

            $this->addFlash('error', 'message.inconsistent_date');

        }

        if ($form->isSubmitted() && $form->isValid() && $reservation->getOccupiedFrom() > $reservation->getOccupiedTo()) {

            $this->addFlash('error', 'message.inconsistent_date');

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



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

And here's the form for Reservation:

 public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder->add(
            'occupiedFrom',
            DateTimeType::class,
            [
                'widget' => 'choice',
                'label' => 'label.occupied_from',
                'placeholder' => [
                    'year' => 'Year', 'month' => 'Month', 'day' => 'Day',
                    'hour' => 'Hour', 'minute' => 'Minute', 'second' => 'Second',
                ],
                'data' => new\DateTime(),
                'attr' => ['min' => (new DateTime())->format('YYYY-mm-dd HH:ii:ss')]
            ]
        );

        $builder->add(
            'occupiedTo',
            DateTimeType::class,
            [
                'widget' => 'choice',
                'label' => 'label.occupied_to',
                'placeholder' => [
                    'year' => 'Year', 'month' => 'Month', 'day' => 'Day',
                    'hour' => 'Hour', 'minute' => 'Minute', 'second' => 'Second',
                ],
                'data' => new\DateTime(),
                'attr' => ['min' => (new DateTime())->format('YYYY-mm-dd HH:ii:ss')]
            ]
        );

        $builder->add(
            'payment',
            EntityType::class,
            [
                'class' => Payment::class,
                'choice_label' => function ($payment) {
                    return $payment->getType();
                },
                'label' => 'label.payment',
                'placeholder' => 'label.none',
                'required' => true,
            ]
        );

        $builder->add(
            'spot',
            EntityType::class,
            [
                'class' => Spot::class,
                'choice_label' => function($spot) {
                return $spot->getSpot();
                },
                'label' => 'label.spot',
                'placeholder' => 'label.none',
                'required' => true,
            ]
        );

There are 4 values I need to access: 'occupied_from' which is the starting date of the reservation, 'occupied_to' which is the ending date, 'payment' one of two ways of payment for the reservation and 'spot' which is the name of the spot.

Whatever I do, I always get the redirect but data is not saved. Thanks in advance from an unexperienced collegue.

You can send data to the route, like this:

    return $this->redirectToRoute(
        'reservation_new', 
        [
            'occupied_to' => $occupiedTo,
            //etc ...
        ],
        301
    );

//in the other side:
public function reservationNew(string $occupiedTo) // ...

Anyway, you can use the SessionInterface Component, in any Controller or Service, like this:

in controller (like @msg suggest in the comment below):

$session = $this->get('session');

or in a service:

use Symfony\Component\HttpFoundation\Session\SessionInterface;

//...

    public function __construct(SessionInterface $session)
    {
        $this->session = $session;
    }

// ...

        //set:
        $this->session->set('form_data',  [
            'occupied_to' => $occupiedTo,
            //etc ...
        ]);

        //and get:
        $this->session->get('form_data', []); // with the second parameter you can set the default value, if the data doesnt exist in the session...

After that, you can rebuild the form, with optionsResolver, or you know, what you want

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM