1

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.

7
  • It would be nice if you can list all fields in your view and specify each field belonging to which model Commented Aug 9, 2016 at 16:41
  • @KiranMuralee - I added table description. Commented Aug 9, 2016 at 16:58
  • So you are saying like if item id value equals 12,then stock max should be 100.Why not use a custom validator. Commented Aug 9, 2016 at 17:03
  • I need a custom validator, but I need to insert id from the product into the Buy validation. I don't know how to do this. Yet :) Commented Aug 9, 2016 at 17:05
  • @sasha.I assume buy is having a relation with the product.So in the buy model,there is a definite product object which you can make use of .If you can show me your Buy and Product models,I will get a clear picture and I would be able to suggest how the custom validation code would be :). Commented Aug 9, 2016 at 17:17

1 Answer 1

2

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');
   }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.