对于我的项目,我使用了 Symfony 框架。我需要使用选择选项为我的表单生成一个列表。
这是代码:
形式:
<form method="post" {{ form_enctype(form)}} action="{{ path('my_path')}}">
{{form_errors(form)}}
<div name="nature">
{{form_label(form.nature,"(*) Nature sample")}}
{{form_errors(form.nature)}}
<select name="nature" id="nature">
<option value ="Other">Other</option>
<option value ="Adn">ADN</option>
</select>
</div>
{{ form_widget(form) }}
<input type="submit" value="Next" class="btn btn-primary" />
</form>
Run Code Online (Sandbox Code Playgroud)
表格类型:
public function buildForm(FormBuilderInterface $builder, array $options){
$builder
->add('nature')
->add('origin');
}
Run Code Online (Sandbox Code Playgroud)
控制器:
public function madeDemandAction($id, Request $request)
{
$em = $this-> getDoctrine() -> getManager();
$sample = new Sample();
$repository = $this ->getDoctrine()
->getManager()
->getRepository('BsBundle:Demand')
->find($id);
$demand = $repository;
$form=$this ->createForm(new SampleType, $sample);
if($request ->getMethod() == 'POST')
{
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid())
{
dump($request);
$inforequest=$form->getData();
dump($inforequest);
$em = $this->getDoctrine()->getManager();
$em->persist($inforequest);
$em->flush();
return $this->redirect($this->generateUrl('homepage'));
}
}
return $this ->render('bs_connected/human_demand.html.twig'
, array('form'=>$form ->createView()
, 'inforequest'=>$inforequest
));
}
Run Code Online (Sandbox Code Playgroud)
问题是当我在表单上选择一个选项时,该字段未加载到我的数据库中。
小智 5
我认为问题始于控制器。如果控制器是通过 get 而不是 post 调用的,则 $inforequest 为空。如果用户没有发布表单,数据从何而来?
然后,据我所知,Request 对象应该始终作为函数调用中的第一个变量注入。
如果这些都被整理出来,那么你应该能够在 twig 中设置默认值。像这样的东西:
<select name="nature" id="nature">
<option value ="Other" {% if inforequest.nature == 'Other' %} selected="selected" {% endif %}>Other</option>
<option value ="Adn" {% if inforequest.nature == 'Adn' %} selected="selected" {% endif %}>ADN</option>
</select>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
8151 次 |
最近记录: |