Hello, what is the suggested way to get parent form values inside validators of fieldset?
basic idea:
- parent form has field
parentField
- form has collection of fieldset
- depending to this
parentField
-value of parent form we should validate fieldset using DIFFERENT logic
how to accomplish this?
namespace Application\Form;
use Laminas\Form\Form;
use Laminas\Form\Element\Collection;
use Laminas\Form\Element\Text;
use Laminas\InputFilter\InputFilterProviderInterface;
class ParentForm extends Form implements InputFilterProviderInterface
{
public function __construct($name = null)
{
parent::__construct($name);
$this->add([
'name' => 'parentField',
'type' => Text::class,
'options' => [
'label' => 'Parent Field',
],
]);
$this->add([
'name' => 'fieldsetCollection',
'type' => Collection::class,
'options' => [
'label' => 'Fieldset Collection',
'count' => 2,
'should_create_template' => true,
'target_element' => [
'type' => FieldsetExample::class,
],
],
]);
}
public function getInputFilterSpecification()
{
return [
'parentField' => [
'required' => true,
'filters' => [
['name' => 'StringTrim'],
['name' => 'StripTags'],
],
'validators' => [
[
'name' => 'NotEmpty',
],
],
],
];
}
}
namespace Application\Form;
use Laminas\Form\Fieldset;
use Laminas\Form\Element\Text;
use Laminas\InputFilter\InputFilterProviderInterface;
class FieldsetExample extends Fieldset implements InputFilterProviderInterface
{
public function __construct($name = null)
{
parent::__construct($name);
$this->add([
'name' => 'childField',
'type' => Text::class,
'options' => [
'label' => 'Child Field',
],
]);
}
public function getInputFilterSpecification()
{
return [
'childField' => [
'required' => true,
'filters' => [
['name' => 'StringTrim'],
['name' => 'StripTags'],
],
'validators' => [
[
'name' => 'Callback',
'options' => [
'callback' => [$this, 'validateChildField'],
],
],
],
],
];
}
public function validateChildField($value, $context, $options)
{
$parentFieldValue = *** HERE we should get parent form field value ***
# example of validation logic
if ($value !== $parentFieldValue) {
return false;
}
return true;
}
}
thanks!