Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement forms in Symfony2 Framework

2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article will explain in detail how to implement the form in the Symfony2 framework. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.

The details are as follows:

For a Web developer, dealing with HTML forms is one of the most common and challenging tasks. Symfony2 integrates a Form component that makes it easy to process forms. In this section, we will

Create a complex form from the foundation and learn the most important things in the form class library.

The Form component of Symfony2 is a stand-alone class library that you can use outside of Symfony2 projects.

Create a simple form:

Suppose you want to create a todo list of your application and you need to display some tasks. Because your users need to edit and create tasks, you need to create a form. Before you start, let's take a look at the general Task class, which represents and stores data for a single task:

/ / src/Acme/TaskBundle/Entity/Task.phpnamespace Acme\ TaskBundle\ Entity;class Task {protected $task; protected $dueDate; public function getTask () {return $this- > task;} public function setTask ($task) {$this- > task = $task;} public function getDueDate () {return $this- > dueDate;} public function setDueDate (\ DateTime $dueDate = null) {$this- > dueDate = $dueDate;}}

If you are coding according to the example provided by us, you need to create an AcmeTaskBundle first:

$php app/console generate:bundle-namespace=Acme/TaskBundle

This class is a normal PHP object class because they do not have any Symfony or other class library references. A very simple PHP object class that directly deals with the data that represents task in your program. Of course, at the end of this section, you will be able to submit an Task instance data through the HTML form, verify its value, and persist it to the database.

Create a Form

Now that you have created a Task class, the next step is to create and render a real HTML form. In symfony2, it is done by creating a form object and rendering it to a template. Form can now be processed from within controller.

