The Form Component

The Form component allows you to create, process and reuse forms.

Form コンポーネントを使用すると、フォームを作成、処理、および再利用できます。

The Form component is a tool to help you solve the problem of allowing end-users to interact with the data and modify the data in your application. And though traditionally this has been through HTML forms, the component focuses on processing data to and from your client and application, whether that data be from a normal form post or from an API.

フォーム コンポーネントは、エンド ユーザーがデータを操作してアプリケーション内のデータを変更できるようにするという問題を解決するのに役立つツールです。そして、これは従来 HTML フォームを介して行われてきたと考えられており、コンポーネントは、データが通常のフォーム ポストからのものであろうと API からのものであろうと、クライアントおよびアプリケーションとの間でやり取りされるデータの処理に重点を置いています。

Installation

1
$ composer require symfony/form

Note

ノート

If you install this component outside of a Symfony application, you must require the vendor/autoload.php file in your code to enable the class autoloading mechanism provided by Composer. Read this article for more details.

このコンポーネントを Symfony アプリケーションの外部にインストールする場合は、Composer が提供するクラス自動ロード メカニズムを有効にするために、コード内に vendor/autoload.php ファイルを必要とする必要があります。詳細については、この記事をお読みください。

Configuration

See also

こちらもご覧ください

This article explains how to use the Form features as an independent component in any PHP application. Read the Forms article to learn about how to use it in Symfony applications.

この記事では、任意の PHP アプリケーションでフォーム機能を独立したコンポーネントとして使用する方法について説明します。フォームの記事を読んで、Symfony アプリケーションでフォームを使用する方法を学んでください。

In Symfony, forms are represented by objects and these objects are built by using a form factory. Building a form factory is done with the factory method Forms::createFormFactory:

Symfony では、フォームはオブジェクトによって表され、これらのオブジェクトはフォーム ファクトリを使用して構築されます。フォーム ファクトリの構築は、factorymethod Forms::createFormFactory を使用して行います。
1
2
3
use Symfony\Component\Form\Forms;

$formFactory = Forms::createFormFactory();

This factory can already be used to create basic forms, but it is lacking support for very important features:

このファクトリは、基本的なフォームを作成するために既に使用できますが、非常に重要な機能のサポートが不足しています:
  • Request Handling: Support for request handling and file uploads;
    リクエスト処理: リクエスト処理とファイル アップロードのサポート。
  • CSRF Protection: Support for protection against Cross-Site-Request-Forgery (CSRF) attacks;
    CSRF 保護: Cross-Site-Request-Forgery (CSRF) 攻撃に対する保護のサポート。
  • Templating: Integration with a templating layer that allows you to reuse HTML fragments when rendering a form;
    テンプレート化: フォームのレンダリング時に HTML フラグメントを再利用できるようにするテンプレート層との統合。
  • Translation: Support for translating error messages, field labels and other strings;
    翻訳: エラー メッセージ、フィールド ラベル、その他の文字列の翻訳をサポート。
  • Validation: Integration with a validation library to generate error messages for submitted data.
    検証: 送信されたデータのエラー メッセージを生成するための検証ライブラリとの統合。

The Symfony Form component relies on other libraries to solve these problems. Most of the time you will use Twig and the Symfony HttpFoundation, Translation and Validator components, but you can replace any of these with a different library of your choice.

Symfony フォーム コンポーネントは、これらの問題を解決するために他のライブラリに依存しています。ほとんどの場合、Twig と SymfonyHttpFoundation、Translation、および Validator コンポーネントを使用しますが、これらのいずれかを選択した別のライブラリに置き換えることができます。

The following sections explain how to plug these libraries into the form factory.

次のセクションでは、これらのライブラリをフォーム ファクトリにプラグインする方法について説明します。

Tip

ヒント

For a working example, see https://github.com/webmozart/standalone-forms

実際の例については、https://github.com/webmozart/standalone-forms を参照してください。

Request Handling

To process form data, you'll need to call the handleRequest() method:

フォーム データを処理するには、handleRequest() メソッドを呼び出す必要があります。
1
$form->handleRequest();

