Hy,
I am confused with the following code and i would like to know what i am doing wrong. I use this code in Mezzio application
$inputFilter = new \Laminas\InputFilter\InputFilter();
$inputFilter->add([
'name' => 'is_active',
'required' => false,
'filters' => [
[
'name' => \Laminas\Filter\Boolean::class,
'type' => \Laminas\Filter\Boolean::TYPE_FALSE_STRING,
]
],
]);
$data = ['is_active' => 'false'];
$inputFilter->setData($data);
$inputFilter->isValid();
And when I call : $inputFilter->getValues(); I obtain an array with ‘is_active’ value is true not false
And with :
$data = ['is_active' => false];
I obtain ‘isEmpty’ error message.
Does anyone have an explanation for this behavior? is this a bug? is my code wrong?
Thank you in advance for your answers
This problem is based on the wrong configuration because the type
is an option and must be set as option:
'filters' => [
[
'name' => Laminas\Filter\Boolean::class,
'options' => [
'type' => Laminas\Filter\Boolean::TYPE_FALSE_STRING,
],
],
],
With your current configuration, the NotEmpty validator is automatically added to the input is_active
. But without any options to handle the special type false
therefore the validator will fail for this type of value.
There are two options for this case:
- Set options to avoid the automatic injection of the NotEmpty validator.
$inputFilter->add(
[
'name' => 'is_active',
'required' => false,
'continue_if_empty' => true, // <-- Add this option
'filters' => [
[
'name' => Laminas\Filter\Boolean::class,
'options' => [
'type' => Laminas\Filter\Boolean::TYPE_FALSE_STRING,
],
],
],
]
);
- Add a custom NotEmpty validator.
$inputFilter->add(
[
'name' => 'is_active',
'validators' => [
[
'name' => Laminas\Validator\NotEmpty::class,
'options' => [
'type' => Laminas\Validator\NotEmpty::NULL,
],
],
],
'filters' => [
[
'name' => Laminas\Filter\Boolean::class,
'options' => [
'type' => Laminas\Filter\Boolean::TYPE_FALSE_STRING,
],
],
],
]
);
Thanks a lot for your answers. this solved my problem.