Gokul Shinde
Gokul Shinde

Reputation: 965

Remove validators and set required as false in controller

I have following code that creates a field for password.

// Element: password
$this->addElement('Password', 'password', array(
   'label' => 'Password',
   'description' => 'Passwords must be at least 6 characters long.',
   'required' => true,
   'allowEmpty' => false,
   validators' => array(
       array('NotEmpty', true),
       array('StringLength', false, array(6, 32)),
       )
  ));
$this->password->getDecorator('Description')->setOptions(array('placement' => 'APPEND'));
$this->password->getValidator('NotEmpty')->setMessage('Please enter a valid password.', 'isEmpty');

In my controller I need to remove the validators and make 'required' false from the controller depending upon some conditions.

For example:-

if($someCondition){
    //Set required to false and remove validator here somehow
}

Does any one know a solution for this case?

Upvotes: 2

Views: 7708

Answers (3)

Michael Krutikov
Michael Krutikov

Reputation: 484

In ZF3: Imagine you have a form class for validating a user input data

namespace Application\Form;

use Zend\Form\Form;
use Zend\Form\Element\Text;

class UserForm extends Form
{  
    public function __construct()
    {
        parent::__construct();

        $this->addElements();
        $this->addInputFilter();
    }

    /**
     * Add elements to the form
     */
    private function addElements()
    {
        $usernameElement = new Text('username');
        $usernameElement->setAttribute('id', 'username');

        $passwordElement = new Text('password');
        $passwordElement->setAttribute('id', 'password');

        $this->add($usernameElement)
            ->add($passwordElement);
    }

    /**
     * Add filters and validators
     */
    private function addInputFilter()
    {
        $inputFilter = $this->getInputFilter();

        $inputFilter->add([
            'name'       => 'username',
            'required'   => true,
            'filters'    => [
                [
                    'name' => 'StringTrim',
                ],
                [
                    'name' => 'StringToLower',
                ],
            ],
            'validators' => [
                [
                    'name'    => 'StringLength',
                    'options' => [
                        'min' => 1,
                        'max' => 255,
                    ],
                ],
                [
                    'name'    => 'Regex',
                    'options' => [
                        'pattern' => '/[a-z0-9_]+/',
                    ],
                ],
            ],
        ]);

    //  add filters and validators for other fields here..
}

/**
*  Make a set of fields required / not required
*/
    public function setFieldsRequirement(array $fieldNames, bool $isRequired = false)
    {
        foreach ($fieldNames as $fieldName) {
            $this->getInputFilter()
                ->get($fieldName)
                ->setRequired($isRequired);
        }
    }
}

Using in controller:

$form = new UserForm();
// get form data from POST params
$formData = $this->params()->fromPost();

$form->setData($formData);

// make username and password not required
$form->setFieldsRequirement(['username', 'password'], false);

if ($form->isValid()) {
   // from data processing...
}

Upvotes: 0

RockyFord
RockyFord

Reputation: 8519

is there any point in displaying a password form element that is not required and not validated? You may as well just remove the whole element from your controller.

//in your controller
$form->removeElement('Password');

also be aware that setting an element 'Required' and using the 'NotEmpty' validator is a little bit redundant as Zend_Form_Element uses the 'NotEmpty' validator to validate 'Required' in isValid(). So you don't need to set 'Required' to true if you use 'NotEmpty'.

Upvotes: 4

vascowhite
vascowhite

Reputation: 18440

If you have instantiated your form in the controller like this:-

$loginForm = new Application_Form_LoginForm();

Then you can set the attributes for the Password (or any other) element like this:-

if($someCondition){
    $loginForm->Password->setRequired(false);
    $loginForm->Password->setValidators(array());
}

Or, as Zend_Form_Element::setRequired() returns an instance of Zend_Form_Element, you can do this:-

if($someCondition){
    $loginForm->Password->setRequired(false)->setValidators(array());
}

Upvotes: 7

Related Questions