I’m using yii2 and I wanted to add some extra attributes and validation rules for them to the model after I call $model->createValidators().
But when I tried with the below code, at the line “$this->{$attr->code} = null”, it’s throwing the error: “Setting unknown property”.
public function rules(){
$rules = [];
if(!is_null($this->attributeSetId)){ // set the rules for custom attributes
foreach($this->attributeSet->attributeGroups as $group){
foreach($group->productAttributes as $attr){
if($attr->required=="1")
$rules[] = [[$attr->code], 'required'];
else
$rules[] = [[$attr->code], 'safe'];
$this->{$attr->code} = null; // trying to set new property to the model (this is the line causing error)
}
}
}
return array_merge([
[['attributeSetId', 'parent', 'typeId'], 'integer'],
[['attributeSetId'], 'required'],
], $rules);
}
I know properties can be declared to an object after we instantiate it using the above method but it’s not working in the above mentioned case.
When I manually set the properties as: “public $propertyName;” at the starting of the model, it’s working perfect but in my case, the properties list is dynamic.
Can someone throw some light on this please?