zf добавить inputfilter для нового элемента fieldset в классе формы
В Zend Framework, как мне добавить inputfilter для нового элемента формы в fieldset с кодом в форме? В следующем случае я определил набор общих элементов формы и фильтр ввода для этих элементов в классе fieldset и добавил набор полей в форму. После этого я добавляю один или несколько новых элементов формы в набор полей в коде формы (я делаю это в форме, а не в наборе полей, чтобы подготовиться к динамическому добавлению элементов с помощью фабрики форм). У меня проблемы с добавлением новых определений входного фильтра для дополнительных элементов.
в моем наборе полей:
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
}
}
В этом примере дополнительный элемент добавляется в набор полей, но я неправильно набрал код для добавления новых определений в фильтр ввода.
1 ответ
Вам нужно получить входной фильтр набора полей, а не класса формы. Для этого Zend Framework содержит InputFilterProviderFieldset
класс, от которого вы должны унаследовать свой набор полей. InputFilterProviderFieldset
Класс поставляется с методами получения и установки для изменения спецификаций входного фильтра во время выполнения. Следующий код не проверен, но должен работать.
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 предоставляет все необходимое для решения вашей проблемы. Я надеюсь, что этот подход поможет вам.