01 Jun 2014
forms [第12天]
Dealing with HTML forms is one of the most common - and challenging - tasks for a web developer. Symfony2 integrates a Form component that makes dealing with forms easy. In this chapter, you’ll build a complex form from the ground-up, learning the most important features of the form library along the way.
Tips:
The Symfony Form component is a standalone library that can be used outside of Symfony2 projects. For more information, see the Symfony2 Form component on GitHub.
Creating a Simple Form¶
Suppose you’re building a simple todo list application that will need to display “tasks”. Because your users will need to edit and create tasks, you’re going to need to build a form. But before you begin, first focus on the generic Task class that represents and stores the data for a single task:
Tips:
If you’re coding along with this example, create the AcmeTaskBundle first by running the following command (and accepting all of the default options):
This class is a “plain-old-PHP-object” because, so far, it has nothing to do with Symfony or any other library. It’s quite simply a normal PHP object that directly solves a problem inside your application (i.e. the need to represent a task in your application). Of course, by the end of this chapter, you’ll be able to submit data to a Task instance (via an HTML form), validate its data, and persist it to the database.
Building the Form¶
Now that you’ve created a Task class, the next step is to create and render the actual HTML form. In Symfony2, this is done by building a form object and then rendering it in a template. For now, this can all be done from inside a controller:
Tips:
This example shows you how to build your form directly in the controller. Later, in the “Creating Form Classes” section, you’ll learn how to build your form in a standalone class, which is recommended as your form becomes reusable.
Creating a form requires relatively little code because Symfony2 form objects are built with a “form builder”. The form builder’s purpose is to allow you to write simple form “recipes”, and have it do all the heavy-lifting of actually building the form.
In this example, you’ve added two fields to your form - task and dueDate - corresponding to the task and dueDate properties of the Task class. You’ve also assigned each a “type” (e.g. text, date), which, among other things, determines which HTML form tag(s) is rendered for that field. Finally, you added a submit button for submitting the form to the server.
New in version 2.3: Support for submit buttons was introduced in Symfony 2.3. Before that, you had to add buttons to the form’s HTML manually.
Symfony2 comes with many built-in types that will be discussed shortly (see Built-in Field Types).
Rendering the Form¶
Now that the form has been created, the next step is to render it. This is done by passing a special form “view” object to your template (notice the $form->createView() in the controller above) and using a set of form helper functions:
Twig:
That’s it! By printing form(form), each field in the form is rendered, along with a label and error message (if there is one). The form function also surrounds everything in the necessary HTML <form> tag. As easy as this is, it’s not very flexible (yet). Usually, you’ll want to render each form field individually so you can control how the form looks. You’ll learn how to do that in the “Rendering a Form in a Template” section.
Before moving on, notice how the rendered task input field has the value of the task property from the $task object (i.e. “Write a blog post”). This is the first job of a form: to take data from an object and translate it into a format that’s suitable for being rendered in an HTML form.
Tips:
The form system is smart enough to access the value of the protected task property via the getTask() and setTask() methods on the Task class. Unless a property is public, it must have a “getter” and “setter” method so that the Form component can get and put data onto the property. For a Boolean property, you can use an “isser” or “hasser” method (e.g. isPublished() or hasReminder()) instead of a getter (e.g. getPublished() or getReminder()).
Handling Form Submissions¶
The second job of a form is to translate user-submitted data back to the properties of an object. To make this happen, the submitted data from the user must be written into the form. Add the following functionality to your controller:
New in version 2.3: The handleRequest() method was introduced in Symfony 2.3. Previously, the $request was passed to the submit method - a strategy which is deprecated and will be removed in Symfony 3.0. For details on that method, see Passing a Request to Form::submit() (deprecated).
This controller follows a common pattern for handling forms, and has three possible paths:
1.When initially loading the page in a browser, the form is simply created and rendered. handleRequest() recognizes that the form was not submitted and does nothing. isValid() returns false if the form was not submitted.
2.When the user submits the form, handleRequest() recognizes this and immediately writes the submitted data back into the task and dueDate properties of the $task object. Then this object is validated. If it is invalid (validation is covered in the next section), isValid() returns false again, so the form is rendered together with all validation errors;
Tips: You can use the method isSubmitted() to check whether a form was submitted, regardless of whether or not the submitted data is actually valid.
3.When the user submits the form with valid data, the submitted data is again written into the form, but this time isValid() returns true. Now you have the opportunity to perform some actions using the $task object (e.g. persisting it to the database) before redirecting the user to some other page (e.g. a “thank you” or “success” page).
Tips:
Redirecting a user after a successful form submission prevents the user from being able to hit the “Refresh” button of their browser and re-post the data.
Submitting Forms with Multiple Buttons¶
New in version 2.3: Support for buttons in forms was introduced in Symfony 2.3.
When your form contains more than one submit button, you will want to check which of the buttons was clicked to adapt the program flow in your controller. To do this, add a second button with the caption “Save and add” to your form:
In your controller, use the button’s isClicked() method for querying if the “Save and add” button was clicked:
Form Validation¶
In the previous section, you learned how a form can be submitted with valid or invalid data. In Symfony2, validation is applied to the underlying object (e.g. Task). In other words, the question isn’t whether the “form” is valid, but whether or not the $task object is valid after the form has applied the submitted data to it. Calling $form->isValid() is a shortcut that asks the $task object whether or not it has valid data
Validation is done by adding a set of rules (called constraints) to a class. To see this in action, add validation constraints so that the task field cannot be empty and the dueDate field cannot be empty and must be a valid DateTime object.
YAML:
Acme/TaskBundle/Resources/config/validation.yml
Acme\TaskBundle\Entity\Task: properties: task: - NotBlank: ~ dueDate: - NotBlank: ~ - Type: \DateTime
That’s it! If you re-submit the form with invalid data, you’ll see the corresponding errors printed out with the form.
Til next time,
Xujiajun
at 08:32