Symfony 4 Форма сбора - PullRequest
       8

Symfony 4 Форма сбора

1 голос
/ 14 марта 2020

Я застрял в этом на несколько часов :( Во-первых, я хочу достичь этой формы:

Форма Exemple

Итак, сначала я начал делать Patient и TourismeRegion объекта С отношением ManyToOne это означает: пациент может иметь только 1 tourismeRegion, а TourismeRegion может иметь несколько пациентов

<?php



 namespace App\Entity;

    use Doctrine\Common\Collections\ArrayCollection;
    use Doctrine\Common\Collections\Collection;
    use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="App\Repository\PatientInformationsRepository")
 */
class PatientInformations
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $Name;

    /**
     * @ORM\Column(type="integer", nullable=true)
     */
    private $Age;

    /**
     * @ORM\Column(type="string", length=50, nullable=true)
     */
    private $Sexe;



    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Housing", inversedBy="patient")
     */
    private $housing;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Specialisation", inversedBy="patient")
     */
    private $specialisation;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\TourismeRegion", inversedBy="patient")
     */
    private $tourismeRegion;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $country;

    /**
     * @ORM\Column(type="integer")
     */
    private $phone;

    /**
     * @ORM\Column(type="string", length=50)
     */
    private $email;

    /**
     * @ORM\Column(type="text")
     */
    private $demande;




    public function getId(): ?int
    {
        return $this->id;
    }

    public function getName(): ?string
    {
        return $this->Name;
    }

    public function setName(string $Name): self
    {
        $this->Name = $Name;

        return $this;
    }

    public function getAge(): ?int
    {
        return $this->Age;
    }

    public function setAge(int $Age): self
    {
        $this->Age = $Age;

        return $this;
    }

    public function getSexe(): ?string
    {
        return $this->Sexe;
    }

    public function setSexe(string $Sexe): self
    {
        $this->Sexe = $Sexe;

        return $this;
    }

    public function getTourismRegion(): ?TourismRegion
    {
        return $this->tourismRegion;
    }

    public function setTourismRegion(?TourismRegion $tourismRegion): self
    {
        $this->tourismRegion = $tourismRegion;

        return $this;
    }

    public function getHousing(): ?Housing
    {
        return $this->housing;
    }

    public function setHousing(?Housing $housing): self
    {
        $this->housing = $housing;

        return $this;
    }

    public function getSpecialisation(): ?Specialisation
    {
        return $this->specialisation;
    }

    public function setSpecialisation(?Specialisation $specialisation): self
    {
        $this->specialisation = $specialisation;

        return $this;
    }

    public function getTourismeRegion(): ?TourismeRegion
    {
        return $this->tourismeRegion;
    }

    public function setTourismeRegion(?TourismeRegion $tourismeRegion): self
    {
        $this->tourismeRegion = $tourismeRegion;

        return $this;
    }

    public function getCountry(): ?string
    {
        return $this->country;
    }

    public function setCountry(string $country): self
    {
        $this->country = $country;

        return $this;
    }

    public function getPhone(): ?int
    {
        return $this->phone;
    }

    public function setPhone(int $phone): self
    {
        $this->phone = $phone;

        return $this;
    }

    public function getEmail(): ?string
    {
        return $this->email;
    }

    public function setEmail(string $email): self
    {
        $this->email = $email;

        return $this;
    }

    public function getDemande(): ?string
    {
        return $this->demande;
    }

    public function setDemande(string $demande): self
    {
        $this->demande = $demande;

        return $this;
    }



}


**Tourism Region entity**

<?php

namespace App\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="App\Repository\TourismeRegionRepository")
 */