Behind the scenes, this uses a NativeRequestHandler object to read data off of the correct PHP superglobals (i.e. $_POST or $_GET) based on the HTTP method configured on the form (POST is default).

舞台裏で、これは NativeRequestHandler オブジェクトを使用して、フォームで構成された HTTP メソッド (POST がデフォルト) に基づいて、正しい PHP スーパーグローバル (つまり、$_POST または $_GET) からデータを読み取ります。

See also

こちらもご覧ください

If you need more control over exactly when your form is submitted or which data is passed to it, use the submit() method to handle form submissions.

フォームがいつ送信されるか、またはフォームに渡されるデータをより正確に制御する必要がある場合は、submit() メソッドを使用してフォームの送信を処理します。
HttpFoundation コンポーネントとの統合

If you use the HttpFoundation component, then you should add the HttpFoundationExtension to your form factory:

HttpFoundation コンポーネントを使用する場合は、HttpFoundationExtension をフォーム ファクトリに追加する必要があります。
1
2
3
4
5
6
use Symfony\Component\Form\Extension\HttpFoundation\HttpFoundationExtension;
use Symfony\Component\Form\Forms;

$formFactory = Forms::createFormFactoryBuilder()
    ->addExtension(new HttpFoundationExtension())
    ->getFormFactory();

Now, when you process a form, you can pass the Request object to handleRequest():

これで、フォームを処理するときに、Request オブジェクトを handleRequest() に渡すことができます。
1
$form->handleRequest($request);

Note

ノート

For more information about the HttpFoundation component or how to install it, see The HttpFoundation Component.

HttpFoundation コンポーネントまたはそのインストール方法の詳細については、「HttpFoundation コンポーネント」を参照してください。

CSRF Protection

Protection against CSRF attacks is built into the Form component, but you need to explicitly enable it or replace it with a custom solution. If you want to use the built-in support, first install the Security CSRF component:

CSRF 攻撃に対する保護はフォーム コンポーネントに組み込まれていますが、明示的に有効にするか、カスタム ソリューションに置き換える必要があります。組み込みのサポートを使用する場合は、まず Security CSRF コンポーネントをインストールします。
1
$ composer require symfony/security-csrf

The following snippet adds CSRF protection to the form factory:

次のスニペットは、CSRF 保護をフォーム ファクトリに追加します。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
use Symfony\Component\Form\Extension\Csrf\CsrfExtension;
use Symfony\Component\Form\Forms;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Security\Csrf\CsrfTokenManager;
use Symfony\Component\Security\Csrf\TokenGenerator\UriSafeTokenGenerator;
use Symfony\Component\Security\Csrf\TokenStorage\SessionTokenStorage;

// creates a RequestStack object using the current request
$requestStack = new RequestStack();
$requestStack->push($request);

$csrfGenerator = new UriSafeTokenGenerator();
$csrfStorage = new SessionTokenStorage($requestStack);
$csrfManager = new CsrfTokenManager($csrfGenerator, $csrfStorage);

$formFactory = Forms::createFormFactoryBuilder()
    // ...
    ->addExtension(new CsrfExtension($csrfManager))
    ->getFormFactory();

Internally, this extension will automatically add a hidden field to every form (called _token by default) whose value is automatically generated by the CSRF generator and validated when binding the form.

内部的に、この拡張機能はすべてのフォーム (デフォルトでは _token と呼ばれます) に隠しフィールドを自動的に追加します。この値は、CSRF ジェネレーターによって自動的に生成され、フォームをバインドするときに検証されます。

Tip

ヒント

If you're not using the HttpFoundation component, you can use NativeSessionTokenStorage instead, which relies on PHP's native session handling:

HttpFoundation コンポーネントを使用していない場合は、代わりに PHP のネイティブ セッション処理に依存する NativeSessionTokenStorage を使用できます。
1
2
3
4
use Symfony\Component\Security\Csrf\TokenStorage\NativeSessionTokenStorage;

$csrfStorage = new NativeSessionTokenStorage();
// ...

