学说的DBAL在Symfony2中与形式
问题描述:
所以,我要做到以下几点:学说的DBAL在Symfony2中与形式
我在/Form/Type/UserType.php
创建的窗体类我有一个表的状态列表(表名为“状态”)。
我想在下拉菜单中显示所有这些状态。
我应该在类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')
应自动创建下拉字段。您还必须将data_class
选项设置为您的User
实体getDefaultOptions
方法的UserType
表单。
答
@ 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());