yii2-dynamic-ar icon indicating copy to clipboard operation
yii2-dynamic-ar copied to clipboard

Validation of nested attributes does not work

Open TomasMolnar opened this issue 8 years ago • 2 comments

If you try to validate nested attributes, it does not work - so even your example is wrong:

public function rules()
    {
        return [['dimensions.length', 'double', 'min' => 0.0]];
    }

Validation of nested attributes can't work due to fact, that yii\validators\Validator uses $model->$attribute instead of $model->getAttribute($attribute) in validateAttribute($model, $attribute) method:

public function validateAttribute($model, $attribute)
    {
    	$result = $this->validateValue($model->$attribute);
        
        if (!empty($result)) {
            $this->addError($model, $attribute, $result[0], $result[1]);
        }
    }

How to overcome this issue? We could override the validateAttribute() method of yii\validators\Validator class in our own inhered class and create a Standalone Validator for every validator type we want to use for nested dynamic attributes. Is there a better way?

TomasMolnar avatar Nov 15 '17 16:11 TomasMolnar

@TomasMolnar $model->$attribute uses DynamicActiveRecord::__get($name) internally, that also uses $model-> getAttribute($name), so validation is functional (just tested it locally too).

I found that we don't have unit tests for this case, we'll add them. But if validation doesn't work in your case, it must be something else.

djagya avatar Nov 15 '17 17:11 djagya

Thanks @djagya for your quick response. You are right, the issue was caused by forgotten JsonBehavior, which was tied to the same attribute. I was playing around with the best method of saving schemaless data :) BTW thanks for this great extension!

TomasMolnar avatar Nov 15 '17 20:11 TomasMolnar