简体   繁体   English

Symfony2在形式类型中使用原则

[英]Symfony2 use doctrine in form type

I would like to create an optgroup in symfony2 like this: 我想像这样在symfony2中创建一个optgroup:

$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) (在形式类型中使用原则)

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. symfony的有关创建表单和服务的教程对此进行了介绍。

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. 最不合理的选择是在创建Form对象时手动传递理论或在构造函数中手动选择,请注意,这完全是非标准的,虽然最简单,但是扩展性也最低。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM