Skip to content

Form data

Samvdg edited this page Jan 28, 2020 · 20 revisions

How to manipulate form data

First things first

First thing to check if we're manipulating form data is to decide where in the sequence to manipulate said data. For now we can do it after the submission. i'll take the create function from the symfony crud as an examnple.

Lets take a look at the following example of students and teachers:

public function new(StudentRepository $StudentRepository, TeacherRepository $TeacherRepository, Request $request): Response { $student= new Student(); $form = $this->createForm(StudentType::class, $Student); $form->handleRequest($request);

    `if ($form->isSubmitted() && $form->isValid()) {`
        `$gesloten = $form->getData()->getTeacher()->getGesloten();`
        `// die($gesloten);`
        `if($gesloten == 1)`
        `{`
            `return $this->render('student/index.html.twig',[`
                `'students' => $studentRepository->findAll(),`
                `'status' => '404',`
            `]);`
        `}`
        `$entityManager = $this->getDoctrine()->getManager();`
        `$entityManager->persist($aanmelding);`
        `$entityManager->flush();`

        `return $this->redirectToRoute('student_index');`
    `}`

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

its pretty basic but looks complicated. The first thing we check is the data iven to us by the form. We collect that as soon as it's submitted, thats why it's in the 'if' statement. if ($form->isSubmitted() && $form->isValid()) { $gesloten = $form->getData()->getTeacher()->getGesloten(); after that... we have the data! You can do with it whatever you would like. In the example it will have conditional rendering as you can see with another 'if' statement. if($gesloten == 1) But that doesn't always have to be the case ofcourse!

You can also do different things with the form data. Here in the example i just got some data of one of the 2 objects that got sent in the form.

Clone this wiki locally