PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, February 27, 2022

[FIXED] Yii2: Either one field is required Validation

 February 27, 2022     active-form, php, validation, yii     No comments   

Issue

I have to implement the validation as mentioned in the title that either one of the two fields (email, phone) is required. I am doing this in my model:

[['email'],'either', ['other' => ['phone']]],

And this is the method:

 public function either($attribute_name, $params) {
        $field1 = $this->getAttributeLabel($attribute_name);
        $field2 = $this->getAttributeLabel($params['other']);
        if (empty($this->$attribute_name) && empty($this->$params['other'])) {
            $this->addError($attribute_name, Yii::t('user', "either {$field1} or {$field2} is required."));
            return false;
        }
        return true;
    }

When I access my index page, it gives me this error:

Exception (Unknown Property) 'yii\base\UnknownPropertyException' with message 'Setting unknown property: yii\validators\InlineValidator::0'

Any help?


Solution

The rule should be:

['email', 'either', 'params' => ['other' => 'phone']],

And method:

public function either($attribute_name, $params)
{
    $field1 = $this->getAttributeLabel($attribute_name);
    $field2 = $this->getAttributeLabel($params['other']);
    if (empty($this->$attribute_name) && empty($this->{$params['other']})) {
        $this->addError($attribute_name, Yii::t('user', "either {$field1} or {$field2} is required."));
    }
}


Answered By - Bizley
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing