[英]ZF2 Select element usage
我正在使用Zend Framework 2,並且需要一個依賴下拉列表。 當用戶選擇類別(在我的示例中為cat_id)時,系統會使用正確的元素填充子類別(sca_id)。
我可以通過創建這樣的應用程序來做到這一點:
我的表格如下:
$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,因為我選擇在我的控制器中執行此操作,在該控制器中可以使用Service Manager:
$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的change事件上,我執行$.ajax
來從Action中獲取元素並填充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'),
),
));
當我提交表單時,它總是說: The input was not found in the haystack
兩個下拉列表The input was not found in the haystack
都The input was not found in the haystack
...
我做錯了什么?
額外的問題:有更好的方法來填充我的下拉菜單嗎?
附注 :我想這個問題禁用notInArray驗證程序Zend Framework 2提出的問題與我相似,但我想詳細說明我的問題。
好吧,我意識到我應該在驗證表單之前填充select元素!
// 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...
}
該代碼很好用。 我的表格現在可以完美驗證了!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.