zendframework / zend-inputfilter

InputFilter component from Zend Framework
BSD 3-Clause "New" or "Revised" License
64 stars 50 forks source link

Avoiding the default NotEmpty::IS_EMPTY validation message. #124

Closed nathanjosiah closed 6 years ago

nathanjosiah commented 7 years ago

I have a form extending Zend\Form\Form implementing the Zend\InputFilter\InputFilterProviderInterface. One of my elements in my form is a Radio with some values and in my InputFilterProvider spec I have a NotEmpty validator with a custom message. Then, in my view I am using the FormRadio view helper to render the element which of course, also renders errors.

The problem, is that if the user submits the form witout selecting a radio option, my validators are not used and instead the default isEmpty message is used from the NotEmpty validator. There is no way to bypass or customize this as the logic prevents any other use. Either, it doesn't have a value but isn't required, or it doesn't have a value, is required, and then fails with the default message. Neither works for my use case as the message is not very nice to the user.

Unless I'm going to check for the default message or manually set the error when it isn't valid in my controller, I'm not sure what the best course of action is aside from making a PR that adds some type of customization to both Input and the factory.

froschdesign commented 6 years ago

@nathanjosiah Sorry for the late response!

Please try the following:

$form = new class extends Zend\Form\Form
    implements \Zend\InputFilter\InputFilterProviderInterface
{
    public function init()
    {
        $this->add(
            [
                'name' => 'foo',
                'type' => Zend\Form\Element\Radio::class,
            ]
        );
    }

    public function getInputFilterSpecification()
    {
        return [
            [
                'name'       => 'foo',
                'validators' => [
                    [
                        'name'    => Zend\Validator\NotEmpty::class,
                        'options' => [
                            'messages' => [
                                Zend\Validator\NotEmpty::IS_EMPTY => 'My empty message!',
                            ],
                        ],
                    ],
                ],
            ],
        ];
    }
};
$form->init();
$form->setData([]);
$form->isValid();

var_dump($form->getMessages());

This outputs:

array (size=1)
  'foo' => 
    array (size=1)
      'isEmpty' => string 'My empty message!' (length=17)

(Btw. the form element is not needed for this test and result.)

nathanjosiah commented 6 years ago

@froschdesign Looks like this is now a viable solution now that Zend\Form\Element\Radio checks to see if a NotEmpty validator is already in the chain before using the default. At the time I submitted this, that check didn't exist. Thank you!

froschdesign commented 6 years ago

@nathanjosiah Thanks for the feedback!