0

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.

tereško
  • 58,060
  • 25
  • 98
  • 150

1 Answers1

3

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.

ddinchev
  • 33,683
  • 28
  • 88
  • 133
  • Thank you! I doesn't know that something like that is possible in Yii. I'm still beginner :) – Yohanes Raymond Aug 24 '11 at 06:58
  • You don't even need the brackets to be honest, it will become an array no matter what its called assuming there are two inputs with the same name. – Al Katawazi Aug 24 '11 at 15:01
  • That is correct. But explicitly writing the inputs like this is helpful for PHP developers to understand your intentions :) – ddinchev Aug 24 '11 at 20:48