nielsv
nielsv

Reputation: 6800

Symfony2 use doctrine in form type

I would like to create an optgroup in symfony2 like this:

$category_choices = array(
    array('Category 1' => array(
        '1' => 'Option 1...',
        '2' => 'Option 2...',
        '3' => 'Option 3...'
    )),
    array('Category 2' => array(
        '4' => 'Option 4...',
        '5' => 'Option 5...'
    ))
);

$builder->add('category_list', 'choice', array(
    'label' => 'Category',
    'choices' => $category_choices
));

But I want to get the category choices from the database and I need to execute some actions on them and add them to an array. How can I do this in the same form type? (use doctrine in form type)

Upvotes: 0

Views: 1967

Answers (1)

Uriziel
Uriziel

Reputation: 742

There are several ways to do that actually.

Most reasonable seems to be adding additional option to your form, this so question seems to be nice tutorial

Other than that you can define your form (you should anyway) as a service and pass a doctrine's entity manager into it. This is covered in symfony's tutorials about creating forms and services.

The least reasonable option is passing doctrine or your choices in constructor manually when creating Form object, note that this is totally non-standard and while it's easiest it's also least extensible.

Upvotes: 1

Related Questions