1

一个简单的问题:

我有一个表格,它返回一个数字,我需要在 Controller 中创建这个数量的标签。

我尝试:

$form2 = $this->createFormBuilder();

for($i = 0; $i < $num; $i++) {
    $name = 'column'.$i;
    $form2->add($name,'number');
}

$form2->getForm();

我认为它应该很简单,但我不能..

4

1 回答 1

2

是的,您可以使用数组/哈希映射而不是真实对象来做到这一点。

这是一个例子:

// Create the array
$dataObj = array();

$dataObj['data1'] = '';
$dataObj['data2'] = 'default';
// ... do a loop here
$dataObj['data6'] = 'Hello';

// Create the form
$formBuilder = $this->createFormBuilder($dataObj);
foreach($dataObj as $key => $val)
{
    $fieldType = 'text'; // Here, everything is a text, but you can change it based on $key, or something else
    $formBuilder->add($key, $fieldType);
}
$form = $formBuilder->getForm();

// Process the form
$request = $this->get('request');
if($request->getMethod() == 'POST')
{
    $form->bind($request); // For symfony 2.1.x
    // $form->bind($this->get('request')->request->get('form')); // For symfony 2.0.x
    if($form->isValid())
    {
        $dataObj = $form->getData();
        foreach($dataObj as $key => $val)
        {
            echo $key . ' = ' . $val . '<br />';
        }
        exit('Done');
    }
}

// Render
    return $this->render('Aaa:Bbb:ccc.html.twig', array(
    'requestForm' => $form->createView()));
于 2013-01-30T14:42:32.130 回答