Compare Against Related Model's Attribute

Hi,

I would like to compare one of a newly created model’s attributes against a related model’s attribute when validating.

Can somebody please point me to the right direction?

I’m searching since a while and do not really find any useful informations.

Thanks a lot!

BR

c

Post your code.

I’ve tried like so (in model):




    public function compareWithRelatedModelAttribute() {

        $szeriaGyartmany = SzeriaGyartmany::model()->findByPk($this->szeriaGyartmanyId);


        if ($szeriaGyartmany->db < $this->db) {

            $this->addError('db', Yii::t('validation', "Error: $szeriaGyartmany->db is less than what you have tried to save, you can't save more than what is allowed."));

        }

    }


    public function rules() {

        return array(

            array('db', 'compareWithRelatedModelAttribute'),

        );

    }



Have you firstly read this?

http://www.yiiframework.com/wiki/168/create-your-own-validation-rule/

yes, and maybe my logic is wrong, but I don’t really see here how can I reach related model’s attribute.




    public function compareWithRelatedModelAttribute($attribute, $params) {

        $szeriaGyartmany = SzeriaGyartmany::model()->findByPk($this->szeriaGyartmanyId);


        if ($szeriaGyartmany->db < $this->db) {

            $this->addError('db', Yii::t('validation', "Error: $szeriaGyartmany->db is less than what you have tried to save, you can't save more than what is allowed."));

        }

    }


    public function rules() {

        return array(

            array('db', 'compareWithRelatedModelAttribute'),

        );

    }



I’ve put $attribute, $params to your compareWithRelatedModelAttribute function.

Have you troubleshooted your code?

I guess I slowly realize what the problem is. I have a similar solution on an update form, and it’s working without $attribute, $params. But in an update, the model already exists and has values. But here, I would like to create a new model, and I guess that’s why it’s not working. So I guess I can’t access the submitted values from the form in the model, right? Maybe my logic is completely wrong, but now I guess this is the problem. Can somebody please help me a little bit to understand?

Thanks a lot!

Hi guys,

here is the answer. Thanks a lot!

BR

c