我遵循了一个示例,想将数据库适配器传递给字段集以创建下拉菜单。
下面的代码是我调用字段集的方式。
我如何访问 BrandFieldset 类中的数据库适配器?
$this->add(array(
'type' => 'Application\Form\BrandFieldset',
'name' => 'brand',
'options' => array(
'label' => 'Brand of the product',
),
));
最佳答案
实例化字段集是 FormElementManager 的责任.当您尝试访问表单、表单元素或字段集时,FormElementManager
知道在哪里可以找到它以及如何创建它。此行为总结在 Default Services 中框架部分。
由于访问表单元素的正确方法是从 FormElementManager 中检索它们,因此我会编写一个 BrandFieldsetFactory
来注入(inject)该 DB 适配器或进一步依赖于构造字段集以实现此目的。
ZF3 友好的 fieldset 工厂看起来像:
<?php
namespace Application\Form\Factory;
use Application\Form\BrandFieldset;
use Interop\Container\ContainerInterface;
class BrandFieldsetFactory
{
/**
* @return BrandFieldset
*/
public function __invoke(ContainerInterface $fem, $name, array $options = null)
{
// FormElementManager is child of AbstractPluginManager
// which makes it a ContainerInterface instance
$adapter = $fem->getServiceLocator()->get('Your\Db\Adapter');
return new BrandFieldset($adapter);
}
}
此时,BrandFieldset
应该扩展 Zend\Form\Fieldset\Fieldset
,它的构造函数可能如下所示:
private $dbAdapter;
/**
* {@inheritdoc}
*/
public function __construct(My/Db/Adapter $db, $options = [])
{
$this->dbAdapter = $db;
return parent::__construct('brand-fieldset', $options);
}
最后,在 module.config.php
文件中,我有一个配置告诉 FormElementManager
关于这个工厂:
<?php
use Application\Form\BrandFieldset;
use Application\Form\Factory\BrandFieldsetFactory;
return [
// other config
// Configuration for form element manager
'form_elements' => [
'factories' => [
BrandFieldset::class => BrandFieldsetFactory::class
],
],
];
HINT: The
BrandFieldset::init()
method will be called automatically by FormElementManager after construction. You can put any post-initialization logic into this method.
关于php - 如何访问 ZF2 Field Set 中的数据库适配器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41782476/