Search code examples
validationmodelyii2ruleyii2-validation

yii2 Validation not working


I need to validate a value from another table both of them field type decimal

if amount(model 1) moreover available(model2 DATA selected)

model 1 rule

 public function rules()
{
    return [
           [['amount'], 'checkAvailable','skipOnEmpty' => false],
    ];
}

custom validation function

  public function checkAvailable($attribute, $params)
{
    $caid = $this->capex_budget_id;
    $available = Capexbudget::find()
            ->select(['available'])
            ->where('id = :caid', [':caid' => $caid])
            ->all();   // select amount from Capexbudget where id = $caid 
    if ($this->amount > $available){
     $this->addError('amount', 'not enough');
    }
}

i can got a data available from Capexbudget where ID that i select

here are the query logs

enter image description here

but validation not working it not compare value between $this->amount and $available what i missing please.


Solution

  • First of all, you're selecting all records matching your where conditions here:

        $available = Capexbudget::find()
            ->select(['available'])
            ->where('id = :caid', [':caid' => $caid])
            ->all();  // HERE
    

    You should change function all() to one(), to get one record. Second thing is, if you're using all() or one(), that methods returns object, not value.

    To make it work, you should change if statement to:

    if ($this->amount > $available->available){   //here, compare to attribute `available`