automatix
automatix

Reputation: 14552

How to get the selected option of a radion button element in Zend Framework 2?

In a Fieldset I have an Element\Radio foo and Element\Text bar.

public function init()
{
    $this->add(
        [
            'type' => 'radio',
            'name' => 'foo',
            'options' => [
                'label' => _('foo'),
                'value_options' => [
                    [
                        'value' => 'a',
                        'label' => 'a',
                        'selected' => true
                    ],
                    [
                        'value' => 'b',
                        'label' => 'b'
                    ]
                ]
            ]
            ...
        ]);

    $this->add(
        [
            'name' => 'bar',
            'type' => 'text',
            'options' => [
                'label' => 'bar',
                ...
            ],
            ...
        ]);
}

The validation of the field bar is depending on the selected foo option. It's easy to implement, if I can get the selected value of foo:

public function getInputFilterSpecification()
{
    return [
        'bar' => [
            'required' => $this->get('foo')->getCheckedValue() === 'a',
            ...
        ],
    ];
}

But there is no method Radio#getCheckedValue(). Well, I can iterate over the $this->get('foo')->getOptions()['value_options'], but is it really the only way?

How to get (in the Fieldset#getInputFilterSpecification()) the selected option of a Zend\Form\Element\Radio?

Upvotes: 0

Views: 215

Answers (1)

FuST
FuST

Reputation: 76

The selected option gets POSTed to the server along with everything else from the HTML form and is all of this is available in validators through the $context array. You can create a conditionally required field by using a callback validator and the $context array like this:

public function getInputFilterSpecification() {
    return [
        'bar' => [
            'required' => false,
            'allow_empty' => true,
            'continue_if_empty' => true,
            'required' => true,
            'validators' => [
                [
                    'name' => 'Callback',
                    'options' => [
                        'callback' => function ($value, $context) {
                            return $context['foo'] === 'a'
                        },
                        'messages' => [
                            \Zend\Validator\Callback::INVALID_VALUE => 'This value is required when selecting "a".'
                        ]
                    ]
                ]
            ]
        ],
    ];
}

That would check if 'foo' is equal to 'a', i.e. option 'a' is selected and return true when it is, which marks the input as valid, and false when it's not, marking the input invalid.

Upvotes: 0

Related Questions