phpvalidationyiiyii-cmodel

How to edit validation rules dynamically in Yii


I have a validation rules in my model:

public function rules()
{
  return array(){
   array('order', 'required'),
  }
}

I have an input text element in my order view:

input type="text" name="order1"

when I press a button, my input text element have increased, so now I have 2 input text element with different name. e.g:

input type="text" name="order1"
input type="text" name="order2"

My question is: how can i edit validation rules dynamically, so when "order1" or "order2" is null, there are a validation message. Thanks.


Solution

  • I would have different approach to the problem. Instead of having inputs with name = order1, order2, orderN, have an array like this <input type="text" name="orders[]" /> And in the model, always expect array of orders, loop through it and if any of items does not validate, add an error.

    class SomeModel
    {
     public $orders;
     public function rules()
     {
      return array(
       array('orders', 'validateOrders'),
      );
     }
    
     public function validateOrders($attribute, $params)
     {
      foreach($this->orders as $order)
       if (empty($order)) {
        $this->addError('orders', 'There is an empty order');
        break;
       }
     }
    }
    

    The above code is written on the go here and is untested but should closely show my idea.