Symfony2无类表单,包含选项:检索提交的数据

时间:2015-02-12 13:41:43

标签: php forms symfony

我在使用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)?

非常感谢。

3 个答案:

答案 0 :(得分:1)

这是字段映射的问题。您传入表单的数据需要应用于您添加的字段('mythings'),因此您必须将数据中的$ data作为键'mythings'的值包装。

例如:

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

答案 1 :(得分:1)

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

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

答案 2 :(得分:1)

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

会为您提供所需的数据。

我希望这会有所帮助。

相关问题