tom-- / yii2-dynamic-ar

An extension to add NoSQL-like documents to Yii 2 Framework's Active Record ORM.
ISC License
57 stars 15 forks source link

Validation of nested attributes does not work #26

Open TomasMolnar opened 7 years ago

TomasMolnar commented 7 years ago

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?

djagya commented 7 years ago

@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.

TomasMolnar commented 7 years ago

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!