dpmfur2635 2014-03-31 09:27
浏览 34
已采纳

Yii的CCompareValidator不起作用

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'])
        {
            $this->addError($params['message']);
        }
    }
}

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?

  • 写回答

1条回答 默认 最新

  • donglie7778 2014-03-31 10:13
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 深度学习残差模块模型
  • ¥20 两个不同Subnet的点对点连接
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0
  • ¥15 C#如何调用串口数据
  • ¥15 MATLAB与单片机串口通信
  • ¥15 L76k模块的GPS的使用
  • ¥15 请帮我看一看数电项目如何设计
  • ¥23 (标签-bug|关键词-密码错误加密)