/ / src/Acme/TaskBundle/Controller/DefaultController.phpnamespace Acme\ TaskBundle\ Controller;use Symfony\ Bundle\ FrameworkBundle\ Controller\ Controller;use Symfony\ Component\ HttpFoundation\ Request;use Acme\ TaskBundle\ Entity\ Task;class DefaultController extends Controller {/ / create a task and give it some fake data as examples $task = new Task (); $task- > setTask ('Write a blog post'); $task- > setDueDate (new\ DateTime (' tomorrow')) $form = $this- > createFormBuilder ($task)-> add ('task','text')-> add (' dueDate','date')-> getForm (); return $this- > render ('AcmeTaskBundle:Default:new.html.twig',array (' form' = > $form- > createView (),);}

The above example shows how to create a form directly in Controller. In order to reuse the form, you can create the form in a separate class file.

Because Symfony2 uses a form generator "form builder" to create form objects, you can do the form creation task with very little code. The purpose of the form builder is to allow you to write a simple form creation method that is responsible for heavy creation tasks.

In this example, you have added two fields to your form, one is task and the other is dueDate. They are associated with the task and dueDate properties of the Task class. You have specified types for each of them (e.g., text,date, etc.), and these types determine what kind of HTML form tags are generated for these fields.

Symfony2 has many built-in types, which we will briefly introduce next.

Render a form

After the form is created, the next step is to render it. This is done by passing a specific form "view" object (that is, the view object returned by $form- > createView () in the example above) to your template and through some columns of form helpers.

Twig format:

{# src/Acme/TaskBundle/Resources/views/Default/new.html.twig #} {{form_widget (form)}}

PHP code format:

>

Assume here that you have created a route called task_new that points to AcmeTaskBundle:Default:new Controller.

That's it. By printing form_widget (form), every field in the form is rendered. There is also a text label and an error message. Isn't it simple, but it's not flexible enough yet. In general, we are eager to render each field in the form separately so that we can have more control over the style of the form. We will describe it in the section rendering the form in the template.

Before we go any further, we notice why the task input box we rendered has a property value of "Write a blog post" from the $task object. This is the first job of a form: take data from an object and render it into an HTML form in the appropriate format.

Note that the form systems are smart enough to access the protected property task in the Task class through methods like getTask () and setTask (). Unless one is a public property, a getter and setter methods must be defined for the form component to get and hold data from these properties. For Boolean properties, you can use a "isser" method (such as isPublished ()) instead of the getter method (getPublished ()).

Handle form submission

The second task of the form system is to pass the data submitted by the user back to the properties of an object. To do this, the data submitted by the user must be bound to the form. Add the following code to your Controller class:

/ /... public function newAction (Request $request) {/ / just create a new $task object (no fake data is needed) $task = new Task (); $form= $this- > createFormBuilder ($task)-> add ('task','text')-> add (' dueDate','date')-> getForm (); if ($request- > getMethod () = = "POST") {$form- > bindRequest ($request) If ($form- > isValid ()) {/ / performs some behaviors, such as keeping task to the database return $this- > redirect ($this- > generateUrl ('task_success'));}} /.}

Now, when the form is submitted, Controller can bind the submitted data to the form, and the form returns the data back to the task and dueDate properties of the $task object. This is all done in the bindRequest () method. As soon as the bindRequest () method is called, the submitted data is immediately transferred to the underlying object. Whether the data is actually checked or not.

Controller generally follows a general pattern for dealing with forms, and there are three possible ways:

1. When a page is initially loaded in the browser, the request method is GET, and the form processing is simply creation and rendering.

two。 When a user submits a form with illegal data (the method is POST), the form is bound and then rendered, showing all validation errors.

3. When the data submitted by the user is legal, the form is bound and you have the opportunity to use the data to perform some business logic activities, such as persisting it to the database, before the page jumps.

Form check

We mentioned earlier how to submit a form with both legal and illegal data. In Symfony2, validation is done on the underlying object. In other words, it doesn't matter whether the form form is legal or not, it depends on whether the underlying object, such as the $task object, is legal after the form submits the data. Calling $form- > isvalid () is a shortcut to ask whether the underlying object has legal data.

Validation is done by adding some column rules (constraints) to a class. We add rules and constraints to the Task class so that its task property cannot be empty, the duDate field cannot be empty and is a legitimate DateTime object.

YAML format:

# Acme/TaskBundle/Resources/config/validation.ymlAcme\ TaskBundle\ Entity\ Task: properties: task:-NotBlank: ~ dueDate:-NotBlank: ~-Type:\ DateTime

Declare the format in the Task class:

/ / Acme/TaskBundle/Entity/Task.phpuse Symfony\ Component\ Validator\ Constraints as Assert;class Task {/ * @ Assert\ NotBlank () * / public $task; / * * @ Assert\ NotBlank () * @ Assert\ Type ("\ DateTime") * / protected $dueDate;}

XML format:

\ DateTime

PHP code format:

/ / Acme/TaskBundle/Entity/Task.phpuse Symfony\ Component\ Validator\ Mapping\ ClassMetadata;use Symfony\ Component\ Validator\ Constraints\ NotBlank;use Symfony\ Component\ Validator\ Constraints\ Type;class Task {/ /. Public static function loadValidatorMetadata (ClassMetadata $metadata) {$metadata- > addPropertyConstraint ('task', new NotBlank ()); $metadata- > addPropertyConstraint (' dueDate', new NotBlank ()); $metadata- > addPropertyConstraint ('dueDate', new Type ('\ DateTime'));}}

That's it. If you submit a form that contains illegal data now, you will see the corresponding error printed on the form.

HTML5 check

As HTML5, many browsers strengthen some validation constraints on the client side. The most common verification activity is to render a required property on a required field. For browsers that support HTML5, the browser displays a prompt if the user submits an empty field to the form at this time. The generated form widely absorbs the advantages of these new content, and monitors the validation by adding some HTML attributes. Client-side validation can be turned off by adding the novalidate attribute to the form tag or formnovalidate to the submission tag. This is very useful when you want to check the server-side verification rules.

Check packet

If your object wants to benefit from the verification group, you need to specify which verification group your form uses.

$form = $this- > createFormBuilder ($users, array ('validation_groups' = > array (' registration'),))-> add (...)

If you create a form class, you need to add the enviable getDefaultOptions () method:

Public function getDefaultOptions (array $options) {return array ('validation_groups' = > array (' registration'));}

In both cases, only the registration verification group will be used to validate the underlying object.

Built-in field type

Symfony Standard Edition contains a large number of field types, which cover almost all common form fields and data types.

Text field:

Text

Textarea

Email

Integer

Money

Number

Password

Percent

Search

Url

Select the field:

Choice

Entity

Country

Language

Locale

Timezone

Date and time fields:

Date

Datetime

Time

Birthday

Other fields:

Checkbox

File

Radio

Field groups:

Collection

Repeated

Hidden fields:

Hidden

Csrf

Basic fields:

Field

Form

Of course, you can also define your own field types.

Field Type option

Each field type has a certain number of options for configuration. For example, the dueDate field is currently rendered as three selection boxes. The date field can be configured to render as a single text box, and the user can enter a string as the date.

-> add ('dueData','data', array (' widget' = 'single_text'))

Required options:

The most commonly used option is the required option, which can be applied to any field. It is set to true by default. This means that browsers that support HTML5 will use client-side validation to determine whether the field is empty. If you don't want it to happen, either set the required option to false on your field, or turn off the HTML5 check. Setting required to true does not mean that server-side validation is applied. In other words, if the user submits an empty value to the field, it will accept this control unless you use Symfony's NotBlank or NotNull check constraint. In other words, the required option is good, but server-side validation should continue to be used.

Label options:

Form fields can be labeled with display characters using the label option, and can be applied to any field:

-> add ('dueDate',' date',array ('widget' = >' single_text', 'label' = >' Due Date',))

Field type guess:

Now that you have added the validation metadata to the Task class, Symfony already knows a little about your fields. If you allow it, Symfony can guess your field data type and set it for you. In the following example, Symfony can guess from the verification rules that the task field is a standard text field and dueDate is the date field.

Public function newAction () {$task = new Task (); $form = $this- > createFormBuilder ($task)-> add ('task')-> add (' dueDate', null, array ('widget' = > single_text'))-> getForm ();}

Symfony's guessing ability works when you omit the second parameter of the add method (or you type null). If you enter an array of options as the third parameter (such as dueDate above), then these options will become the basis for Symfony guesses. If your form uses the specified check array, the field type guesser will still take into account all the validation rules to comprehensively guess your field type.

Field type optional guess

In addition to guessing the field type, Symfony can also guess some optional field values. When these options are set, the field will be rendered to a specific HTML property and the HTML5 client will provide the check.

However, they do not generate corresponding verification rules on the server side. Although you need to manually add these rules to the server, these field type options can still be guessed from this information.

Required: required rules can be guessed on the basis of validation rules or document metadata. This is useful when your client-side validation will automatically match your verification rules.

Max_length: if the field is a column text field, the max_length option can be guessed from the validation rules or document metadata.

If you like to change a guessed value, you can override it by passing this option in an array of options.

-> add ('task',null, array (' max_length'= > 4))

Render the form in a template

So far, we have seen how a complete form is rendered with a single line of code. Of course, you usually need more flexible rendering:

Twig format:

{# src/Acme/TaskBundle/Resources/views/Default/new.html.twig #} {{form_errors (form)}} {{form_row (form.task)}} {{form_row (form.dueDate)}} {{form_rest (form)}}

PHP code format:

>

Let's take a look at the details of this set of code:

Form_enctype (form) as long as one field is a file upload, it will be set to enctype= "multipart/form-data".

Form_errors (form) renders any error message for any entire form (errors for specific fields are displayed on the following line of each field).

Form_row (form.dueDate) by default, renders a text label, any errors, and HTML form widgets in a div for a given field.

Form_rest (form) renders any remaining fields that are not indicated, and is usually called at the end of the form to prevent forgetting or rendering hidden fields that you don't want to set manually. It can also provide us with CSRF protection.

Most of the work is done by the form_row helper class, which by default renders and displays labels, error messages, and HTML form widgets for each field in a div.

Note that you can access your current table data through form.vars.value:

Twig format:

{{form.vars.value.task}}

PHP code format:

Manually render each form field

The form_row helper allows you to quickly render every field in your form, and each line can be customized. But life is not always that simple, and you may have to render each field manually.

Twig format:

{{form_errors (form)}} {{form_errors (form.task)}} {{form_widget (form.task)}} {{form_label (form.dueDate)}} {{form_errors (form.dueDate)}} {{form_widget (form.dueDate)}} {{form_rest (form)}}

PHP code format:

If the automatic generation of the display label is not accurate, you can specify it explicitly:

Twig format:

{{form_label (form.task, 'Task Description')}}

PHP code format:

Some field types have additional rendering options that can be passed into widget, and a common option is attr, which allows you to modify the properties of form elements. The following example adds task_field class to the rendered text input field:

Twig format:

{{form_widget (form.task, {'attr': {' class':'task_field'}})}}

PHP code format:

If you want to render form fields manually, you can access the values of each field individually, such as id,name and label. Here we get id

Twig format:

{{form.task.vars.id}}

PHP code format:

You need to get the form field name property. You need to use the full_ name value:

Twig format:

{{form.task.vars.full_name}}

PHP code format:

Create a form class

As you can see, a form can be created and used directly in the controller class. However, a better approach is to create the form in a separate PHP class. It can be reused anywhere in your application. Create a new class to hold the logic for generating the task form:

/ / src/Acme/TaskBundle/Form/Type/TaskType.phpnamespace Acme\ TaskBundle\ Form\ Type;use Symfony\ Component\ Form\ AbstractType;use Symfony\ Component\ Form\ FormBuilder;class TaskType extends AbstractType {public function buildForm (FormBuilder $builder, array $options) {$builder- > add ('task'); $builder- > add (' dueDate', null, array ('widget' = >' single_text');} public function getName () {return 'task';}}

This new class contains everything you need to create an task form. Note that the getName () method returns a unique identity of the form type for quick creation of the form.

/ / src/Acme/TaskBundle/Controller/DefaultController.php// add this new reference statement use Acme\ TaskBundle\ Form\ Type\ TaskType;public function newAction () {$task = /... $form = $this- > createForm (new TaskType (), $task) to the class; / /.}

Set up data_class

Each form needs to know the name of the class in which its underlying data is stored (for example, Acme\ TaskBundle\ Entity\ Task). Usually, the guess is based on the second parameter of the createForm method. Later, when you start embedding forms, this may not be enough, so it's usually a good idea to explicitly specify the data_class option by adding the following code to your form type class.

Public function getDefaultOptions (array $options) {return array ('data_class' = >' Acme\ TaskBundle\ Entity\ Task',);}

Of course, this is not always necessary.

When you map a form to an object, all fields are mapped. Any field of the form that does not exist on the mapped object will cause an exception to be thrown. In this case, you need to get the fields in the form (for example, a "do you agree with these statements?" Check box) will not map to the underlying object, so you need to set property_path to false to avoid throwing an exception.

Public function buildForm (FormBuilder $builder, array $options) {$builder- > add ('task'); $builder- > add (' dueDate', null, array ('property_path' = > false));}

In addition, if there are any form fields that are not included in the submitted data, then these fields need to be explicitly set to null.

We can access the field data in the controller class:

$form- > get ('dueDate')-> getData ()

Forms and Doctrine

The purpose of a form is to pass data from an underlying object to an HTML form and then return the data submitted by the user to the original underlying object. Therefore, the underlying object persists the data to the database and has nothing to do with the form. However, if you have configured the underlying class to be persisted through Doctrine (you have defined mapping metadata in the underlying class), then when the form submits the data, it can be persisted when the form is legal.

If ($form- > isValid ()) {$em = $this- > getDoctrine ()-> getEntityManager (); $em- > persist ($task); $em- > flush (); return $this- > redirect ($this- > generateUrl ('task_success'));}

If for some reason you don't want to access the original $task object, you can get the data directly from the form:

$task = $form- > getData ()

Here, it is important to understand that when the form is bound to the underlying object, the data submitted by the user is immediately passed to the underlying object. If you want to persist the data, you only need to persist the object itself.

Embedded form: (Embedded Forms)

In general, you may want to generate a form that contains fields from different objects. For example, a registration form might contain fields that belong to User objects and Address objects. Fortunately, all of this is easy and natural for form components. Embed a separate object: assuming that each Task belongs to a Category object, first create the Category object:

/ / src/Acme/TaskBundle/Entity/Category.phpnamespace Acme\ TaskBundle\ Entity;use Symfony\ Component\ Validator\ Constraints as Assert;class Category {/ * * @ Assert\ NotBlank () * / public $name;}

Next, add a new category property to the Task class:

/ /. Class Task {/... / * * @ Assert\ Type (type= "Acme\ TaskBundle\ Entity\ Category") * / protected $category; / /. Public function getCategory () {return $this- > category;} public function setCategory (Category $category = null) {$this- > category = $category;}}

Now to address a new requirement of our application, we need to create a form that allows the user to modify the Category object.

/ / src/Acme/TaskBundle/Form/Type/CategoryType.phpnamespace Acme\ TaskBundle\ Form\ Type;use Symfony\ Component\ Form\ AbstractType;use Symfony\ Component\ Form\ FormBuilder;class CategoryType extends AbstractType {public function buildForm (FormBuilder $builder, array $options) {$builder- > add ('name');} public function getDefaultOptions (array $options) {return array (' data_class' = > 'Acme\ TaskBundle\ Entity\ Category',);} public function getName () {return' category';}

Our ultimate goal is to enable the user to modify the Category object in the Task form, so we need to add a category field of type CategoryType form class to the TaskType form class.

Public function buildForm (FormBuilder $builder, array $options) {/ /... $builder- > add ('category', new CategoryType ());}

At this point, we can render the fields of the TaskType class next to the rendering of the CategoryType class fields:

Twig format:

{#... #} Category {{form_row (form.category.name)}} {{form_rest (form)}} {#... #}

PHP code format:

Category

When the user submits the form, the submitted Category field data is used to create a Category instance, which is then set to the category field of the Task instance. The Category instance can be accessed through the Task instance, and can also be persisted to data or used for other purposes.

$task- > getCategory ()

Embed a form collection

You can also embed a form collection into a form (imagine an Category form and many produce subforms). It is implemented through a field type collection class.

Form theming

Each part of the form rendering can be customized and personalized. You are free to change the rendering of each form line, change the rendering error flag, or how the textarea tag should be displayed. There are no restrictions, and different personalization settings can be used in different areas.

Symfony uses templates to render each or part of the form, such as label tags, input tags, error messages, and any other content. In Twig, each form fragment is rendered by a Twig block. To personalize the rendering form, you only need to rewrite the corresponding block. In PHP templates, it renders form fragments through separate template files, so you need to write a new template to replace the old one. Now that you understand how they work, let's personalize the form_row fragment and add a class attribute to the div element that wraps each table row. First create a new template file to hold the new logo:

Twig format:

{# src/Acme/TaskBundle/Resources/views/Form/fields.html.twig #} {% block field_row%} {% spaceless%} {{form_label (form)}} {{form_errors (form)}} {{form_widget (form)}} {% endspaceless%} {% endblock field_row%}

PHP code format:

Field_row form snippets are used when rendering most of the form fields through the form_row function. To tell your form component to use your new field_row snippet, add the following to the top of the template where you rendered the form:

Twig format:

{# src/Acme/TaskBundle/Resources/views/Default/new.html.twig #} {% form_theme form 'AcmeTaskBundle:Form:fields.html.twig'%} {% form_theme form' AcmeTaskBundle:Form:fields.html.twig' 'AcmeTaskBundle:Form:fields2.html.twig'%}

PHP code format:

The form_theme tag imports the previously defined fragment. In other words, when the form_row function is called in the template, it will use the field_row block from your custom theme (instead of Symfony's existing field_row block). You don't have to rewrite all the blocks for your personalized theme. When rendering a block that you have not rewritten, the theme causes a global theme (defined at the bundle level) to be used.

In the case of multiple personalized themes, it looks for a custom list before using the global theme. To personalize any part of your form, you only need to rewrite the relevant fragments.

Form fragment naming

In symfony, every part of the form is rendered, and HTML form elements, error messages, display tags, and so on are defined in the underlying theme. It consists of a collection of Twig blocks and a collection of PHP templates.

In Twig, each required block is defined into a separate template file (form_dive_layout.html.twig), which is stored in Twig Bridge. In this file, you can see each block and default field type required to render a form.

In PHP templates, fragments are separate template files. By default, they are located in the Resources/views/Form directory of the framework bundle. Each skewness name follows the same basic pattern and is divided into two parts with an underscore (_), such as:

Field_row is used for most of the fields in form_row rendering

Textarea_widget is used for form_widget rendering of a textarea field type

Field_errors is used to form_errors to render an error message for a field

Each fragment is named according to the type_part pattern. The type part corresponds to the field type being rendered (such as textarea,checkbox,date, etc.), while the part part corresponds to what is rendered (such as label,widget,errors, etc.)

By default, there are four possible form part for rendering:

The label of the label render field such as field_label

The HTML representation of the widget render field is like field_widget

Error messages for errors render fields such as field_errors

The entire line of the row render field (including label,widget and errors) such as filed_row

There are three other part types, rows,rest and enctype, but these three are not generally used.

By knowing the field type (e.g. textarea) and which part you want to render (e.g. widget), you can create a fragment name that you need to rewrite (e.g. textarea_widget).

Template fragment inheritance

In some cases, your personalized clips may be lost. For example, textarea_errors snippets are not provided in the default theme provided by Symfony. So how do you render an error message for a textarea field?

The answer is through field_errors fragments. When Symfony renders an error of type textarea, it first looks for a textarea_errors fragment, and if it doesn't find it, it returns to the field_errors fragment.

Each field type has a parenttype (the parent type of textarea is field), and if Symfony does not find its own fragment, it will use the parent fragment instead.

So, to override the errors of the textarea field, copy the field_errors fragments, rename them to textarea_errors, and personalize them. Overriding the default error rendering for all fields requires a direct copy and personalization of field_errors clips.

Global form topic

In the above example, we used form_theme helper to import a custom form fragment into the form. You can also tell Symfony to import custom form throughout the project.

Twig

To automatically include personalized block from all previously created fileds.html.twig templates, modify your application configuration file:

YAML format:

# app/config/config.ymltwig: form: resources:-'AcmeTaskBundle:Form:fields.html.twig' #...

XML format:

AcmeTaskBundle:Form:fields.html.twig

PHP code format:

/ / app/config/config.php$container- > loadFromExtension ('twig', array (' form' = > array ('resources' = > array (' AcmeTaskBundle:Form:fields.html.twig',)) / /...))

Any block in the fields.html.twig template can now be widely used to define the form output.

Custom form output to a single Twig file

In Twig, you can also personalize a form block in the template

{% extends':: base.html.twig'%} {# Import "_ self" as a form subject #} {% form_theme form_ self%} {# Personalized form fragment #} {% block field_row%} {# Custom Field Row output #} {% block content%} {#. #} {{form_row (form.task)} {% endblock%}

Here the {% form_theme form_ self%} tag allows form blocks to be directly customized in templates that use automated content. Use this method to quickly generate personalized output.

Note that the functionality of {% form_theme form_ self%} works only if it is inherited from another template, and if it is not inherited from another template, you need to indicate that form_theme is in a separate template.

PHP

Personalization templates are automatically imported from the Acme/TaskBundle/Resources/views/Form directory previously created in all templates. Modify your configuration file:

YAML format:

# app/config/config.ymlframework: templating: form: resources:-'AcmeTaskBundle:Form'#...

XML format:

AcmeTaskBundle:Form

PHP code format:

/ / app/config/config.php$container- > loadFromExtension ('framework', array (' templating' = > array ('form' = > array (' resources' = > array ('AcmeTaskBundle:Form',)) / /...))

At this point, any fragment in the Acme/TaskBundle/Resources/views/Form directory can define the form output globally.

CSRF protection

CSRF--Cross-site request forgery, cross-site forgery is a way for malicious attackers to try to get your legitimate users to unwittingly submit data they don't want to submit.

Fortunately, CSRF attacks can be blocked by using CSRF tokens in your form.

By default, Symfony automatically embeds a legitimate CSRF token for you. This means you don't have to do anything to get CSRF protection. CSRF is protected by adding a hidden field to your form, which is called _ token by default. It contains a value that only you and your users know. This ensures that it is the user, not the other entity, that is submitting the data. Symfony automatically verifies the existence and accuracy of the token.

The _ token field is a hidden field and will be automatically rendered, as long as you include the form_rest () function in your template. It ensures that all fields that have not been rendered are rendered. CSRF tokens can be personalized according to the form, such as:

Class TaskType extends AbstractType {/ /... Public function getDefaultOptions (array $options) {return array ('data_class' = >' Acme\ TaskBundle\ Entity\ Task', 'csrf_protection' = > true,' csrf_field_name' = >'_ token', / / a unique key value to guarantee the generation of the token 'intention' = >' task_item',);} / /.}

To turn off CSRF protection, set the csrf_protection option to false. The intentsion option is optional, but generating different tokens for different forms greatly enhances security.

Use a bottomless class form

In most cases, a form binds to an object, and all the fields in the form get or save their data to the object properties. Sometimes, however, you may just want to use a classless form and return an array of submitted data, which is very easy to implement:

/ / make sure you import the Request object use Symfony\ Component\ HttpFoundation\ Request//. Public function contactAction (Request $request) {$defaultData = array ('message' = >' Type your message here'); $form = $this- > createFormBuilder ($defaultData)-> add ('name',' text')-> add ('email',' email')-> add ('message',' textarea')-> getForm () If ($request- > getMethod () = = 'POST') {$form- > bindRequest ($request); / / the data is an array and contains "name", "email", and "message" keys $data = $form- > getData ();} / /. Render form}

By default, a form really assumes that you want an array of data instead of a data object.

There are two ways you can change its behavior and bind an object.

1. Pass in an object when you create the form (as the first parameter of createFormBuilder or the second parameter of createForm).

two。 Declare the data_class option in your form

If neither of the above is available, the form returns an array of data. In this example, because $defaultData is not an object and the data_class option is not set, $form- > getData () eventually returns an array.

You can also access the value of POST directly through the Request object

$this- > get ('request')-> request- > get (' name')

Note that in most cases we use the getData () method as a better choice. Because it returns data that has been converted by the form framework.

Add a check rule

The only thing missing is the verification rule. Usually when you call $form- > isvalid (), the object will call the verification rule you provided in the class east to verify. But if there are no classes, how do you add constraint rules to your form data? The answer is to create your own constraints and then pass them into the form.

Import the namespace use Symfony\ Component\ Validator\ Constraints\ Email;use Symfony\ Component\ Validator\ Constraints\ MinLength;use Symfony\ Component\ Validator\ Constraints\ Collection;$collectionConstraint = new Collection before the controller class (array ('name' = > new MinLength (5),' email' = > new Email (array ('message' = > Invalid email address'),)); / / create a form with no default value, pass in the constraint option. $form = $this- > createFormBuilder (null, array ('validation_constraint' = > $collectionConstraint,)-> add (' email', 'email') / /.

Now, when you call $form- > bindRequest ($request), the constraint will be created and applied to your form data. If you use a form class, override the getDefaultOptions method to specify options:

Namespace Acme\ TaskBundle\ Form\ Type;use Symfony\ Component\ Form\ AbstractType;use Symfony\ Component\ Form\ FormBuilder;use Symfony\ Component\ Validator\ Constraints\ Email;use Symfony\ Component\ Validator\ Constraints\ MinLength;use Symfony\ Component\ Validator\ Constraints\ Collection;class ContactType extends AbstractType {/ /. Public function getDefaultOptions (array $options) {$collectionConstraint = new Collection (array ('name' = > new MinLength (5),' email' = > new Email (array ('message' = >' Invalid email address'),)); return array ('validation_constraint' = > $collectionConstraint);}}

This gives you enough flexibility to create form classes and constraints that return an array of data instead of an object. In most cases, this is good, but binding a form to an object is somewhat more robust. It's a good choice for simple forms.

This is the end of the article on "how to implement the form in the Symfony2 framework". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it out for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report