You can disable CSRF protection per form using the csrf_protection option:

csrf_protection オプションを使用して、フォームごとに CSRF 保護を無効にすることができます。
1
2
3
4
use Symfony\Component\Form\Extension\Core\Type\FormType;

$form = $formFactory->createBuilder(FormType::class, null, ['csrf_protection' => false])
    ->getForm();

Twig Templating

If you're using the Form component to process HTML forms, you'll need a way to render your form as HTML form fields (complete with field values, errors, and labels). If you use Twig as your template engine, the Form component offers a rich integration.

Form コンポーネントを使用して HTML フォームを処理する場合は、フォームを HTML フォーム フィールド (フィールド値、エラー、およびラベルを含む) としてレンダリングする方法が必要です。 Twig をテンプレート エンジンとして使用する場合、フォーム コンポーネントは豊富な統合を提供します。

To use the integration, you'll need the twig bridge, which provides integration between Twig and several Symfony components:

統合を使用するには、Twig といくつかの Symfony コンポーネント間の統合を提供する twig ブリッジが必要です。
1
$ composer require symfony/twig-bridge

The TwigBridge integration provides you with several Twig Functions that help you render the HTML widget, label, help and errors for each field (as well as a few other things). To configure the integration, you'll need to bootstrap or access Twig and add the FormExtension:

TwigBridge 統合は、各フィールドの HTML ウィジェット、ラベル、ヘルプ、エラー (およびその他のいくつか) をレンダリングするのに役立ついくつかの Twig 関数を提供します。統合を構成するには、Twig をブートストラップまたはアクセスして、FormExtension を追加する必要があります。
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
31
32
33
34
35
36
37
38
39
40
use Symfony\Bridge\Twig\Extension\FormExtension;
use Symfony\Bridge\Twig\Form\TwigRendererEngine;
use Symfony\Component\Form\FormRenderer;
use Symfony\Component\Form\Forms;
use Twig\Environment;
use Twig\Loader\FilesystemLoader;
use Twig\RuntimeLoader\FactoryRuntimeLoader;

// the Twig file that holds all the default markup for rendering forms
// this file comes with TwigBridge
$defaultFormTheme = 'form_div_layout.html.twig';

$vendorDirectory = realpath(__DIR__.'/../vendor');
// the path to TwigBridge library so Twig can locate the
// form_div_layout.html.twig file
$appVariableReflection = new \ReflectionClass('\Symfony\Bridge\Twig\AppVariable');
$vendorTwigBridgeDirectory = dirname($appVariableReflection->getFileName());
// the path to your other templates
$viewsDirectory = realpath(__DIR__.'/../views');

$twig = new Environment(new FilesystemLoader([
    $viewsDirectory,
    $vendorTwigBridgeDirectory.'/Resources/views/Form',
]));
$formEngine = new TwigRendererEngine([$defaultFormTheme], $twig);
$twig->addRuntimeLoader(new FactoryRuntimeLoader([
    FormRenderer::class => function () use ($formEngine, $csrfManager) {
        return new FormRenderer($formEngine, $csrfManager);
    },
]));

// ... (see the previous CSRF Protection section for more information)

// adds the FormExtension to Twig
$twig->addExtension(new FormExtension());

// creates a form factory
$formFactory = Forms::createFormFactoryBuilder()
    // ...
    ->getFormFactory();

1.30

1.30

The Twig\RuntimeLoader\FactoryRuntimeLoader was introduced in Twig 1.30.

Twig\RuntimeLoader\FactoryRuntimeLoader は Twig 1.30 で導入されました。

The exact details of your Twig Configuration will vary, but the goal is always to add the FormExtension to Twig, which gives you access to the Twig functions for rendering forms. To do this, you first need to create a TwigRendererEngine, where you define your form themes (i.e. resources/files that define form HTML markup).

Twig 構成の正確な詳細はさまざまですが、目標は常に FormExtension を Twig に追加することです。これにより、フォームをレンダリングするための Twig 関数にアクセスできるようになります。これを行うには、まず、フォームテーマを定義する TwigRendererEngine を作成する必要があります。 (つまり、フォーム HTML マークアップを定義するリソース/ファイル)。

