A.Mali A.Mali - 5 months ago 106
PHP Question

Select option html tag in twig Symfony

For my project I used Symfony framework. I need to use the select option to generate a list for my form.

Here is the code:

Form:

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


Controller:

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


The problem is when I select an option on my form, the field is not load on my database.

Answer

Problem resolved! I didn't put the correct name on my select option id

Here the code

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

Small precision : my bs_bundle_sample is the name of my formType (name find on my getName function).

Comments