Skip to content

Form data

Samvdg edited this page Sep 3, 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: src/controller/StudentController.php


   /**
     * @Route("/new", name="student_new", methods={"GET","POST"})
     * Bij deze functie voor het nieuw aanmaken van een student wordt eerst nagelopen of het teacher is gesloten doormiddel van de 
     * gesubmitte data langs te lopen, daarnaast checkt hij ook of na het aanmaken van de student deze het max aantal studenten heeft bereikt
     *
     *
     * Vergeet niet StudentRepository met hoofdletter A neer te zetten, de variable is kleine letter
     */
    public function new(StudentRepository $studentRepository, TeacherRepository $TeacherRepository, Request $request): Response
    {
        $student= new Student();
        $form = $this->createForm(StudentType::class, $student); // Hier moet student ook met hoofdletter van Type
        $form->handleRequest($request);
        $em = $this->getDoctrine()->getManager();
        
        // als het form goed is
        if ($form->isSubmitted() && $form->isValid()) {
            // haal het id op van het gegeven teacher
            $teacher = $form->getData()->getTeacher(); //hoofdletter T
            $count = 0;
            //                         hoofdletter A hierzo
            $counts = $em->getRepository('App:Student')->findBy(['student' => $teacher->getId()]);
            // dd(count($count));
            foreach($counts as $student)
            {
                $count++;
            }
            // dd($count);
            if($gesloten == 1 || $count >= $teacher->getMaxPlayers())
            {
                return $this->render('student/index.html.twig',[
                    'students' => $studentRepository->findAll(),
                    'status' => '404',
                ]);
            }
            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->persist($student);
            $entityManager->flush();

            //                         hoofdletter A hierzo
            $counts = $em->getRepository('App:Student')->findBy(['teacher' => $teacher->getId()]);
            $count = 0;
            foreach($counts as $student)
            {
                $count++;
            }
            if($count = $teacher->getMaxPlayers()){
                return $this->render('student/index.html.twig',[
                    'students' => $studentRepository->findAll(),
                    'status' => '405',
                ]);
            }


            return $this->redirectToRoute('aanmelding_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 given 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! t=t a=s

Don't forget to catch the error messages in the corresponding templates/entity/index.html.twig file In this case that would be templates/student/index.html:

{% extends 'base.html.twig' %}

{% block title %}Student index{% endblock %}

{% block body %}
    <h1>Student index</h1>

{% if status == 404 %}
<script> alert('Dit Teacher is gesloten. Studenten kunnen niet meer gedaan worden') </script>
{% endif %}
{% if status == 405 %}
<script> alert('Dit Teacher is gesloten. Maximaal aantal Studenten bereikt') </script>
{% endif %}

Oh seems like we forgot to add a status to the standard index function. Since we try to load the property 'status' it has to be passed along at all times. If you head to the corresponding controller, in this case 'src/Controller/studentController.pphp', you'll find the '/index' function at the top

    /**
     * @Route("/", name="student_index", methods={"GET"})
     * de benaming voor de variable tussen de '()' moet met een hoofdletter!
     */
    public function index(StudentRepository $studentRepository): Response
    {
        return $this->render('student/index.html.twig', [
            'students' => $studentRepository->findAll(),
        ]);
    }

Now just add 'status => '200' underneath the 'students' property as follows:

    /**
     * @Route("/", name="student_index", methods={"GET"})
     * de benaming voor de variable tussen de '()' moet met een hoofdletter!
     */
    public function index(StudentRepository $studentRepository): Response
    {
        return $this->render('student/index.html.twig', [
            'students' => $studentRepository->findAll(),
            'status'=> '200',
        ]);
    }

Zet de volgende code in een .htaccess bestand om de applicatie in productie stand te zetten.

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ public/$1 [QSA,L]
</IfModule>

En vergeet niet bij de .env map dev te veranderen in prod. Zet de volgende code in je terminal.

APP_ENV=prod APP_DEBUG=0 php bin/console cache:clear

Met deze code kan je de roles verdelen tussen user en admin.

{% if is_granted('ROLE_SUPER_ADMIN') %}
{% endif %}

Met de volgende code kan je bepaalde data uit een database halen door middel van een klein formuliertje. Hieronder zie je de functie die je in de controller moet zetten.

/**
* @Route("/Checkin_date", name="Checkin_date", methods={"POST"})
*/
public function date(Request $request, ReserveringRepository $reserveringRepository): Response {
    if ($this->isGranted('ROLE_ADMIN')) {
        $datum = $request->request->get('Checkin_date');
        // dd($request);
        return $this->render('reservering/index.html.twig', [
            'reserverings' => $reserveringRepository->findBy(['Checkin_date' => new \DateTime($datum)]),
        ]);
    } else {
        $datum = "Niet beschikbaar!";
        return $this->render('reservering/index.html.twig', [
            'reserverings' => $reserveringRepository->findAll(),
            'error' => $datum,
        ]);
    } 
} 

Hieronder zie je het formuliertje die hier bij hoort.

{% if error is defined %}
<script>alert("{{error}}")</script>
{% else %}
<form action="{{path('Checkin_date')}}"method="post">
        <input type="date" name="Checkin_date">
        <input type="submit">
</form>
{% endif %}

Hier vind je de code die ervoor zorgt dat je maar vanaf 1 bepaalde datum kan selecteren. Dit zet je in de form.php van de pagina waar je het wilt hebben.

<?php

namespace App\Form;

use App\Entity\Reservering;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\DateTimeType;

class ReserveringType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('checkinDate', DateTimeType::class,['data'   => new \DateTime(),
                'attr' => ['min' => ( new \DateTime() )->format('Y-m-d')]
            ])

            ->add('checkoutDate', DateTimeType::class,['data'   => new \DateTime(),
                'attr' => ['min' => ( new \DateTime() )->format('Y-m-d')]
            ])
            ->add('reknr')
            ->add('betaaldatum', DateTimeType::class, array(
                'widget' => 'single_text',
            ))
            ->add('Betaalmethode')
            ->add('opmerking')
            ->add('kamer')
        ;
    }
}

Zet de volgende code in je user index van user.controller en verwijder de code die erin stond.

public function index(): Response
    {
            if ($this->isGranted('ROLE_ADMIN')) {
                $users = $this->getDoctrine()
                    ->getRepository(User::class)
                    ->findAll();
                return $this->render('user/index.html.twig', [
                    'users' => $users,
                ]);
            } else {
                return $this->redirectToRoute('user_show', [
                    'id' => $this->getUser()->getId()
                ]);
            }
    }

De volgende code moet je in je terminal zetten hierdoor kan je je registratie pagina en inlog pagina vinden en in je navigatie zetten.

php bin/console debug:router

Dit is datum between checkin_date en checkout_date. En daaronder staat wat je moet aanpassen aan de functie in je controller.

->andWhere('r.Checkin_date <= :val AND  r.Checkout_date >= :val')

return $this->render('reservering/index.html.twig', [
            'reserverings' => $reserveringRepository->findByExampleField($datum)

Hieronder zie je de querybuilder

public function findByExampleField($value)
    {
        return $this->createQueryBuilder('r')
            ->andWhere('r.Checkin_date = :val')
            ->setParameter('val', $value)
            ->orderBy('r.Checkin_date', 'ASC')
            ->setMaxResults(10)
            ->getQuery()
            ->getResult()
        ;
}

Clone this wiki locally