[英]zf add inputfilter for a new fieldset element in the form class
在zend Framework中,如何在具有表單代碼的字段集中為新表單元素添加inputfilter? 在以下情況下,我在fieldset類中定義了一組常見的表單元素和這些元素的inputfilter,然后將fieldset添加到表單中。 之后,我將一個或多個新表單元素添加到表單代碼中的字段集中(我是在表單中而不是在字段集中這樣做,以准備通過表單工廠動態添加元素)。 我遇到的麻煩是為其他元素添加了新的inputfilter定義。
在我的領域:
class myFieldset extends Fieldset implements InputFilterProviderInterface
{
public function init()
{
// add form elements
}
public function getInputFilterSpecification()
{
$inputFilter['myFormElement'] = [
'required' => true,
'filters' => [[ ... ],],
'validators' => [[ ... ],],
'allow_empty' => false,
'continue_if_empty' => false,
];
// more filters
return $inputFilter;
}
}
以我的形式:
class myForm extends Form
{
public function __construct()
{
// ...
// add elements from fieldset
$this->add([
'name' => 'myFieldset',
'type' => 'Application\Form\Fieldset\myFieldset',
'options' => [
'use_as_base_fieldset' => true,
],
]);
// add new element
$myFieldset = $this->get('myFieldset');
$myFieldset->add([
'name' => 'additionalElement',
'type' => 'Zend\Form\Element\ ... ',
'attributes' => [],
'options' => [],
]);
// update inputfilter
$input = new Input('additionalElement');
$input->setRequired(false);
$currentInputFilter = $this->getInputFilter();
$currentInputFilter->add($input);
$this->setInputFilter($currentInputFilter);
// submit buttons
}
}
在此示例中,附加元素被添加到字段集中,但是我將代碼錯誤地添加到inputfilter的新定義中。
您需要獲取字段集而不是表單類的輸入篩選器。 為此,Zend Framework包含InputFilterProviderFieldset
類,您應該從該類繼承字段集。 InputFilterProviderFieldset
類帶有getter和setter方法,用於在運行時修改輸入過濾器的規范。 以下代碼未經測試,但可以正常工作。
namesapce Application\Form\MyFieldset;
use Zend\Form\InputFilterProviderFieldset;
class MyFieldset extends InputFilterProviderFieldset
{
public function init()
{
$this->add([
'name' => 'element1',
'type' => Text::class,
'attributes' => [
...
],
'options' => [
...
],
]);
}
}
通過使用InputFilterProviderFieldset
類,您的表單類應如下所示。
namespace Application\Form;
use Zend\Form\Form;
class YourForm extends Form
{
public function __construct(string $name, array $options = [])
{
// definition of your fieldset must use the input_filter_spec key
$this->add([
'name' => 'myFieldset',
'type' => 'Application\Form\Fieldset\myFieldset',
'options' => [
'use_as_base_fieldset' => true,
'input_filter_spec' => [
'element1' => [
'required' => true,
'filters' => [
...
],
'validators' => [
...
],
],
],
],
]);
// add a new element to the fieldset
$this->get('myFieldset')->add([
'name' => 'element2',
'type' => Text::class,
'attributes' => [
...
],
'options' => [
...
],
]);
// Update the input filter of the fieldset
$myFieldsetFilterSpec = $this->get('myFieldset')->getInputFilterSpecification();
$myNewFieldsetFilterSpec = array_merge(
$myFieldsetFilterSpec,
[
'element2' => [
'required' => false,
],
],
);
// set the new filter specs for your fieldset
$this->get('myFieldset')->setInputFilterSpecification($myNewFieldsetFilterSpec);
}
}
如您所見,Zend Framework帶來了解決問題所需的所有東西。 希望這種方法對您有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.