I have various form fields. Some of those form fields can have values while others may not have. So I have made those as required ‘false’ and also made them as allow_empty true. Come what may I am still getting isEmpty when I validate the form. Even I have tried to avoid form validation even then the error is there.Please advise what are the options for me.
The following example shows the use:
final class ExampleForm extends Laminas\Form\Form
implements Laminas\InputFilter\InputFilterProviderInterface
{
public function init(): void
{
$this->add(
[
'name' => 'artist',
'type' => Laminas\Form\Element\Text::class,
'options' => [
'label' => 'Artist',
],
]
);
$this->add(
[
'name' => 'title',
'type' => Laminas\Form\Element\Text::class,
'options' => [
'label' => 'Title',
],
]
);
$this->add(
[
'name' => 'genre',
'type' => Laminas\Form\Element\Text::class,
'options' => [
'label' => 'Genre',
],
]
);
}
public function getInputFilterSpecification(): array
{
return [
[
'name' => 'artist',
'required' => true,
'allow_empty' => true,
],
[
'name' => 'title',
'required' => true,
'allow_empty' => false,
],
[
'name' => 'genre',
'required' => false,
'allow_empty' => true,
],
];
}
}
$form = new ExampleForm();
$form->init();
$form->setData(
[
'artist' => '',
'title' => 'David Bowie',
]
);
var_dump($form->isValid()); // true
$form->setData(
[
'artist' => '',
'title' => '',
]
);
var_dump($form->isValid()); // false
$form->setData(
[
'artist' => '',
'title' => 'David Bowie',
'genre' => '',
]
);
var_dump($form->isValid()); // true
As you can see require
means the field itself must be provided. allow_empty
does exactly what the name says.
1 Like