skip to Main Content

1.Form(StudentRegistrationType.php)

<?php

namespace AppForm;

use SymfonyComponentFormAbstractType;
use SymfonyComponentFormExtensionCoreTypeCheckboxType;
use SymfonyComponentFormExtensionCoreTypeChoiceType;
use SymfonyComponentFormExtensionCoreTypeEmailType;
use SymfonyComponentFormExtensionCoreTypeSubmitType;
use SymfonyComponentFormExtensionCoreTypeRadioType;
use SymfonyComponentFormExtensionCoreTypeTextareaType;
use SymfonyComponentFormFormBuilderInterface;
use SymfonyComponentOptionsResolverOptionsResolver;
use SymfonyComponentFormExtensionCoreTypeTextType;
use SymfonyComponentIntlCountries;

class StudentRegistrationType extends AbstractType

{ 

    public function buildForm(FormBuilderInterface $builder, array $options): void
    { 
       $countries = Countries::getNames();
       $builder
        ->add('first_name', TextType::class)
        ->add("last_name", TextType::class)
        ->add('email', EmailType::class)
        ->add('gender', ChoiceType::class, [
            'choices' => [
               'Male' => 'male',
               'Female' => 'female',
           ],
           //'choice_value' => true,
           'choice_value' => function ($choice) {
               return $choice;
            },
           'multiple'=>false,
           'expanded'=>true
        ])

         ->add('address', TextareaType::class)
         ->add('languages', ChoiceType::class, [
           'choices' => [
              'English' => 'Eng',
              'Hindi' => 'Hin',
              'Japanese' => 'Jap'
            ],
            'multiple'=>true,
            'expanded'=>true
            ])

             ->add('country', ChoiceType::class, [
               'choices' => $countries,
               'choice_label' => function ($choice, $key, $value) {
                  return ucwords($value);
                },


            ])

            ->add('Submit', SubmitType::class)
            ;

    }


     public function configureOptions(OptionsResolver $resolver): void
     {
         $resolver->setDefaults([
            // Configure your form options here
         ]);
    }

}

2.Controller (StudentRegistrationController.php)

<?php

namespace AppController;

use AppEntityStudent;
use AppFormStudentRegistrationType;
use DoctrineORMEntityManager;
use DoctrineORMEntityManagerInterface;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentRoutingAnnotationRoute;
use SymfonyBundleFrameworkBundleControllerAbstractController;

class StudentRegistrationController extends AbstractController
{
    #[Route('/student-registration', name: 'app_student_registration')]
    public function index(Request $request, EntityManagerInterface $entityManager): Response
    {
        $student = new Student;

        $form = $this ->createForm(StudentRegistrationType::class);

        $form->handlerequest($request);

        if($form->isSubmitted()){
            $data = $form->getData();
            $language = $form->get('languages')->getData();
            $student->setLanguagesKnown($language);

            //dd($language);
            dd($data);
            $entityManager->persist($student);
            $entityManager->flush();

            return new Response($student->getId());
        }

        return $this->render('student_registration/index.html.twig', [
            'controller_name' => 'StudentRegistrationController',
            "form"=>$form
        ]);
    }
}

3.Entity (student.php)

<?php

namespace AppEntity;

use AppRepositoryStudentRepository;
use DoctrineDBALTypesTypes;
use DoctrineORMMapping as ORM;

#[ORMEntity(repositoryClass: StudentRepository::class)]
class Student
{
    #[ORMId]
    #[ORMGeneratedValue]
    #[ORMColumn]
    private ?int $id = null;

    #[ORMColumn(length: 40)]
    private ?string $firstName = null;

    #[ORMColumn(length: 40)]
    private ?string $lastName = null;

    #[ORMColumn(length: 100)]
    private ?string $email = null;

    #[ORMColumn(length: 10)]
    private ?string $gender = null;

    #[ORMColumn(type: Types::TEXT)]
    private ?string $address = null;

