1

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..

7
  • 2
    you're trying to add an embedding form several time? If yes have a look on this it'll help you : symfony.com/doc/2.0/cookbook/form/form_collections.html Commented Oct 24, 2012 at 13:03
  • I didn't to use one Type and Class Commented Oct 24, 2012 at 13:47
  • So your form don't use entity? Then just add a for loop in twig to duplicate your field Commented Oct 24, 2012 at 14:04
  • Yes. And how would I take the values ​​of the labels in Controller? Commented Oct 25, 2012 at 12:04
  • can you show us your form type, controller method and twig corresponding to this form? Commented Oct 25, 2012 at 12:26

1 Answer 1

2

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()));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.