简体   繁体   English

在symfony2中使用形式的dbal

[英]using doctrine's dbal in symfony2 with forms

So I want to do the following: 因此,我想执行以下操作:

I created a form class at /Form/Type/UserType.php 我在/Form/Type/UserType.php创建了一个表单类

I have a table with a list of states (table named "states"). 我有一张带有状态列表的表(名为“ states”的表)。

I want to show all of these states in a drop down menu. 我想在下拉菜单中显示所有这些状态。

What code should I use in the class UserType to show all the states? 我应该在UserType类中使用什么代码来显示所有状态?

I tried: 我试过了:

    $request = new Request;
    $conn = $request->get('database_connection');
    $states = $conn->fetchAll('SELECT state_code, state_name FROM states');

    $builder->add('state', 'choice', array(
        'choices'   => $states,
        'required'  => false,
   ));

but that gives me an error. 但这给了我一个错误。 Basically, I want to query all of the states from the table states, and create a drop down menu from all of these states. 基本上,我想从表状态查询所有状态,并从所有这些状态创建一个下拉菜单。

You can create State entity, map it to states table and create a OneToMany relation with the User entity. 您可以创建State实体,将其映射到states表,并与User实体创建OneToMany关系。 Then in your UserType form $builder->add('state') should create dropdown field automatically. 然后在您的UserType表单中, $builder->add('state')应该自动创建下拉字段。 You also have to set data_class option to your User entity in getDefaultOptions method of UserType form. 您还必须在UserType表单的getDefaultOptions方法中将data_class选项设置为您的User实体。

@m2mdas has given you the correct object based answer. @ m2mdas为您提供了正确的基于对象的答案。 However, if all you really want to do is to store the state_code then what you have will almost work. 但是,如果您真正想要做的只是存储state_code,那么您所拥有的几乎就可以了。 You just need to get the connection right. 您只需要正确连接即可。

class MyType extends extends AbstractType
{
    public function __construct($em) { $this->em = $em; }

    public function buildForm(FormBuilder $builder, array $options)
    {
        $conn = $this->em->getConnection();
        $statesx = $conn->fetchAll('SELECT state_code, state_name FROM states');

        // Need to index for the choice
        $states = array();
        foreach($statesx as $state) 
        { 
            $states[$state['state_code']] = $state['state_name']; 
        }

        $builder->add('state', 'choice', array(
            'choices'   => $states,
            'required'  => false,
        ));

...
// In your controller
$form = new MyType($this->getDoctrine()->getEntityManager());

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

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