class TourismeRegion
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="date")
     */
    private $Arrival_date;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $estimate_period;



    /**
     * @ORM\Column(type="string", length=255)
     */
    private $Guide;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $Car;

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\PatientInformations", mappedBy="tourismeRegion")
     */
    private $patient;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\MedicalCity", inversedBy="Region")
     */
    private $medicalCity;

    public function __construct()
    {
        $this->patient = new ArrayCollection();
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getArrivalDate(): ?\DateTimeInterface
    {
        return $this->Arrival_date;
    }

    public function setArrivalDate(\DateTimeInterface $Arrival_date): self
    {
        $this->Arrival_date = $Arrival_date;

        return $this;
    }

    public function getEstimatePeriod(): ?string
    {
        return $this->estimate_period;
    }

    public function setEstimatePeriod(string $estimate_period): self
    {
        $this->estimate_period = $estimate_period;

        return $this;
    }



    public function getGuide(): ?string
    {
        return $this->Guide;
    }

    public function setGuide(string $Guide): self
    {
        $this->Guide = $Guide;

        return $this;
    }

    public function getCar(): ?string
    {
        return $this->Car;
    }

    public function setCar(string $Car): self
    {
        $this->Car = $Car;

        return $this;
    }

    /**
     * @return Collection|PatientInformations[]
     */
    public function getPatient(): Collection
    {
        return $this->patient;
    }

    public function addPatient(PatientInformations $patient): self
    {
        if (!$this->patient->contains($patient)) {
            $this->patient[] = $patient;
            $patient->setTourismeRegion($this);
        }

        return $this;
    }

    public function removePatient(PatientInformations $patient): self
    {
        if ($this->patient->contains($patient)) {
            $this->patient->removeElement($patient);
            // set the owning side to null (unless already changed)
            if ($patient->getTourismeRegion() === $this) {
                $patient->setTourismeRegion(null);
            }
        }

        return $this;
    }

    public function getMedicalCity(): ?MedicalCity
    {
        return $this->medicalCity;
    }

    public function setMedicalCity(?MedicalCity $medicalCity): self
    {
        $this->medicalCity = $medicalCity;

        return $this;
    }
}

После этого я сделал форму туристического региона:

<?php

namespace App\Form;

use App\Entity\TourismeRegion;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\NumberType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class RegiontourismType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('Arrival_date',DateType::class)
            ->add('estimate_period',TextType::class,[
                'choices'  => [
                    'Non prévue'=>'Non prévue',
                    '1 semaine'=>'1 semaine' ,
                    '2 semaine'=>'2 semaine',
                    '3 semaine'=>'3 semaine',
                    '1 Mois'=>'1 Mois',
                    'Plus de 1 mois '=>'Plus de 1 mois',
                ],
            ])
            ->add('Guide',TextType::class,[
                'choices'  => [
                    'Oui'=>'Oui' ,
                    'Non'=>'Non',

                ],
            ])
            ->add('Car',TextType::class,[
                'choices'  => [
                    'Sans Voiture'=>'Sans Voiture',
                    'Avec Voiture'=>'Avec Voiture' ,
                    'Voiture Avec Chauffeur'=>'Voiture Avec Chauffeur',
                ],
            ])
            ->add('medicalCity',TextType::class)
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => TourismeRegion::class,
        ]);
    }
}


**Then I made the Patient form :**

<?php

namespace App\Form;

use App\Entity\PatientInformations;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\Extension\Core\Type\NumberType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class PatientInfo2Type extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('Age',NumberType::class)
            ->add('Sexe',ChoiceType::class,[
                'choices'  => [
                    'Women'=>'Women',
                    'Men'=>'Men' ,
                    'Other'=>'Other',
                ],
            ])
            ->add('tourismeRegion',CollectionType::class,[
                'entry_type' => RegiontourismType::class,
                'entry_options' => ['label' => false],
                'prototype' => true


            ])
            ->add('housing')
            ->add('specialisation')
            ->add('Save',SubmitType::class,[
                'attr' => [
                    'class' => 'btn-success'
                ]
            ])

        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => PatientInformations::class,
        ]);
    }
}

Я наконец-то создал контроллер и веточку и следовал документации по форме сбора symfony, но она не работает :(

Контроллер

<?php

namespace App\Controller;

use App\Entity\PatientInformations;
use App\Entity\Test;
use App\Entity\TourismeRegion;
use App\Form\PatientInfo2Type;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;

class PatientInfoController extends AbstractController
{
    /**
     * @Route("/patient/info", name="patient_info")
     */
    public function index(Request $request)
    {   $patient= new PatientInformations();

        $region= new TourismeRegion();
        $region->setArrivalDate(new \DateTime());
        $region->setGuide("Non");
        $region->setEstimatePeriod("2 semaine");
        $region->setCar("Sans Voiture");




        $form = $this->createForm(PatientInfo2Type::class,$patient);

        $form->handleRequest($request);
        $patient->setTourismeRegion($region);


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


**TWIG**

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

{% block title %}Request{% endblock %}

{% block body %}

    <div class="container">
        <h1>Informations Patient</h1>
        {{ form_start(PatientInfo) }}
        {# iterate over each existing tag and render its only field: name #}
                {{ dump(PatientInfo) }}
        <div>
            {% for row in PatientInfo.tourismeRegion %}
               {{ form_row(row.estimate_period) }}
            {% endfor %}
                </div>


        {{ form_end(PatientInfo) }}
    </div>


{% endblock %}

Я только что сделал только пациента и область туризма, потому что хочу посмотреть, сработает ли я, я заставлю остальных делать то же самое, я думаю, что у меня есть проблема в части Контролера, помогите, пожалуйста, я застрял в течение нескольких часов.

...