在 表單入門 Part02 部分, 表單是直接在 Controller 里的. 通常這樣的代碼是不優(yōu)雅的. 看起來(lái)也不是很專業(yè). 我們把表單創(chuàng)建單獨(dú)的用一個(gè) Class
來(lái)實(shí)現(xiàn). 這樣會(huì)比較美觀和方便維護(hù)與重用.
使用 symfony/make
包提供的輔助創(chuàng)建表單類指令 make:form
快速的創(chuàng)建一個(gè)表單類
$ bin/console make:form
The name of the form class (e.g. OrangeChefType):
> UserType
The name of Entity or fully qualified model class name that the new form will be bound to (empty for none):
> User
created: src/Form/UserType.php
Success!
Next: Add fields to your form and start using it.
把創(chuàng)建好的表單類: UserType 進(jìn)行PHP代碼完善一下. 看起來(lái)像這樣:
<?php
namespace App\Form;
use App\Entity\User;
use Symfony\Component\Form\AbstractType;
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\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class UserType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('email', EmailType::class, ['empty_data' => ''])
->add('passwd', PasswordType::class, ['empty_data' => ''])
->add('name', TextType::class, ['empty_data' => ''])
->add('save', SubmitType::class)
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => User::class,
]);
}
}
這樣, 在 Controller 中的代碼就會(huì)非常的簡(jiǎn)潔了. 修改成這樣:
// ... code
public function signUp(Request $request)
{
$user = new User();
// $formBuilder = $this->createFormBuilder($user);
// $formBuilder->add('name', TextType::class, ['empty_data' => '']);
// $formBuilder->add('email', EmailType::class, ['empty_data' => '']);
// $formBuilder->add('passwd', PasswordType::class, ['empty_data' => '']);
// $formBuilder->add('save', SubmitType::class);
// $form = $formBuilder->getForm();
$form = $this->createForm(UserType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// ... code
Form 的創(chuàng)建單獨(dú)轉(zhuǎn)成 Class 后. 和之前的功能實(shí)現(xiàn)是一樣的效果.