2014-03-05 53 views
3

我想根据Yii模型中的条件验证字段。Yii需要基于条件的验证

我有两个领域在我看来

类型(单选):标准&特殊

项(文本框):任何文本数据

目前我显示项文本基于类型条件,即如果类型是特殊的,则显示o/w隐藏。

我想验证它使用Yii所需的规则,即如果用户选择单选按钮特殊,然后他必须填写术语文本域数据o/w它不是强制性的。

如果我使用特殊需要,那么它的验证在type = standard的情况下是错误的。我做了以下自定义验证,但它不工作。

public function rules() { 
    array('type', 'required'), 
    array('term', 'checkTerm', 'trigger' => 'type'), 
} 

public function checkTerm($attribute, $params) {   
    if ($this->$params['trigger'] == "Special") { 
     if (empty($attribute)) 
      $this->addError($attribute, 'Special term cannot be blank.'); 
    } 
} 

我去哪里错了?需要帮忙。由于

回答

3

试试这个:

public function rules() { 
    array('type', 'required'), 
    array('term', 'checkTerm'), 
} 

public function checkTerm() {   
    if ($this->type == "Special") { 
     if (empty($this->term)) 
      $this->addError("term", 'Special term cannot be blank.'); 
    } 
} 
+0

它的工作,但验证消息不低于显示足月文本字段。另外星号(*)不带标签显示。 – Sky

+0

检查更新,我认为这将解决显示错误文本问题,但老实说,我不知道星号符号。 –

+0

好的。谢谢..... – Sky

1

而不是

if (empty($attribute)) 
     $this->addError($attribute, 'Special term cannot be blank.'); 
} 

使用

if (empty($this->term)) 
     $this->addError($attribute, 'Special term cannot be blank.'); 
}