The Marlboro Man
The Marlboro Man

Reputation: 971

Symfony2 classless form with choices: retrieving submitted data

I am having a problem using symfony2 and a classless form with a choice field.

The setup is very, very simple:

$data=array();
$choices=array(1 => 'A thing', 2 => 'This other thing', 100 => 'That other thing');

$fb=$this->createFormBuilder($data);
$fb->add('mythings', 'choice', array(
        'choices' => $choices,
        'data' => $data,
        'required' => false,
        'expanded' => true, 
        'multiple' => true,
        'mapped' => false))->
    add('save', 'submit', array('label' => 'Save'));
$form=$fb->getForm();

And then...

$request=$this->getRequest();
$form->handleRequest($request);
if($form->isValid())
{
    //Go nuts.
}

It is in the "go nuts" part where I am stuck. I actually need to access the selected choices by their original index as given in the $choices array... And I haven't been able to. This is the closest I got:

$submitted_data=$form->get('mythings'); 
foreach($submitted_data as $key => $value) 
{   
echo $key.' -> '.$value->getData().'<br />'; 
}

Which assuming we mark the first and last choices, yields:

0 -> 1
1 ->  
2 -> 1

It is absolutely necessary that this be a classless form. How do I access the original index (in our case, 1, 2 or 100) of the choices?.

Thanks a lot.

Upvotes: 1

Views: 131

Answers (3)

Lost Koder
Lost Koder

Reputation: 884

$form->get('mythings')->getData()

will give you data that you need.

I hope this helps.

Upvotes: 1

TheGreenkey
TheGreenkey

Reputation: 143

you could try naming the array keys to preserve the actual index

$data=array();
$choices=array('1' => 'A thing', '2' => 'This other thing', '100' => 'That other thing');

$fb=$this->createFormBuilder($data);
$fb->add('mythings', 'choice', array(
        'choices' => $choices,
        'data' => $data,
        'required' => false,
        'expanded' => true, 
        'multiple' => true,
        'mapped' => false))->
    add('save', 'submit', array('label' => 'Save'));
$form=$fb->getForm();

Upvotes: 1

SA Alex
SA Alex

Reputation: 46

It's an issue with field mapping. the data you're passing into the form needs to be applied to the field you're adding ('mythings') so you have to wrap $data in an array as a value to the key 'mythings'.

For example:

$data=array();
$choices=array(1 => 'A thing', 2 => 'This other thing', 100 => 'That other thing');

$fb=$this->createFormBuilder(array('mythings' => $data));
$fb->add('mythings', 'choice', array(
    'choices' => $choices,
    'required' => false,
    'expanded' => true, 
    'multiple' => true))
   ->add('save', 'submit', array('label' => 'Save'));

$form=$fb->getForm();

Upvotes: 1

Related Questions