For general details on rendering forms, see How to Customize Form Rendering.

フォームのレンダリングに関する一般的な詳細については、フォームのレンダリングをカスタマイズする方法を参照してください。

Note

ノート

If you use the Twig integration, read "The Form Component" below for details on the needed translation filters.

Twig 統合を使用する場合は、必要な翻訳フィルターの詳細について、以下の「フォーム コンポーネント」をお読みください。

Translation

If you're using the Twig integration with one of the default form theme files (e.g. form_div_layout.html.twig), there is a Twig filter (trans) that is used for translating form labels, errors, option text and other strings.

デフォルトのフォーム テーマ ファイル (例: form_div_layout.html.twig) の 1 つとの Twig 統合を使用している場合、フォーム ラベル、エラー、オプション テキスト、およびその他の文字列の変換に使用される Twig フィルター (trans) があります。

To add the trans Twig filter, you can either use the built-in TranslationExtension that integrates with Symfony's Translation component, or add the Twig filter yourself, via your own Twig extension.

トランス Twig フィルターを追加するには、Symfony の Translation コンポーネントと統合する組み込みの TranslationExtension を使用するか、独自の Twig 拡張機能を介して自分で Twig フィルターを追加します。

To use the built-in integration, be sure that your project has Symfony's Translation and Config components installed:

組み込みの統合を使用するには、プロジェクトに Symfony の翻訳および構成コンポーネントがインストールされていることを確認してください。
1
$ composer require symfony/translation symfony/config

Next, add the TranslationExtension to your Twig\Environment instance:

次に、Twig\Environment インスタンスに TranslationExtension を追加します。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
use Symfony\Bridge\Twig\Extension\TranslationExtension;
use Symfony\Component\Form\Forms;
use Symfony\Component\Translation\Loader\XliffFileLoader;
use Symfony\Component\Translation\Translator;

// creates the Translator
$translator = new Translator('en');
// somehow load some translations into it
$translator->addLoader('xlf', new XliffFileLoader());
$translator->addResource(
    'xlf',
    __DIR__.'/path/to/translations/messages.en.xlf',
    'en'
);

// adds the TranslationExtension (it gives us trans filter)
$twig->addExtension(new TranslationExtension($translator));

$formFactory = Forms::createFormFactoryBuilder()
    // ...
    ->getFormFactory();

Depending on how your translations are being loaded, you can now add string keys, such as field labels, and their translations to your translation files.

翻訳の読み込み方法に応じて、フィールド ラベルなどの文字列キーとその翻訳を翻訳ファイルに追加できるようになりました。

For more details on translations, see Translations.

翻訳の詳細については、翻訳を参照してください。

Validation

The Form component comes with tight (but optional) integration with Symfony's Validator component. If you're using a different solution for validation, no problem! Take the submitted/bound data of your form (which is an array or object) and pass it through your own validation system.

Form コンポーネントには、Symfony の Validator コンポーネントとの緊密な (ただしオプションの) 統合が付属しています。検証に別のソリューションを使用している場合でも問題ありません。送信/バインドされたフォームのデータ (配列またはオブジェクト) を取得し、独自の検証システムに渡します。

To use the integration with Symfony's Validator component, first make sure it's installed in your application:

Symfony の Validator コンポーネントとの統合を使用するには、まずそれがアプリケーションにインストールされていることを確認してください:
1
$ composer require symfony/validator

If you're not familiar with Symfony's Validator component, read more about it: Validation. The Form component comes with a ValidatorExtension class, which automatically applies validation to your data on bind. These errors are then mapped to the correct field and rendered.

Symfony の Validator コンポーネントに慣れていない場合は、それについて詳しく読んでください: Validation. Form コンポーネントには、バインド時にデータに検証を自動的に適用する ValidatorExtension クラスが付属しています。これらのエラーは、正しいフィールドにマップされ、レンダリングされます。

Your integration with the Validation component will look something like this:

