0

Being trying to sort this out but going nowhere with it. I have got an array as attribute for a model and I am trying to create custom validation for some of the keys in the array as required. Or even can't figure out how the attribute labels will work? Here is my code:

MODEL

 ...
 public $company = [
                    'name'                  => '',
                    'trading_name'          => '',
                    'type'                  => '',
                ];

 public function attributeLabels(){
    return [
            'company[name]' => 'Company Name',
    ];
 }   

 public function rules(){

    return [
             [['company[name]','company[trading_name'], 'safe'],
             [['company[name]'], 'return_check','skipOnEmpty'=> false],

    ];
 }  

 public function return_check($attribute, $params){

    $this->addError($attribute  ,'Required ');
    return false;
 }
 ...

I have even tried to pass the whole array and check in the validator method for the keys and values but the custom validator is not even triggered.

2 Answers 2

1

I think you need separated model for company.

Sign up to request clarification or add additional context in comments.

3 Comments

Yes if I create different Models and then using ActiveForms generate the form, it might do the validation but my issue is that I want to skip ActiveRecords. Is there any other way? And for simple attributes (not arrays) still custom validator is not triggered. Am I missing something?
Then create custom rule for variable $company and manualy validate all elements.
@ThinkDifferent You don't need to let your model inherit from ActiveRecord, just use yii\base\Model. It is lightweight but allows you to do all kinds of validations. Yii encourages class-based object oriented programming; if you try to work against that, you'll have a bad time.
0

I've used custom rule functions, and they all worked. Try removing the return clause at the end of the return_check function.

Here's what has worked for me:

class Essid extends ActiveRecord {
    public function rules() {
        return [
            ['network_name', 'checkNetworkName']
        ]
    }

    public function checkNetworkName($attribute, $params){
        if (!$this->hasErrors()) {
            if ( !ctype_alnum($this->network_name) )
                $this->addError($attribute, Yii::t('app', 'Not a valid Network Name'));
        }
    }
}

Hope it helps

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.