Symfony2具有选项的无类表单:检索提交的数据


Symfony2 classless form with choices: retrieving submitted data

我在使用symfony2和带有选择字段的无类表单时遇到问题。

设置非常非常简单:

$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();

然后。。。

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

这是在"疯狂"的部分,我被卡住了。实际上,我需要通过$choices数组中给定的原始索引来访问选定的选项。。。我一直没能做到。这是我得到的最接近的:

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

假设我们标记第一个和最后一个选择,得出:

0 -> 1
1 ->  
2 -> 1

这是绝对必要的,这是一个无类的形式。我如何访问原始索引(在我们的情况下,1,2或100)的选择?。

非常感谢。

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

将为您提供所需的数据。

我希望这能有所帮助。

这是字段映射的问题。传递到表单中的数据需要应用到要添加的字段("mythings"),因此必须将$data封装在数组中,作为键"mything"的值。

例如:

$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();

您可以尝试命名数组键以保留实际索引

$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();