検証コンポーネントとの統合は次のようになります。
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
use Symfony\Component\Form\Extension\Validator\ValidatorExtension;
use Symfony\Component\Form\Forms;
use Symfony\Component\Validator\Validation;

$vendorDirectory = realpath(__DIR__.'/../vendor');
$vendorFormDirectory = $vendorDirectory.'/symfony/form';
$vendorValidatorDirectory = $vendorDirectory.'/symfony/validator';

// creates the validator - details will vary
$validator = Validation::createValidator();

// there are built-in translations for the core error messages
$translator->addResource(
    'xlf',
    $vendorFormDirectory.'/Resources/translations/validators.en.xlf',
    'en',
    'validators'
);
$translator->addResource(
    'xlf',
    $vendorValidatorDirectory.'/Resources/translations/validators.en.xlf',
    'en',
    'validators'
);

$formFactory = Forms::createFormFactoryBuilder()
    // ...
    ->addExtension(new ValidatorExtension($validator))
    ->getFormFactory();

To learn more, skip down to the The Form Component section.

詳細については、フォーム コンポーネント セクションまでスキップしてください。

Accessing the Form Factory

Your application only needs one form factory, and that one factory object should be used to create any and all form objects in your application. This means that you should create it in some central, bootstrap part of your application and then access it whenever you need to build a form.

アプリケーションに必要なフォーム ファクトリは 1 つだけであり、その 1 つのファクトリ オブジェクトを使用してアプリケーション内のすべてのフォーム オブジェクトを作成する必要があります。これは、アプリケーションの中央のブートストラップ部分で作成し、フォームを作成する必要があるときにいつでもアクセスする必要があることを意味します。

Note

ノート

In this document, the form factory is always a local variable called $formFactory. The point here is that you will probably need to create this object in some more "global" way so you can access it from anywhere.

このドキュメントでは、フォーム ファクトリは常に $formFactory というローカル変数です。ここでのポイントは、このオブジェクトをより「グローバル」な方法で作成して、どこからでもアクセスできるようにする必要があるということです。

Exactly how you gain access to your one form factory is up to you. If you're using a service container (like provided with the DependencyInjection component), then you should add the form factory to your container and grab it out whenever you need to. If your application uses global or static variables (not usually a good idea), then you can store the object on some static class or do something similar.

1 つのフォーム ファクトリにアクセスする方法は、ユーザー次第です。サービス コンテナー (DependencyInjection コンポーネントで提供されるものなど) を使用している場合は、フォーム ファクトリをコンテナーに追加し、必要なときに取得する必要があります。アプリケーションがグローバル変数または静的変数を使用する場合 (通常は良い考えではありません)、オブジェクトを静的クラスに格納するか、同様のことを行うことができます。

Creating a simple Form

Tip

ヒント

If you're using the Symfony Framework, then the form factory is available automatically as a service called form.factory, you can inject it as Symfony\Component\Form\FormFactoryInterface. Also, the default base controller class has a createFormBuilder() method, which is a shortcut to fetch the form factory and call createBuilder() on it.

Symfony Framework を使用している場合、フォーム ファクトリは form.factory と呼ばれるサービスとして自動的に利用可能であり、Symfony\Component\Form\FormFactoryInterface として注入できます。また、defaultbase コントローラ クラスには createFormBuilder() メソッドがあります。これは、フォーム ファクトリをフェッチして createBuilder() を呼び出すためのショートカットです。

Creating a form is done via a FormBuilder object, where you build and configure different fields. The form builder is created from the form factory.

フォームの作成は、さまざまなフィールドを構築および構成する FormBuilder オブジェクトを介して行われます。フォーム ビルダーは、フォーム ファクトリから作成されます。
  • Standalone Use
    スタンドアロン使用
  • Framework Use
    フレームワークの使用
1
2
3
4
5
6
7
8
9
10
11
12
13
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\DateType;

// ...

$form = $formFactory->createBuilder()
    ->add('task', TextType::class)
    ->add('dueDate', DateType::class)
    ->getForm();

var_dump($twig->render('new.html.twig', [
    'form' => $form->createView(),
]));

