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

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 email 標籤渲染。其語法如下:

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 range 標籤渲染。其語法如下:

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', 
)); 

這裡,Widget 是渲染欄位的基本方法。

它執行以下功能。

  • choice - 渲染三個選擇輸入。選擇的順序在 format 選項中定義。

  • text - 渲染三個文字型別輸入欄位(月、日、年)。

  • single_text - 渲染單個日期型別輸入欄位。使用者的輸入將根據 format 選項進行驗證。

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

這是一個特殊的欄位“組”,它建立兩個必須匹配值的相同欄位。其語法如下:

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

一個多用途欄位,用於允許使用者“選擇”一個或多個選項。它可以渲染為選擇標籤、單選按鈕或複選框。其語法如下:

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'), 
))

表單輔助函式

表單輔助函式是 Twig 函式,用於在模板中輕鬆建立表單。

form_start

返回指向有效操作、路由或 URL 的 HTML 表單標籤。其語法如下:

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

form_end

關閉使用 form_start 建立的 HTML 表單標籤。其語法如下:

{{ form_end(form) }} 

textarea

返回一個 textarea 標籤,可選地用內聯富文字 JavaScript 編輯器包裝。

checkbox

返回一個 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'); 

label

返回帶有指定引數的標籤。

radiobutton

返回一個 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'); 

select

返回一個用世界各國填充的選擇標籤。其語法如下:

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

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/new.html.twig', array( 
            'form' => $form->createView(), 
         )); 
   } 
}              

步驟 4:渲染檢視

移動到“app/Resources/views/student/”目錄,建立“new.html.twig”檔案並在其中新增以下更改。

{% extends 'base.html.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,“https://:8000/student/new”,它會產生以下結果。

結果

Rendering View
廣告
© . All rights reserved.