发布于 2015-08-27 16:33:56 | 331 次阅读 | 评论: 0 | 来源: 网络整理
Forms are one of the most misused Symfony components due to its vast scope and endless list of features. In this chapter we’ll show you some of the best practices so you can leverage forms but get work done quickly.
最佳实践
Define your forms as PHP classes.
The Form component allows you to build forms right inside your controller code. This is perfectly fine if you don’t need to reuse the form somewhere else. But for organization and reuse, we recommend that you define each form in its own PHP class:
namespace AppBundleForm; use SymfonyComponentFormAbstractType; use SymfonyComponentFormFormBuilderInterface; use SymfonyComponentOptionsResolverOptionsResolver; class PostType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('title') ->add('summary', 'textarea') ->add('content', 'textarea') ->add('authorEmail', 'email') ->add('publishedAt', 'datetime') ; } public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(array( 'data_class' => 'AppBundleEntityPost' )); } public function getName() { return 'post'; } }
To use the class, use createForm
and instantiate the new class:
use AppBundleFormPostType; // ... public function newAction(Request $request) { $post = new Post(); $form = $this->createForm(new PostType(), $post); // ... }
You can also register your form type as a service. But this is not recommended unless you plan to reuse the new form type in many places or embed it in other forms directly or via the collection type.
For most forms that are used only to edit or create something, registering the form as a service is over-kill, and makes it more difficult to figure out exactly which form class is being used in a controller.
There are a lot of ways to render your form, ranging from rendering the entire thing in one line to rendering each part of each field independently. The best way depends on how much customization you need.
One of the simplest ways - which is especially useful during development - is to render the form tags and use form_widget()
to render all of the fields:
{{ form_start(form, {'attr': {'class': 'my-form-class'} }) }} {{ form_widget(form) }} {{ form_end(form) }}
If you need more control over how your fields are rendered, then you should remove the form_widget(form)
function and render your fields individually. See the How to Customize Form Rendering article for more information on this and how you can control how the form renders at a global level using form theming.
Handling a form submit usually follows a similar template:
public function newAction(Request $request) { // build the form ... $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $em = $this->getDoctrine()->getManager(); $em->persist($post); $em->flush(); return $this->redirect($this->generateUrl( 'admin_post_show', array('id' => $post->getId()) )); } // render the template }
There are really only two notable things here. First, we recommend that you use a single action for both rendering the form and handling the form submit. For example, you could have a newAction
that only renders the form and a createAction
that only processes the form submit. Both those actions will be almost identical. So it’s much simpler to let newAction
handle everything.
Second, we recommend using $form->isSubmitted()
in the if
statement for clarity. This isn’t technically needed, since isValid()
first calls isSubmitted()
. But without this, the flow doesn’t read well as it looks like the form is always processed (even on the GET request).
最佳实践
Add the app_
prefix to your custom form field types to avoid collisions.
Custom form field types inherit from the AbstractType
class, which defines the getName()
method to configure the name of that form type. These names must be unique in the application.
If a custom form type uses the same name as any of the Symfony’s built-in form types, it will override it. The same happens when the custom form type matches any of the types defined by the third-party bundles installed in your application.
Add the app_
prefix to your custom form field types to avoid name collisions that can lead to hard to debug errors.