我正在尝试创建,渲染,提交和验证没有实体类的表单。
为此,我使用FormBuilderInterface创建了FormType类。但是当我尝试在树枝模板中渲染表单时,我总是只获得带有令牌输入的表单,但没有其他字段。
我的代码如下:
类型定义:
<?php
namespace AppBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Length;
class VendorLeadType extends AbstractType{
/**
* @param FormBilderInterface $builder
* @param array $options
*/
public function buidForm(FormBuilderInterface $builder, array $options){
$builder
->add('email', EmailType::class, [
'constraints' => [
new Email(),
new Length(['max'=>'100'])
]
])
->add('name', TextType::class, [
'constraints' => [
new NotBlank(),
new Length(['max'=>'100'])
]
])
->add('phone', TextType::class, [
'constraints' => [
new NotBlank(),
new Length(['max'=>'100'])
]
])
;
}
}
控制器:
<?php
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use AppBundle\Form\VendorLeadType;
class DefaultController extends Controller
{
/**
* @Route("/", name="homepage")
*/
public function indexAction(Request $request)
{
$form = $this->createForm(VendorLeadType::class);
return $this->render('index.html.twig', [
'form' => $form->createView()
]);
}
}
Twig模板
{% extends 'base.html.twig' %}
{% block body %}
{{ form(form) }}
{% endblock %}
输出html
<form name="vendor_lead" method="post">
<div id="vendor_lead">
<input type="hidden" id="vendor_lead__token" name="vendor_lead[_token]" value="...">
</div>
</form>
知道我做错了吗?
答案 0 :(得分:1)
首先,您的VendorLeadType脚本中有拼写错误。你需要修复`public function buildForm'的拼写。
要让表单变量进入控制器,您需要告诉symfony不要期望任何表单变量通过向您的参数添加'mapped' => false,
来映射到实体:
$builder
->add('email', EmailType::class, [
'mapped' => false,
'constraints' => [
new Email(),
new Length(['max'=>'100'])
]
])
->add('name', TextType::class, [
'mapped' => false,
'constraints' => [
new NotBlank(),
new Length(['max'=>'100'])
]
])
->add('phone', TextType::class, [
'mapped' => false,
'constraints' => [
new NotBlank(),
new Length(['max'=>'100'])
]
])
;