2016-06-13 58 views
1

对于我的项目,我使用了Symfony框架。我需要使用select选项来为我的表单生成一个列表。在树枝中选择选项html标记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> 

FormType:

public function buildForm(FormBuilderInterface $builder, array $options){ 
    $builder 
      ->add('nature') 
      ->add('origin'); 
    } 

控制器:

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 
     )); 
    } 

问题是,当我选择一个选项我形式,该字段是n不加载我的数据库。

+1

添加处理表单提交的控制器代码可能是一个好主意。 – tlenss

回答

0

问题已解决! 我没有把正确的名字在我的选择选项ID

下面的代码

<select name="bs_bundle_sample[nature]" id="bs_bundle_sample_nature"> 
     <option value ="Other">Other</option> 
     <option value ="Adn">ADN</option> 
    </select> 

小型精密:我bs_bundle_sample是我formType的姓名(名称在我的getName功能找到)。

0

Symfony的都可以自动做到这一点:尝试改变对 '自然' 的选项中你formType到:

 ->add('nature', 'choice', array('label' => '(*) Nature sample', 'choices' => array ('Other' => 'Other', 'Adn' => 'ADN'))) 

而在你的树枝,将其替换选择:

{{form_errors(form.nature)}} 
{{form_widget(form.nature)}} 

最后:完整的参考在这里:http://symfony.com/doc/current/book/forms.html

+0

我知道这一点,但我使用一个JavaScript脚本谁动态生成一个其他领域(起源)谁取决于我的以前选择(性质)的选择。这就是为什么我需要使用这个。 –

1

我认为问题开始在控制器。如果控制器是通过get而不是post来调用的,那么$ inforequest是空的。如果用户没有发布表单,数据来自哪里?

然后,据我所知,Request对象应该始终作为函数调用中的第一个变量注入。

如果这些都是整理出来的,那么你应该可以在树枝中设置默认值。类似这样的:

<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>