Create form dynamically in Symfony 2

懵懂的女人 提交于 2019-12-08 06:01:37

问题


A simple question:

I have one form, it returns one number and I need create this number of labels in Controller.

I try:

$form2 = $this->createFormBuilder();

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

$form2->getForm();

I think it should very simple, but i can't..


回答1:


Yes, you can do it with an array / hash map instead of a real object.

Here is an example :

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


来源:https://stackoverflow.com/questions/13049723/create-form-dynamically-in-symfony-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!