我开始使用 zf2 ..
我想知道如何在从数据库中获取选项的表单中创建一个下拉列表?
这可能是一个新手问题,但我很难做到。
谢谢
你可以这样做:
创建一个扩展 Fieldset 的类。
如果您想对该字段进行某种验证,请实现类 InputFilterProviderInterface。
要访问服务管理器,需要实现ServiceLocatorAwareInterface和setServiceLocator()和getServiceLocator()两个方法。
默认情况下,Zend Framework MVC 注册一个初始化器,它将 ServiceManager 实例注入到任何实现 Zend\ServiceManager\ServiceLocatorAwareInterface 的类中。读这个
namespace Users\Form;
use Zend\InputFilter\InputFilterProviderInterface;
use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\Form\Element;
use Zend\Form\Fieldset;
class GroupsFieldset extends Fieldset implements InputFilterProviderInterface,
ServiceLocatorAwareInterface
{
/**
* @var ServiceLocatorInterface
*/
protected $serviceLocator;
public function __construct ()
{
parent::__construct('groups');
$this->setLabel('Group');
$this->setName('groups');
$sl = $this->getServiceLocator();
$sm = $sl->get('Users\Model\GroupsTable');
$groups = $sm->fetchAll();
$select = new Element\Select('groups');
$options = array();
foreach ($groups as $group) {
$options[$group->id] = $group->name;
}
$select->setValueOptions($options);
}
/**
* Set serviceManager instance
*
* @param ServiceLocatorInterface $serviceLocator
* @return void
*/
public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
{
$this->serviceLocator = $serviceLocator;
return $this;
}
/**
* Retrieve serviceManager instance
*
* @return ServiceLocatorInterface
*/
public function getServiceLocator()
{
return $this->serviceLocator;
}
/**
*
* @return multitype:multitype:boolean
*/
public function getInputFilterSpecification ()
{
return array(
'name' => array(
'required' => true
)
);
}
}
比在 module.php 中
public function getServiceConfig()
{
return array(
'factories' => array(
'Users\Model\UsersTable' => function($sm) {
$dbAdapter1 = $sm->get('Zend\Db\Adapter\Adapter');
$table1 = new UsersTable($dbAdapter1);
return $table1;
}, // Adapter and table groups here
'Users\Model\GroupsTable' => function($sm) {
$dbAdapter2 = $sm->get('Zend\Db\Adapter\Adapter');
$table2 = new GroupsTable($dbAdapter2);
return $table2;
},
),
);
}
最后在你的表格中
$groups = new GroupsFieldset();
$this->add($groups);