1

I'm new to Symfony2 (version 2.7) and I'm trying to get the value from a submitted form. Using $form->getData(), I get the index corresponding to the selected value in the list.

For example, assuming $test is an array:

$form = $this->createFormBuilder($test)
->add('abc', 'choice',
    array('choices' => array(
        '0' => 'option1',
        '1' => 'option2',
        '2' => 'option3'
    )))
->getForm();
$form->handleRequest($request);
if ($form->isValid()) {
    $data = ($form->getData());
}

Then, $data will be 1 if I select option2. I've also tried to set choices_as_values to true, but then I got the array indexes in the drop-down list.

What can I do to get $data equal to option2 ?

1 Answer 1

1
$values = array('option1', 'option2', 'option3');

$form = $this->createFormBuilder($test)
->add('abc', 'choice', array('choices' => $values))
->getForm();

$form->handleRequest($request);

if ($form->isValid()) {
    $data = $form['abc']->getData();

    //returns option1 if option1 is selected etc..
    $choice = $values[$data];

    //returns choice value
    $choice = $data;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks ! Worked like a charm.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.