    #[ORMColumn(type: Types::JSON)]
    private array $languagesKnown = [];

    #[ORMColumn(length: 255)]
    private ?string $country = null;

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

    public function getFirstName(): ?string
    {
        return $this->firstName;
    }

    public function setFirstName(string $firstName): self
    {
        $this->firstName = $firstName;

        return $this;
    }

    public function getLastName(): ?string
    {
        return $this->lastName;
    }

    public function setLastName(string $lastName): self
    {
        $this->lastName = $lastName;

        return $this;
    }

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

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

        return $this;
    }

    public function getGender(): ?string
    {
        return $this->gender;
    }

    public function setGender(string $gender): self
    {
        $this->gender = $gender;

        return $this;
    }

    public function getAddress(): ?string
    {
        return $this->address;
    }

    public function setAddress(string $address): self
    {
        $this->address = $address;

        return $this;
    }

    public function getLanguagesKnown(): array
    {
        return $this->languagesKnown;
    }

    public function setLanguagesKnown(array $languagesKnown): self
    {
        $this->languagesKnown = $languagesKnown;

        return $this;
    }

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

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

        return $this;
    }
}

4.index.html.twig

In this twig file for gender & Languages are not correct. Please correct it as well.

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

{% block title %}Hello StudentRegistrationController!{% endblock %}

{% block body %}
   <div class="container"> 
     <div class="row "> 
     <h1 class = "mt-14 mb-6">Student Registration Form</h1>
        <div class="col-md-6">

           {{ form_start(form, {'attr': {'class': 'form'}}) }}
             {{ form_row(form.first_name, {'attr': {'class': 'form-control', 'style': 'margin-bottom: 30px;'}}) }}
             {{ form_row(form.last_name, {'attr': {'class': 'form-control', 'style': 'margin-bottom: 30px;'}}) }} 
             {{ form_row(form.email, {'attr': {'class': 'form-control', 'style': 'margin-bottom: 30px;'}}) }} 
             
             {{ form_row(form.gender, {'attr': {'class': 'form-control', 'style': 'margin-bottom: 30px;'}}) }}
 
             {{ form_row(form. address, {'attr': {'class': 'form-control', 'style': 'margin-bottom: 30px;'}}) }} 
             {{ form_row(form.languages, {'attr': {'class': 'form-control', 'style': 'margin-bottom: 30px;'}}) }}
             {{ form_row(form.country, {'attr': {'class': 'form-control', 'style': 'margin-bottom: 30px;'}}) }}  
             {{ form_row(form. Submit, {'attr': {'class': 'btn btn-primary btn-block mt-3'}}) }}   
           {{ form_end(form) }}    
        </div> 
     </div> 
 </div>

{% endblock %}

5 .env file

APP_ENV=dev
APP_SECRET=8e7a728a3ce6fd1438895ebf22793360
DATABASE_URL="mysql://root:@127.0.0.1:3307/StudentRegistration?serverVersion=8&charset=utf8mb4"
MESSENGER_TRANSPORT_DSN=doctrine://default?auto_setup=0

my db connection is correctly given. When i run php bin/console doctrine:database:create
The database StudentRegistration has been created in phpmyadmin.

Picture 1:-Form in browser.Try to fix gender & Langugages in my twig file

Picture 2:-After submitting the form browser showing output

Picture 3:-Shown output is not saved in my database

2

Answers


  1. Before calling $entityManager->flush() you need to call $entityManager->persist($student); to tell Doctrine you want to store it to the database.

    Read more about persisting objects here

    Login or Signup to reply.
  2. You need to pass the $student object to createForm() as the second argument. This is so that the form will work with that object. Otherwise it will not update $student with the form entry data.

    You should also explicitly specify the data_class option in the form class. E.g.:

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

    The relevant part of the Symfony documentation can be found here: https://symfony.com/doc/current/forms.html#creating-form-classes

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search