验证值不能小于0

时间:2016-08-26 06:52:41

标签: php yii2 yii2-advanced-app

我在Yii2上有这个表格

Employee Name   : N1
Apply Date      : 2016-08-26
Start Date      : 2016-08-29
Days Leave      : 4 Days
Days Leave Left : 8
Status          : Pending

我预期的结果是,当我在休假时输入9天时,表格将验证

"Maximum Quota is Exceeded,Cannot Input"

这是我的模特让天离开

  public function daysleaveleft($id,$year) {
        $models = Leave::find()->select(['daysleave'=>'sum(daysleave)'])->where(['EmpId' => $id,'year(startdate)'=>$year])->One();

        $setting = Setting::find()->where(['Var'=>'MaxLeave'])->One();
        return $Setting->Val - $models['daysleave'];            
    }

被修改

Days Leave | Days Leave Left
    0      |       12
    4      |       8
    3      |       5
    6      |      -1

我希望结果会像这样,当用户输入6时,当他剩下5个配额时,表格将会验证。

1 个答案:

答案 0 :(得分:1)

您可以使用inline validator

在您的规则中添加:

['field_name', 'integer', 'min' => 1],
['field_name', 'validateLeaveDays', 'when' => $this->startdate && $this->EmpId]

并向您的Leave模型添加:

public function validateLeaveDaysLeft($attribute) {
    $year = date('Y', strtotime($this->startdate));
    $maxLeaveDays = $this->daysleaveleft($this->EmpId, $year);
    if ($this->$attribute < $maxLeaveDays) {
        $this->addError($attribute, 'Maximum Quota is Exceeded,Cannot Input');
    }
}

虽然使维护更容易

  1. daysleaveleft重命名为getLeaveDaysLeft或更好地描述功能。
  2. getLeaveDaysLeft功能移动到员工模型中。这也将消除传递ID的需要,因为您可以使用$this->id
  3. 确保您的Leave模型与员工有关系。
  4. 这会将您的验证器功能更改为:

    public function validateLeaveDaysLeft($attribute) {
        $year = date('Y', strtotime($this->startdate));
        $maxLeaveDays = $this->employee->getLeaveDaysLeft($year);
        if ($this->$attribute < $maxLeaveDays) {
            $this->addError($attribute, 'Maximum Quota is Exceeded,Cannot Input');
        }
    }