我有一个表单,其中包含一个 formCollection 和一个选择元素,我想根据 POST 参数用值(来自 SQL)填充它。
将此参数从 Controller 传递到表单不是问题,但现在我找不到在 formCollection 的 target_element 中设置/读取该参数的方法。关于如何让它发挥作用的任何想法?
这是我的代码:
Controller
class MyController extends AbstractActionController{
public function indexAction()
{
$form = $this->serviceLocator->get('FormElementManager')->get('Module\Form\myForm');
$form->init([
'param' => $this->params()->fromPost('param')
]);
}
}
表单
class myForm extends Form
{
private $sm;
public function __construct($sm = null)
{
parent::__construct();
$this->sm = $sm;
}
public function init($params=[])
{
$this->add([
'name' => 'choices',
'type' => 'Zend\Form\Element\Collection',
'options' => [
'label' => 'SelectLabel',
'count' => 1,
'should_create_template' => true,
'allow_add' => true,
'template_placeholder' => '__placeholder__',
'target_element' => [
'type' => 'Module\Form\choicesFieldset',
'options' => [
'param' => isset($params['param']) ? $params['param'] : 0,
]
],
],
]);
}
}
字段集
class choicesFieldset extends Fieldset{
private $sm;
public function __construct($sm = null){
parent::__construct();
$this->sm = $sm;
}
public function init(){
$param = $this->getOption('param');
$availableChoices = /* SQL_QUERY_BASED_ON_PARAM; */
$this->add([
'name' => 'choice_1',
'type' => 'Select',
'options' => [
'label' => 'First choice',
'value_options' => $availableChoices,
]
]);
}
}
预先感谢您的帮助。
最佳答案
您需要做的就是从服务管理器中获取Request
实例;检查您想要的参数,然后将其“注入(inject)”到表单中。
在表单工厂中这样做会更有意义;而不是在 Controller 中重复自己。
例如:
public function getFormElementConfig()
{
return array(
'factories' => array(
'MyModule\Form\MyForm' => function($formElementManager) {
$serviceManager = $formElementManager->getServiceLocator();
$request = $serviceManager->get('Request');
// defaults to 0 if not set
$param = $request->getPost('the_posted_variable_name', 0);
$options = array(
'my_custom_option_name' => $param,
);
// You should maintain the Zend\Form\Element::__construct() method signuture
// as it allows for the 'options' to be passed in.
// Alternatively you could use $form->setOption('param', $options)
// and inject the options as a soft dependency
$form = new Form\MyForm('my_form', $options, $serviceManager);
// ... other form stuff here
return $form;
},
),
);
}
现在您可以使用表单中的选项:
$param = $this->getOption('my_custom_option_name');
关于php - 如何将选项/参数传递给 ZendFramework 2 中的 formCollection 字段集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23953346/