Symfony-forms

提供:Dev Guides
移動先:案内検索

symfony-フォーム

symfonyは、HTMLフォームを簡単かつ安全に処理するためのさまざまな組み込みタグを提供します。 Symfonyのフォームコンポーネントは、フォームの作成と検証プロセスを実行します。 モデルとビューレイヤーを接続します。 事前定義されたモデルから本格的なhtmlフォームを作成するための一連のフォーム要素を提供します。 この章では、フォームについて詳しく説明します。

フォームフィールド

symfonyフレームワークAPIは、フィールドタイプの大規模なグループをサポートします。 各フィールドタイプについて詳しく見ていきましょう。

FormType

Symfonyフレームワークでフォームを生成するために使用されます。 その構文は次のとおりです-

use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\FormType;
//...

$builder = $this->createFormBuilder($studentinfo);
$builder
   ->add('title', TextType::class);
ここで、$ * studentinfo はStudentタイプのエンティティです。 *createFormBuilder は、HTMLフォームを作成するために使用されます。 addメソッドは、フォーム内の入力要素を*追加*するために使用されます。 title は、学生のタイトルプロパティを指します。 *TextType
class* はhtmlテキストフィールドを指します。 symfonyはすべてのhtml要素にクラスを提供します。

テキストタイプ

TextTypeフィールドは、最も基本的な入力テキストフィールドを表します。 その構文は次のとおりです-

use Symfony\Component\Form\Extension\Core\Type\TextType;
$builder->add(‘name’, TextType::class);

ここでは、名前はエンティティにマッピングされます。

TextareaType

textarea HTML要素をレンダリングします。 その構文は次のとおりです-

use Symfony\Component\Form\Extension\Core\Type\TextareaType;
$builder->add('body', TextareaType::class, array(
   'attr' => array('class' => 'tinymce'),
));

EmailType

EmailTypeフィールドは、HTML5電子メールタグを使用してレンダリングされるテキストフィールドです。 その構文は次のとおりです-

use Symfony\Component\Form\Extension\Core\Type\EmailType;
$builder->add('token', EmailType::class, array(
   'data' => 'abcdef', ));

PasswordType

PasswordTypeフィールドは、入力パスワードテキストボックスを表示します。 その構文は次のとおりです-

use Symfony\Component\Form\Extension\Core\Type\PasswordType;
$bulder->add('password', PasswordType::class);

RangeType

RangeTypeフィールドは、HTML5範囲タグを使用してレンダリングされるスライダーです。 その構文は次のとおりです-

use Symfony\Component\Form\Extension\Core\Type\RangeType;
//...
$builder->add('name', RangeType::class, array(
   'attr' => array(
      'min' => 100,
      'max' => 200
   )
));

PercentType

PercentTypeは、入力テキストフィールドをレンダリングし、パーセンテージデータの処理に特化しています。 その構文は次のとおりです-

use Symfony\Component\Form\Extension\Core\Type\PercentType;
//...
$builder->add('token', PercentType::class, array(
   'data' => 'abcdef',
));

DateType

日付形式をレンダリングします。 その構文は次のとおりです-

use Symfony\Component\Form\Extension\Core\Type\DateType;
//...
$builder->add(‘joined’, DateType::class, array(
   'widget' => 'choice',
));

ここで、ウィジェットはフィールドをレンダリングする基本的な方法です。

次の機能を実行します。

  • choice -3つの選択入力をレンダリングします。 選択の順序は、formatオプションで定義されます。
  • text -テキストタイプ(月、日、年)の3つのフィールド入力をレンダリングします。
  • single_text -日付型の単一の入力をレンダリングします。 ユーザーの入力は、形式オプションに基づいて検証されます。

CheckboxType

単一の入力チェックボックスを作成します。 これは、ブール値を持つフィールドに対して常に使用する必要があります。 その構文は次のとおりです-

use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
//...
$builder-<add(‘sports’, CheckboxType::class, array(
   'label'    =< ‘Are you interested in sports?’,
   'required' =< false,
));

RadioType

単一のラジオボタンを作成します。 ラジオボタンが選択されている場合、フィールドは指定された値に設定されます。 その構文は次のとおりです-

use Symfony\Component\Form\Extension\Core\Type\RadioType;
//...
$builder->add('token', RadioType::class, array(
   'data' => 'abcdef',
));

