Sasha Sasha - 3 months ago 83
PHP Question

Yii2 - dynamic min and max value validation rules

How can I create dynamic min and max validation for specific item?

For buying I am using model Buy, and for products I am using model Products. I need to implement this rules in the Buy model.

Example - I am looking item with id 12, and this item have stock of 100 units (this needs to be maximum) and minimum order of 10 (this needs to be minimum).

EDIT:

Products (item) table:

id
name
stock
minOffer


Buy table:

id
offer
product_id
user_id


Offer for buying can't be larger then current stock in the product table.

Answer

Inside your Buy model,you can write your custom rule like one given below.

public function rules()
    {
        return [
            ['product_id', 'checkmaxandminvalues'],//assuming product_id is a field in Buy

            // other rules
        ];
    }

public function checkmaxandminvalues($attribute, $params)
{
    $your_product=Products::find()->where(['_id'=>$this->product_id])->one();

    //Here you do your validation logic
    if($your_product->_id === 12 && $your_product->stock > 100)
    {
        $this->addError('product_id', 'Product stock should not be greater than 100');
    }
   else if($your_product->_id===12 && $your_product->stock < 10)
   {

        $this->addError('product_id', 'Product stock should not be less than 10');
   }
}
Comments