- Symfony 教程
- Symfony - 首页
- Symfony - 简介
- Symfony - 安装
- Symfony - 架构
- Symfony - 组件
- Symfony - 服务容器
- Symfony - 事件 & 事件监听器
- Symfony - 表达式
- Symfony - Bundles
- 创建简单的Web应用程序
- Symfony - 控制器
- Symfony - 路由
- Symfony - 视图引擎
- Symfony - Doctrine ORM
- Symfony - 表单
- Symfony - 验证
- Symfony - 文件上传
- Symfony - Ajax 控制
- Cookie & Session 管理
- Symfony - 国际化
- Symfony - 日志记录
- Symfony - 邮件管理
- Symfony - 单元测试
- Symfony - 高级概念
- Symfony - REST 版本
- Symfony - CMF 版本
- 完整的可运行示例
- Symfony 有用资源
- Symfony - 快速指南
- Symfony - 有用资源
- Symfony - 讨论
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”,它会产生以下结果。
结果