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.

Think Different
  • 2,815
  • 1
  • 12
  • 18

2 Answers2

1

I think you need separated model for company.

Konstantin
  • 566
  • 4
  • 9
  • 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? – Think Different Jul 22 '15 at 10:55
  • Then create custom rule for variable $company and manualy validate all elements. – Konstantin Jul 22 '15 at 14:38
  • @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. – tarleb Jul 22 '15 at 20:54
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

Aldo Bassanini
  • 475
  • 4
  • 16