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 Android STD快速启动
  • ¥15 如何使用simulink建立一个永磁同步直线电机模型?
  • ¥30 天体光谱图的的绘制并得到星表
  • ¥15 PointNet++的onnx模型只能使用一次
  • ¥20 西南科技大学数字信号处理
  • ¥15 有两个非常“自以为是”烦人的问题急期待大家解决!
  • ¥30 STM32 INMP441无法读取数据
  • ¥15 R语言绘制密度图,一个密度曲线内fill不同颜色如何实现
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动