Hello everyone today I will guide you, especially those new to the Symfony framework how to create FormType using common or common field types. I forgot to follow this post I will continue the next article on how to self-customize custom errors or how to check validations for special cases, don’t say much more, let’s start
Component form
Form components are basically a tool or something that will help you solve problems that often arise from end-users when users manipulate data such as adding, editing, and deleting. To create the Form you do the following:
1 2 3 4 5 6 7 | use SymfonyComponentFormExtensionHttpFoundationHttpFoundationExtension; use SymfonyComponentFormForms; $formFactory = Forms::createFormFactoryBuilder() ->addExtension(new HttpFoundationExtension()) →getFormFactory(); |
To handle the data submitted we use the handleRequest () function, we only need to pass the parameter is the Request object.
1 2 | $form->handleRequest($request); |
Example: Create a simple form
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | // src/Controller/TaskController.php namespace AppController; use SymfonyBundleFrameworkBundleControllerAbstractController; use SymfonyComponentFormExtensionCoreTypeDateType; use SymfonyComponentFormExtensionCoreTypeTextType; class TaskController extends AbstractController { public function new(Request $request) { $form = $this->createFormBuilder() ->add('task', TextType::class) ->add('dueDate', DateType::class) ->getForm(); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $data = $form->getData(); // ... Xử lý logic ở đây, ví dụ như save data vào DB chảng hạn return $this->redirectToRoute('task_success'); } // ... } } |
Display the form on the view page:
1 2 3 4 5 6 | {{ form_start(form) }} {{ form_widget(form) }} <input type="submit"/> {{ form_end(form) }} |
Then when you come to this step, you will have for yourself a displayed form, but there are still problems as to validate (I will talk in the next article) or how to adjust the FieldType inside it. In my opinion, please continue reading below.
Text Fields
Text Fields in this group include field types that allow us to enter data such as TextType, TextareaType, NumberType, PasswordType, etc. The common options available in TextType are:
attr
: This option allows us to add attributes to the field when displayed in HTML, the value entered is of the array type.data
This allows us to set values for the field, the value of the input is all data types.disabled
: If you do not want the user to change data on the field then you use this option, the input value is boolean and the setting will be false.label
: set the label for this fieldmapped
: this option is when you want the field to bemapped
with the same data structure as previously defined, for example, when you have defined an Enity / Model with so many attributes / attributes, when setting the value totrue
then It will automatically map to the Enity / Model that you have defined, and in case offalse
, you can create a field whose name does not have in the attributes / attributes of an Enity / Model. Temporarily is like that later I will have an article that talks more about this and how to use it in real life.required
: The name says it all…
And there are many other options, but these are the most common options in the Text Fields group Example: How to create a Text Field
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | $builder->add('name', TextType::class, [ 'required' => false, 'attr' => [ 'placeholder' => ‘Please enter your name’, 'class' => 'text-input col-sm-10', ], 'constraints' => [ new NotBlank(), new Length([ 'max' => 100, 'maxMessage' => trans('message.length.max'), ]), ], ]) |
Choice Fields
Choice Fields allows users to select one or more gen when it will be select tags, radio …. Within this group is ChoiceType, EntityType is frequently used. Since this is used frequently, this article I will only say these two
ChoiceType
: When this gene generates HTML, it is a select tag, we can change it to become a dropdown or select, a group of radio buttonsEntityType
: This one I often use it to create dropdown fish (when the gene is also select). The difference between these two is that: ChoiceType is only used to display simple data of hard set data such as using it to display values in enums, for example, and EntityType is used for displaying Display data loaded from database. The options in the Choice Fields group are not much different from the Text Fields except:
choice_attr
: Often used to add attributes to each select option’s tagsgroup_by
: if you already know that 1 select it allows splitting up groups then this will work like thatmultiple
: this option allows us to select multiple (multi select / choice) or not.- …
Example: How to create a ChoiceType
1 2 3 4 5 6 7 8 9 10 11 12 13 | $builder->add('order_type', ChoiceType::class, [ 'required' => false, 'multiple' => false, 'placeholder' => 'Please choice...', 'choices' => [ '0' => 'DESC', '1’ => 'ASC', ], 'attr' => [ 'class' => 'order-select', ], ]) |
Example: How to create an EntityType
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | $builder->add('order_type', EntityType::class, [ 'class' => OrderType::class, 'choice_label' => 'order_type', 'expanded' => false, 'placeholder' => 'Please Choice….’, 'constraints' => [ new NotBlank(), ], 'query_builder' => function (EntityRepository $er) { return $er->createQueryBuilder('ot')->orderBy('ot .id', 'ASC'); }, 'choice_value' => function ( OrderType $oderType = null) { return $ oderType ? $oderType->getId() : null; }, 'choice_label' => function ( OrderType $category = null) { return $ oderType ? $oderType->getName() : null; }, ]) |
That’s all in general, this should be enough
Date and Time Fields
The fields in this group will have a way of displaying on HTML as inputs that allow to set the day / month / year or time, it can display in many different ways via widgets. A quick glance at some of the options is very similar to Choice Fields and TextFields. Example: How to create a DateType:
1 2 3 4 5 6 7 8 | $builder->add('published_at', DateType::class, [ 'widget' => 'single_text', 'input' => 'datetime_immutable' 'attr' => ['class' => 'js-datepicker'], 'placeholder' => 'Select a value', 'placeholder' => 'Select a value', ]); |
Other fields such as: Field Group, Hidden Fields, Button are nothing special, but there are still a lot of things to say like validation, form collection …. In summary, I have introduced fields that are often Meet most, the next article I will guide on how to validate, custom validation on a form.
Refer
Reference: https://symfony.com/doc/current/reference/forms/types.html