[040] Symfony4 表单入门 Part01
2019-03-17 本文已影响0人
观星汉
使用 Symfony 来实现一个注册表单, 这里我们使用 Bootstrap4 快速实现一个简单的注册表单如下:
SignUp.png
HTML源代码非常简单:
<div class="form-box p-3 w-100 bg-white rounded shadow">
<!-- Form Start -->
<div class="logo mb-3">
<div class="col-md-12 text-center">
<h1>Sign Up</h1>
</div>
</div>
<form action="" method="post" name="regist">
<div class="form-group">
<label for="name" class="small">Name</label>
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text">
<i class="fas fa-user"></i>
</div>
</div>
<input type="text" name="name" id="name" class="form-control" placeholder="Enter name">
</div>
<div class="text-danger small"></div>
</div>
<div class="form-group">
<label for="email" class="small">Email address</label>
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text">
<i class="far fa-envelope"></i>
</div>
</div>
<input type="text" name="email" id="email" class="form-control" placeholder="Enter email">
</div>
<div class="text-danger small"></div>
</div>
<div class="form-group">
<label for="password" class="small">Password</label>
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text">
<i class="fas fa-key"></i>
</div>
</div>
<input type="password" name="password" id="password" class="form-control" placeholder="Enter Password">
</div>
<div class="text-danger small"></div>
</div>
<div class="form-group text-center ">
<button type="submit" class="btn btn-block mybtn btn-primary tx-tfm rounded-pill">Get Started For Free</button>
</div>
<div class="form-group">
<div class="py-2 position-relative text-black-50">
<hr style="height: 1px; margin-top: 0px; margin-bottom: 0px;">
<span class="bg-white d-block position-absolute text-center" style="left: 50%; top: -5px; margin-left: -25px; width: 50px;">or</span>
</div>
</div>
<div class="form-group">
<p class="text-center small">Already have an account? <a href="#" id="signup">Sign in</a></p>
</div>
</form>
<!-- Form End -->
</div>
现在用 symfony 来完成一个注册操作. 先安装一下 form 包.
composer require symfony/form
创建一个控制器 DefaultController
, 添加方法: signUp()
来处理注册页面.
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
class DefaultController extends AbstractController
{
/**
* @Route("/sign-up.html", name="url_sign-up")
*
* @param Request $request
* @return \Symfony\Component\HttpFoundation\Response
*/
public function signUp(Request $request)
{
$formBuilder = $this->createFormBuilder();
$formBuilder->add('name', TextType::class);
$formBuilder->add('email', EmailType::class);
$formBuilder->add('password', PasswordType::class);
$formBuilder->add('save', SubmitType::class);
$form = $formBuilder->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$data = $form->getData();
dump($data);
} else {
dump($form->getErrors());
}
return $this->render('default/sign-up.html.twig', [
'form' => $form->createView(),
]);
}
}
在模板文件里直接输出 form
{# template/default/signup.htm.twig #}
{{ form(form) }}
表单渲染出来非常的干净, 纯 Form 元素.
<form name="form" method="post">
<div id="form">
<div>
<label for="form_name" class="required">Name</label>
<input type="text" id="form_name" name="form[name]" required="required" />
</div>
<div>
<label for="form_email" class="required">Email</label>
<input type="email" id="form_email" name="form[email]" required="required" />
</div>
<div>
<label for="form_password" class="required">Password</label>
<input type="password" id="form_password" name="form[password]" required="required" />
</div>
<div>
<button type="submit" id="form_save" name="form[save]">Save</button>
</div>
<input type="hidden" id="form__token" name="form[_token]" value="OH_rtM7xZeK3f97MiwonQixEJza15Nm4i6nK8LPGCsE" />
</div>
</form>
表单提交后, 可以打印到用户输入的数据是一个数组. 大概类似这样:
[
"name" => "Hill"
"email" => "ssdf@sdf"
"passwd" => "1212"
]
如果直接使用 {{ form(form) }}
这样输出是很丑的, 通常我们网页美化是很重要的. 所以在创建表单的时候更多的是详细输出到设计好的 dom 结构中去. 为了让 sf 的 form 创建的表单和我们在之前静态表单一致, 我们需要定制化输出传入到实体的表单对象. 把模板代码改成下面的样子:
{# template/default/sign-up.html.twig #}
{% extends 'base.html.twig' %}
{% block title %} Sign up {% endblock %}
{% block body %}
<section class="main flex-grow-1">
<div class="container h-100">
<div class="row h-100">
<div class="col-md-4 mx-auto d-flex flex-colum align-items-center">
<div class="form-box p-3 w-100 bg-white rounded shadow">
<!-- Form Start -->
<div class="logo mb-3">
<div class="col-md-12 text-center">
<h1>Sign Up</h1>
</div>
</div>
{{ form_start(form, {'method': 'POST', 'attr': {'novalidate': 'novalidate'}}) }}
<div class="form-group">
{{ form_label(form.name, 'Name', {'label_attr': {'class': 'small'}}) }}
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text">
<i class="fas fa-user"></i>
</div>
</div>
{{ form_widget(form.name, {'attr': {'class': 'form-control', 'placeholder': 'Enter name'}}) }}
</div>
<div class="text-danger small">{{ form_errors(form.name) }}</div>
</div>
<div class="form-group">
{{ form_label(form.email, 'Email address', {'label_attr': {'class': 'small'}}) }}
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text">
<i class="far fa-envelope"></i>
</div>
</div>
{{ form_widget(form.email, {'attr': {'class': 'form-control', 'placeholder': 'Enter email'}}) }}
<!-- <input type="text" name="email" id="email" class="form-control" placeholder="Enter email"> -->
</div>
<div class="text-danger small">{{ form_errors(form.email) }}</div>
</div>
<div class="form-group">
{{ form_label(form.passwd, 'Password', {'label_attr': {'class': 'small'}}) }}
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text">
<i class="fas fa-key"></i>
</div>
</div>
{{ form_widget(form.passwd, {'attr': {'class': 'form-control', 'placeholder': 'Enter password'}}) }}
<!-- <input type="password" name="password" id="password" class="form-control" placeholder="Enter Password"> -->
</div>
<div class="text-danger small">{{ form_errors(form.passwd) }}</div>
</div>
<div class="form-group text-center ">
{{ form_widget(form.save, {'attr': {'class': 'btn btn-block mybtn btn-primary tx-tfm rounded-pill'}, 'label': 'Get Started For Free'}) }}
<!-- <input type="submit" class="btn btn-block mybtn btn-primary tx-tfm rounded-pill" value="Get Started For Free"> -->
</div>
<div class="form-group">
<div class="py-2 position-relative text-black-50">
<hr style="height: 1px; margin-top: 0px; margin-bottom: 0px;">
<span class="bg-white d-block position-absolute text-center" style="left: 50%; top: -5px; margin-left: -25px; width: 50px;">or</span>
</div>
</div>
<div class="form-group">
<p class="text-center small">Already have an account? <a href="{{ path('url_login') }}">Sign in</a></p>
</div>
{{ form_end(form) }}
<!-- Form End -->
</div>
</div>
</div>
</div>
</section>
{% endblock %}
这样一来, 表单就会按设计的结构展现, 符合预期要求. 这里使用了 form_start
, form_end
, form_label
, form_widget
来拆开显示表单.
现在来继续了解 Symfony/form
, 在控制器中. 表单使用 createFormBuilder()
来创建, 在创建表单时候, 可以传入一个实体对象, 这样就会自动把用户提交的信息并入到实体对象中. 简单的改造一下注册的接口, 实现注册信息保存到数据库中, 然后返回首页
// ...
public function signUp(Request $request)
{
$user = new User();
$formBuilder = $this->createFormBuilder($user);
$formBuilder->add('name', TextType::class);
$formBuilder->add('email', EmailType::class);
$formBuilder->add('passwd', PasswordType::class);
$formBuilder->add('save', SubmitType::class);
$form = $formBuilder->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$data = $form->getData();
if (!$data instanceof User) {
throw $this->createNotFoundException('Request page not founded.');
}
$data->setExpired(new \DateTime());
$data->setResetPasswdExpired(new \DateTime());
$data->setCreated(new \DateTime());
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($data);
$entityManager->flush();
return $this->redirectToRoute('url_home');
//dump($data);
} else {
dump($form->getErrors());
}
return $this->render('default/sign-up.html.twig', [
'form' => $form->createView(),
]);
}
最简单的 Form 使用这样就完成了. 接下来了解一下项目中非常重要的表单验证.