根本不使用 Symfony,并生成自己的令牌?
在制作表单时,您实际上并不需要使用 Symfony 表单主题。我自己,我总是建立自己的表单标签。
- 您想自定义您的选择吗?也可以做
- 您想使用不在实体中的字段,也可以这样做...
Symfony 表单并没有你想象的那么严格。
你很可能不知道这件事的“诀窍”。
控制器
public function customFormAction(Request $request) {
$form=$this->createFormBuilder()
->setAction($this->generateUrl('route_name'))
->setMethod('POST')
->add("customField", ChoiceType::class, array(
'choices'=>array(
'1'=>'Choice 1',
'2'=>'Choice 2',
'3'=>'Choice 2',
),
'required'=>true,
'mapped'=>false, //Isn't mapped to any entity
))
->getForm();
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()) {
$customField=$form->get('customField')->getData();
//do your stuff
}
return $this->render('route_name', array(
'form'=>$form->createView(),
));
}
树枝视图
<form action="{{ form.vars.action }}" method="{{ form.vars.method }}">
<div class="input-field">
<select id="{{ form.customField.vars.id }}" name="{{ form.customField.vars.full_name }}" class="my_classes">
{% for option in form.customField.vars.choices %}
<option data-attr="my_attributes" value="{{ option.value }}">{{ option.label }}</option>
{% endfor %}
</select>
</div>
<input name="{{ form._token.vars.full_name }}" value="{{ form._token.vars.value }}" type="hidden">
</form>
有了这个,我几乎不使用任何树枝模板,我仍然有一个 CSRF 令牌,Symfony 几乎不处理表单(它只会检查 CSRF 令牌)