We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

How to dynamically specify a form element, check it or pass?

Hi. How to dynamically specify a form element, check it or pass? I found the following solution. Maybe there are even better

$form->get('name')->addValidator( new PresenceOf(
        array(
            'message' => 'The name is required'
        )
    ));

What exactly you want to achieve ?



12.4k

I want to some fields, depending on the conditions that were required, and others not.



12.4k

Like a Validation Group

In zend framework 2 I used the following code

$validationGroup[] = 'country';
$validationGroup[] = 'city';
$form->setValidationGroup($validationGroup);
edited Mar '16

So what's the problem with extending phalcon's form. Creating validation groups and add method like you want ?



145.0k
Accepted
answer
edited Mar '16

What yes ? So extend it and that's it :) I don't see any easier other option. You can extend phalcons' classes. For example you can create MyForm like this:

class MyForm extends Form
{
    private $groups;

    public function initialize()
    {
        $this->groups = array();
         // adding fields

         // creating groups
         $this->addValidationGroup('country',[
             'someField'=>new PresenceOf(array('message' => 'The name is required')),
             'someField1'=>new PresenceOf(array('message' => 'The name is required')),
             'someField2'=>new PresenceOf(array('message' => 'The name is required')),
         ]);
         $this->addValidationGroup('default',[
             'someField3'=>new PresenceOf(array('message' => 'The name is required')),
         ]);
         $this->setValidationGroups('default');
    }

    public function addValidationGroup($name,$arrayOfValidators)
    {
        $this->groups[$name] = $arrayOfValidators;
    }

    private function setValidationGroup($name)
    {
        if(isset($this->groups[$name])){
            foreach($this->groups[$name] as $field => $validator){
                if($this->has($field)){
                    $this->get($field)->addValidator($validator);
                }
            }
        }
    }

    public function setValidationGroups($validationGroups)
    {
        if(is_array($validationGroups)){
            foreach($validationGroups as $name){
                $this->setValidationGroup($name)
            }
        }
        else if(is_string($validationGroups)){
            $this->setValidationGroup($validationGroups)
        }
        else{
            throw new Exception();
        }
    }
}

Well i guess i could possibly add to phalcon Form some code like this - but is it really necessary ?



12.4k

My validation form depends on various conditions. In my case - it is really necessary



12.4k

Thanks for the good code "MyForm"

No problem :) If it's solve your problem then accept answer.