ZF2 Select 元素用法 [英] ZF2 Select element usage
问题描述
我使用的是 Zend Framework 2,我需要一个 Dependent Dropdown.当用户选择一个类别(在我的示例中为 cat_id)时,系统会使用正确的元素填充子类别 (sca_id).
I'm using Zend Framework 2 and I need a Dependent Dropdown. When user select an category (cat_id on my example) the system fills the subcategory (sca_id) with the correct elements.
我可以通过创建这样的应用程序来做到这一点:
I could do that by creating an application like this:
我的表单看起来像:
$this->add(array(
'name' => 'cat_id',
'type' => 'Zend\Form\Element\Select',
'options' => array(
'label' => 'Categoria',
'value_options' => array(
'' => '',
),
),
));
$this->add(array(
'name' => 'sca_id',
'type' => 'Zend\Form\Element\Select',
'options' => array(
'label' => 'Sub Categoria',
'style' => 'display:none;', // Esse campo soh eh exibido qndo uma categoria for escolhida
'value_options' => array(
'' => '',
),
),
));
请注意,我没有在那里填写 value_options,因为我选择在服务管理器可用的控制器中执行此操作:
Note that I don't fill the value_options there, because I choose do that in my controller, where the Service Manager is avaliable:
$form = new ProdutoForm('frm');
$form->setAttribute('action', $this->url()->fromRoute('catalogo-admin', array( ... )));
// Alimenta as comboboxes...
$form->get('cat_id')->setValueOptions($this->getCategoriaService()->listarCategoriasSelect());
在 cat_id 的更改事件中,我执行了一个 $.ajax
以从 Action 中获取元素并填充 sca_id.
On the change event of cat_id I do an $.ajax
to grab the elements from an Action and fill the sca_id.
效果很好!
问题出在我的验证上:
$this->add(array(
'name' => 'cat_id',
'require' => true,
'filters' => array(
array('name' => 'Int'),
),
));
$this->add(array(
'name' => 'sca_id',
'require' => true,
'filters' => array(
array('name' => 'Int'),
),
));
当我提交表单时,它一直说:两个下拉菜单的输入都没有在干草堆中找到
...
When I submit my form it keeps saying : The input was not found in the haystack
for both dropdowns...
我做错了什么?
额外问题:有更好的方法来填充我的下拉列表吗?
Extra questions : There's a better way to fill my dropdowns?
Ps.:我猜这个问题禁用notInArray Validator Zend Framework 2问了一些与我类似的问题,但我想更详细地说明我的问题.
Ps.: I guess this question Disable notInArray Validator Zend Framework 2 asks something similar than me, but I wanted to detail more my problem.
推荐答案
好吧,我意识到我应该在验证表单之前填充我的 select 元素!
Well, I realized that I should populate my select element before validate my form!
// SaveAction
$request = $this->getRequest();
if ($request->isPost())
{
$form = new ProdutoForm();
// Alimenta as comboboxes...
$form->get('cat_id')->setValueOptions($this->getCategoriaService()->listarCategoriasSelect());
$form->get('sca_id')->setValueOptions($this->getSubCategoriaService()->listarSubCategoriasSelect());
// If the form doesn't define an input filter by default, inject one.
$form->setInputFilter(new ProdutoFormFilter());
// Get the data.
$form->setData($request->getPost());
// Validate the form
if ($form->isValid())
{
// Valid!
}else{
// Invalid...
}
该代码运行良好.我的表单现在可以完美验证!
That code works nice. My form now validate perfectly!
这篇关于ZF2 Select 元素用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!