在 Symfony2 中使用 Doctrine 的 DBAL 与表单



所以我想做以下事情:

我在/form/Type/UserType.php 上创建了一个表单类

我有一个包含状态列表的表(名为"states"的表)。

我想在下拉菜单中显示所有这些状态。

我应该在类UserType中使用什么代码来显示所有状态?

我试过了:

    $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,
   ));

但这给了我一个错误。基本上,我想查询表状态中的所有状态,并从所有这些状态创建一个下拉菜单。

您可以创建State实体,将其映射到states表,并创建与User实体的OneToMany关系。然后在UserType表单中,$builder->add('state')应该自动创建下拉字段。您还必须在UserType表单的getDefaultOptions方法中将data_class选项设置为User实体。

@m2mdas已经给出了正确的基于对象的答案。然而,如果您真正想做的只是存储state_code,那么您所拥有的几乎可以工作。你只需要做好连接。

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

最新更新