2014-03-31 09:27


  • yii
  • validation
  • php

Either I don't understand how CCompareValidator works in Yii (sic!) or it doesn't work for me at all.

I want to check, if an ID of row / record / user being updated isn't the same, as an ID of currently logged-in user. And prohibit update, if it is.

I used CCompareValidator at first:

array('id', 'compare', 'compareValue'=>Yii::app()->user->id, 'message'=>'Boom!')

It doesn't work -- it halts editing / update of every row / record / user, no matter, what an ID actually is.

So, I rewrote it to my own, custom validator. In my opinion, the code is the same as in case of built-in one:

array('id', 'compareId', 'compareValue'=>Yii::app()->user->id, 'message'=>'Boom!')

public function compareId($attribute = null, $params = null)
    if($attribute === 'id')
        if($this->id == $params['compareValue'])

It works like a charm -- allows update of any row / record / user, which ID is different than currently logged-in user's ID. Blocks update, showing defined message, in case compared IDs are equal.

What am I missing? Why original Yii's built in validator fails on such simple example, while my own works?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答


  • donglie7778 donglie7778 7年前

    The validator works, as supposed, my logic have failed:

    1. CCompareValidator, throws an error, when two compared values are not equal. On the other hand, if they're equal -- it passes validation without errors. That is supposed behavior.

    2. I wanted an error, when values are equal (which means, that user is attempting to edit himself or herself) and pass as validated, when both values are different (logged user edits different one).

    That's why I need to use 'operator'=>'!=' as configuration of validator. This is the answer.

    BTW: All the glory of solving this problem goes to Keith at YiiFramework.com's forum.

    点赞 评论 复制链接分享