ラジオボタンのチェックを外すことはできません。値は、同じ名前の別のラジオボタンがチェックされた場合にのみ変化することに注意してください。

RepeatedType

これは、値が一致する必要がある2つの同一のフィールドを作成する特別なフィールド「グループ」です。 その構文は次のとおりです-

use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;

//...
$builder->add('password', RepeatedType::class, array(
   'type' => PasswordType::class,
   'invalid_message' => 'The password fields must match.',
   'options' => array('attr' => array('class' => 'password-field')),
   'required' => true,
   'first_options'  => array('label' => 'Password'),
   'second_options' => array('label' => 'Repeat Password'),
));

これは主に、ユーザーのパスワードまたはメールを確認するために使用されます。

ButtonType

シンプルなクリック可能なボタン。 その構文は次のとおりです-

use Symfony\Component\Form\Extension\Core\Type\ButtonType;
//...
$builder->add('save', ButtonType::class, array(
   'attr' => array('class' => 'save'),
));

ResetType

すべてのフィールドを初期値にリセットするボタン。 その構文は次のとおりです-

use Symfony\Component\Form\Extension\Core\Type\ResetType;
//...
$builder->add('save', ResetType::class, array(
   'attr' => array('class' => 'save'),
));

ChoiceType

多目的フィールドは、ユーザーが1つ以上のオプションを「選択」できるようにするために使用されます。 選択タグ、ラジオボタン、またはチェックボックスとしてレンダリングできます。 その構文は次のとおりです-

use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
//...
$builder->add(‘gender’, ChoiceType::class, array(
   'choices'  => array(
      ‘Male’ => true,
      ‘Female’ => false,
   ),
));

SubmitType

フォームデータを送信するには、送信ボタンを使用します。 その構文は次のとおりです-

use Symfony\Component\Form\Extension\Core\Type\SubmitType;
//...
$builder->add('save', SubmitType::class, array(
   'attr' => array('class' => 'save'),
))

フォームヘルパー関数

フォームヘルパー関数は、テンプレートでフォームを簡単に作成するために使用される小枝関数です。

form_start

有効なアクション、ルート、またはURLを指すHTMLフォームタグを返します。 その構文は次のとおりです-

{{ form_start(form, {'attr': {'id': 'form_person_edit'}}) }}

form_end

form_startを使用して作成されたHTMLフォームタグを閉じます。 その構文は次のとおりです-

{{ form_end(form) }}

テキストエリア

オプションでインラインリッチテキストJavaScriptエディターでラップされたtextareaタグを返します。

チェックボックス

type =“ checkbox”のXHTML準拠の入力タグを返します。 その構文は次のとおりです-

echo checkbox_tag('choice[]', 1);
echo checkbox_tag('choice[]', 2);
echo checkbox_tag('choice[]', 3);
echo checkbox_tag('choice[]', 4);

input_password_tag

type =“ password”のXHTML準拠の入力タグを返します。 その構文は次のとおりです-

echo input_password_tag('password');
echo input_password_tag('password_confirm');

input_tag

type =“ text”のXHTML準拠の入力タグを返します。 その構文は次のとおりです-

echo input_tag('name');

ラベル

指定されたパラメーターを持つラベルタグを返します。

ラジオボタン

type =“ radio”のXHTML準拠の入力タグを返します。 その構文は次のとおりです-

echo ' Yes '.radiobutton_tag(‘true’, 1);
echo ' No '.radiobutton_tag(‘false’, 0);

reset_tag

type =“ reset”のXHTML準拠の入力タグを返します。 その構文は次のとおりです-

echo reset_tag('Start Over');

選択する

世界のすべての国が入力された選択タグを返します。 その構文は次のとおりです-

echo select_tag(
   'url', options_for_select($url_list),
   array('onChange' => 'Javascript:this.form.submit();'));

提出する

type =“ submit”のXHTML準拠の入力タグを返します。 その構文は次のとおりです-

echo submit_tag('Update Record');

次のセクションでは、フォームフィールドを使用してフォームを作成する方法を学習します。

学生フォームアプリケーション

Symfonyフォームフィールドを使用して、簡単な学生詳細フォームを作成しましょう。 これを行うには、次の手順に従う必要があります-

ステップ1:Symfonyアプリケーションを作成する

次のコマンドを使用して、Symfonyアプリケーション formsample を作成します。

symfony new formsample

