您可以使用工廠類注入任何您喜歡的選項。
use MyModule\Form\MyForm;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\ServiceManager\FactoryInterface;
class MyFormFactory implements FactoryInterface
{
public function createService(ServiceLocatorInterface $formElementManager)
{
$serviceManager = $formElementManager->getServiceLocator();
$request = $serviceManager->get('Request');
// I would recommend assigning the data
// from the request to the options array
$options = [
'is_ajax' => $request->isXmlHttpRequest(),
];
// Although you could also pass in the request instance into the form
return new MyForm('my_form', $options, $request);
}
}
如果注入的要求,您將需要修改MyForm::__construct
。
namespace MyModule\Form;
use Zend\Form\Form;
use Zend\Http\Request as HttpRequest;
class MyForm extends Form
{
protected $request;
public function __construct($name, $options, HttpRequest $request)
{
$this->request = $request;
parent::__construct($name, $options);
}
}
更新您的module.config.php
使用工廠
return [
'form_elements' => [
'factories' => [
'MyModule\Form\MyForm' => 'MyModule\Form\MyFormFactory'
]
]
]
然後確保你要求從服務管理形式(在控制器工廠)
$myForm = $serviceManager->get('FormElementManager')->get('MyModule\Form\MyForm');
好的,很酷,謝謝。仍然圍繞着工廠 - 我可以重寫或抽象getForm方法在所有檢索到的表單上注入類似的基本選項嗎?像說getTailoredForm? – Scott
另外,我記得當$ this-> getServiceManager返回formManager中的formManager時,formManager的getServiceManager返回標準服務定位器,所以我還可以根據需要在上下文中獲取值(構造函數完成後) – Scott
@Scott您的表單具有類似的依賴關係,您當然可以擴展工廠和/或爲每個表單創建一個抽象類。爲了在控制器中獲取表單,理想情況下應該創建一個'MyControllerFactory',然後將表單注入控制器(就像在我的示例中注入'Request'一樣)。 – AlexP