As you can see, creating a form is like writing a recipe: you call add() for each new field you want to create. The first argument to add() is the name of your field, and the second is the fully qualified class name. The Form component comes with a lot of built-in types.

ご覧のとおり、フォームの作成はレシピを書くようなものです。作成する新しいフィールドごとに add() を呼び出します。 add() の最初の引数はフィールドの名前で、2 番目の引数は完全修飾クラス名です。 Formcomponent には多くの組み込み型が付属しています。

Now that you've built your form, learn how to render it and process the form submission.

フォームを作成したので、フォームの送信をレンダリングして処理する方法を学びます。

Setting default Values

If you need your form to load with some default values (or you're building an "edit" form), pass in the default data when creating your form builder:

フォームにいくつかのデフォルト値をロードする必要がある場合 (または「編集」フォームを作成している場合)、フォーム ビルダーを作成するときにデフォルト データを渡します。
  • Standalone Use
    スタンドアロン使用
  • Framework Use
    フレームワークの使用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\DateType;

// ...

$defaults = [
    'dueDate' => new \DateTime('tomorrow'),
];

$form = $formFactory->createBuilder(FormType::class, $defaults)
    ->add('task', TextType::class)
    ->add('dueDate', DateType::class)
    ->getForm();

Tip

ヒント

In this example, the default data is an array. Later, when you use the data_class option to bind data directly to objects, your default data will be an instance of that object.

この例では、デフォルトのデータは配列です。後で、data_class オプションを使用してデータをオブジェクトに直接バインドすると、デフォルト データはそのオブジェクトのインスタンスになります。

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:

フォームが作成されたので、次のステップはそれをレンダリングすることです。これは、特別なフォームの「ビュー」オブジェクトをテンプレートに渡し (上記のコントローラーの $form->createView() に注目してください)、一連のフォーム ヘルパー関数を使用することによって行われます。
1
2
3
4
5
{{ form_start(form) }}
    {{ form_widget(form) }}

    <input type="submit"/>
{{ form_end(form) }}

That's it! By printing form_widget(form), each field in the form is rendered, along with a label and error message (if there is one). While this is convenient, 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 form customization article.

それでおしまい! form_widget(form) を出力すると、フォームの各フィールドが、ラベルとエラー メッセージ (存在する場合) とともにレンダリングされます。これは便利ですが、あまり柔軟ではありません (まだ)。通常、フォームの外観を制御できるように、各フォーム フィールドを個別にレンダリングする必要があります。その方法については、フォームのカスタマイズに関する記事で学習します。

Changing a Form's Method and Action

By default, a form is submitted to the same URI that rendered the form with an HTTP POST request. This behavior can be changed using the FormType Field and FormType Field options (the method option is also used by handleRequest() to determine whether a form has been submitted):

デフォルトでは、フォームは、HTTP POST リクエストでフォームをレンダリングしたのと同じ URI に送信されます。この動作は、FormType Field および FormType Field オプションを使用して変更できます (メソッド オプションは、フォームが送信されたかどうかを判断するために handleRequest() によっても使用されます)。
  • Standalone Use
    スタンドアロン使用
  • Framework Use
    フレームワークの使用
1
2
3
4
5
6
7
8
9
10
use Symfony\Component\Form\Extension\Core\Type\FormType;

// ...

$formBuilder = $formFactory->createBuilder(FormType::class, null, [
    'action' => '/search',
    'method' => 'GET',
]);

// ...

Handling Form Submissions

To handle form submissions, use the handleRequest() method:

  • Standalone Use
    スタンドアロン使用
  • Framework Use
    フレームワークの使用
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
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\TextType;

// ...

$form = $formFactory->createBuilder()
    ->add('task', TextType::class)
    ->add('dueDate', DateType::class)
    ->getForm();

$request = Request::createFromGlobals();

$form->handleRequest($request);

if ($form->isSubmitted() && $form->isValid()) {
    $data = $form->getData();

    // ... perform some action, such as saving the data to the database

    $response = new RedirectResponse('/task/success');
    $response->prepare($request);

    return $response->send();
}

// ...

Caution

注意

The form's createView() method should be called after handleRequest() is called. Otherwise, when using form events, changes done in the *_SUBMIT events won't be applied to the view (like validation errors).

フォームの createView() メソッドは、handleRequest() が呼び出された後に呼び出される必要があります。そうしないと、フォーム イベントを使用するときに、*_SUBMIT イベントで行われた変更がビューに適用されません (検証エラーなど)。

This defines a common form "workflow", which contains 3 different possibilities:

これは、3 つの異なる可能性を含む共通のフォーム「ワークフロー」を定義します。
  1. On the initial GET request (i.e. when the user "surfs" to your page), build your form and render it;

    最初の GET リクエスト (つまり、ユーザーがページに「サーフィン」したとき) で、フォームを作成してレンダリングします。

    If the request is a POST, process the submitted data (via handleRequest()).

    リクエストが POST の場合、送信されたデータを (handleRequest() を介して) 処理します。

    Then:

  2. if the form is invalid, re-render the form (which will now contain errors);
    フォームが無効な場合は、フォームを再レンダリングします (エラーが含まれます)。
  3. if the form is valid, perform some action and redirect.
    フォームが有効な場合は、何らかのアクションを実行してリダイレクトします。

Luckily, you don't need to decide whether or not a form has been submitted. Just pass the current request to the handleRequest() method. Then, the Form component will do all the necessary work for you.

幸いなことに、フォームが送信されたかどうかを判断する必要はありません。現在のリクエストを handleRequest() メソッドに渡すだけです。次に、フォーム コンポーネントが必要なすべての作業を行います。

Form Validation

The easiest way to add validation to your form is via the constraints option when building each field:

フォームにバリデーションを追加する最も簡単な方法は、各フィールドを作成するときに制約オプションを使用することです。
  • Standalone Use
    スタンドアロン使用
  • Framework Use
    フレームワークの使用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Type;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\DateType;

$form = $formFactory->createBuilder()
    ->add('task', TextType::class, [
        'constraints' => new NotBlank(),
    ])
    ->add('dueDate', DateType::class, [
        'constraints' => [
            new NotBlank(),
            new Type(\DateTime::class),
        ],
    ])
    ->getForm();

When the form is bound, these validation constraints will be applied automatically and the errors will display next to the fields on error.

フォームがバインドされると、これらの検証制約が自動的に適用され、エラーが発生したフィールドの横にエラーが表示されます。

Note

ノート

For a list of all of the built-in validation constraints, see Validation Constraints Reference.

組み込みの検証制約のすべてのリストについては、「検証制約リファレンス」を参照してください。

Accessing Form Errors

You can use the getErrors() method to access the list of errors. It returns a FormErrorIterator instance:

getErrors() メソッドを使用して、エラーのリストにアクセスできます。 FormErrorIterator インスタンスを返します。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
$form = ...;

// ...

// a FormErrorIterator instance, but only errors attached to this
// form level (e.g. global errors)
$errors = $form->getErrors();

// a FormErrorIterator instance, but only errors attached to the
// "firstName" field
$errors = $form['firstName']->getErrors();

// a FormErrorIterator instance in a flattened structure
// use getOrigin() to determine the form causing the error
$errors = $form->getErrors(true);

// a FormErrorIterator instance representing the form tree structure
$errors = $form->getErrors(true, false);

Clearing Form Errors

Any errors can be manually cleared using the clearErrors() method. This is useful when you'd like to validate the form without showing validation errors to the user (i.e. during a partial AJAX submission or dynamic form modification).

すべてのエラーは、clearErrors() メソッドを使用して手動でクリアできます。これは、ユーザーに検証エラーを表示せずにフォームを検証したい場合 (つまり、部分的な AJAX 送信または動的フォーム変更中) に役立ちます。

Because clearing the errors makes the form valid, clearErrors() should only be called after testing whether the form is valid.

エラーをクリアするとフォームが有効になるため、clearErrors() はフォームが有効かどうかをテストした後にのみ呼び出す必要があります。

Learn more