エンティティは通常、「src/AppBundle/Entity/」ディレクトリの下に作成されます。

ステップ2:エンティティを作成する

「src/AppBundle/Entity/」ディレクトリの下に「StudentForm.php」ファイルを作成します。 ファイルに次の変更を追加します。

StudentForm.php

<?php
namespace AppBundle\Entity;

class StudentForm {
   private $studentName;
   private $studentId;
   public $password;
   private $address;
   public $joined;
   public $gender;
   private $email;
   private $marks;
   public $sports;

   public function getStudentName() {
      return $this->studentName;
   }
   public function setStudentName($studentName) {
      $this->studentName = $studentName;
   }
   public function getStudentId() {
      return $this->studentId;
   }
   public function setStudentId($studentid) {
      $this->studentid = $studentid;
   }
   public function getAddress() {
      return $this->address;
   }
   public function setAddress($address) {
      $this->address = $address;
   }
   public function getEmail() {
      return $this->email;
   }
   public function setEmail($email) {
      $this->email = $email;
   }
   public function getMarks() {
      return $this->marks;
   }
   public function setMarks($marks) {
      $this->marks = $marks;
   }
}

ステップ3:StudentControllerを追加する

ディレクトリ「src/AppBundle/Controller」に移動し、「StudentController.php」ファイルを作成して、次のコードを追加します。

StudentController.php

<?php
namespace AppBundle\Controller;

use AppBundle\Entity\StudentForm;
use AppBundle\Form\FormValidationType;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\RangeType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\ButtonType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\PercentType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;

class StudentController extends Controller {
  /* *
     * @Route("/student/new")
   */
   public function newAction(Request $request) {
      $stud = new StudentForm();
      $form = $this->createFormBuilder($stud)
         ->add('studentName', TextType::class)
         ->add('studentId', TextType::class)
         ->add('password', RepeatedType::class, array(
            'type' => PasswordType::class,
            'invalid_message' => 'The password fields
            must match.', 'options' => array('attr' => array('class' => 'password-field')),
            'required' => true, 'first_options'  => array('label' => 'Password'),
            'second_options' => array('label' => 'Re-enter'),
         ))

         ->add('address', TextareaType::class)
         ->add('joined', DateType::class, array(
               'widget' => 'choice',
         ))

         ->add('gender', ChoiceType::class, array(
            'choices'  => array(
               'Male' => true,
               'Female' => false,
            ),
         ))

         ->add('email', EmailType::class)
         ->add('marks', PercentType::class)
         ->add('sports', CheckboxType::class, array(
            'label'    => 'Are you interested in sports?', 'required' => false,
         ))

         ->add('save', SubmitType::class, array('label' => 'Submit'))
         ->getForm();
         return $this->render('student/newl.twig', array(
            'form' => $form->createView(),
         ));
   }
}

ステップ4:ビューをレンダリングする

「app/Resources/views/student/」ディレクトリに移動し、「newl.twig」ファイルを作成して、次の変更を追加します。

{% extends 'basel.twig' %}
{% block stylesheets %}
<style>
   #simpleform {
      width:600px;
      border:2px solid grey;
      padding:14px;
   }
   #simpleform label {
      font-size:14px;
      float:left;
      width:300px;
      text-align:right;
      display:block;
   }
   #simpleform span {
      font-size:11px;
      color:grey;
      width:100px;
      text-align:right;
      display:block;
   }
   #simpleform input {
      border:1px solid grey;
      font-family:verdana;
      font-size:14px;
      color:light blue;
      height:24px;
      width:250px;
      margin: 0 0 10px 10px;
   }
   #simpleform textarea {
      border:1px solid grey;
      font-family:verdana;
      font-size:14px;
      color:light blue;
      height:120px;
      width:250px;
      margin: 0 0 20px 10px;
   }
   #simpleform select {
      margin: 0 0 20px 10px;
   }
   #simpleform button {
      clear:both;
      margin-left:250px;
      background: grey;
      color:#FFFFFF;
      border:solid 1px #666666;
      font-size:16px;
   }
</style>

{% endblock %}
   {% block body %}
   <h3>Student details:</h3>
   <div id="simpleform">
      {{ form_start(form) }}
      {{ form_widget(form) }}
      {{ form_end(form) }}
   </div>
{% endblock %}

ここで、URL「http://localhost:8000/student/new」をリクエストすると、次の結果が生成されます。

結果

レンダリングビュー