1

When you are using Yii2's validation rules within a model, for example:

[['foo','bar'], 'integer],

Obviously ['foo','bar'] is an array, which I know you can use.

But can do pass a multi-dimensional array like this:

$this->numbers = [1,2,3];

[['foo','bar','numbers'], 'integer]

Will Yii2 accept this and check the correct data or will it test the value and return an error because numbers is an array?

Brett
  • 19,449
  • 54
  • 157
  • 290
  • Maybe [this](http://stackoverflow.com/a/30300977/57091) will help you, if you want to create a validation with certain allowed values. Do you mean foo and bar may only have value 1, 2 or 3? – robsch Sep 27 '15 at 17:49
  • Or numbers should be an integer array? Yes, that needs to be defined separately from foo and bar if these attributes are 'normal' integers. – robsch Sep 27 '15 at 18:00
  • @robsch Yep, the second one. I have moved them to using the `each` validator. – Brett Sep 28 '15 at 06:06

1 Answers1

3

You need merge arrays for work rules

[ArrayHelper::merge(['foo','bar'], $this->getNumberFields()), 'integer']

Update:

Use each rule. See EachValidator.

public function rules()
{
    return [
        ['numbers', 'each', 'rule' => ['integer']],
    ]
}
Onedev_Link
  • 1,981
  • 13
  • 26
  • What is `$this->getNumberFields()`? – Brett Sep 27 '15 at 13:25
  • Function in your model that return field names array like `['dynamicIntegerFieldOne', 'integerFieldTwo']`. – Onedev_Link Sep 27 '15 at 13:30
  • But I would just want to pass it the property name Like I do with `foo` & `bar`. I guess I was just checking if it could all be done within the one rule, if not I will just use the `each` validator on a second rule. :) – Brett Sep 27 '15 at 13:34
  • 1
    @Brett `[ArrayHelper::merge(['foo','bar'], $this->numbers), 'integer']` could work. The rule will always be re-created when validation takes place. So `$this->numbers` can change from one to the next validation, if this is important. – robsch Sep 27 '15 at 15:20
  • @robsch So why would you use `$this->numbers` rather than just `numbers` - aren't you supposed to provide the property name and not it's value? – Brett Sep 27 '15 at 17:16
  • 1
    @Brett Not sure what you mean. If you do the merge integer validations would be done for 5 attributes: foo, bar, dog, cat, fish. Those attributes should have integer values. They don't need to be explicitly declared, but they would be expected to exist when validation takes place. Isn't this what you wanted? – robsch Sep 27 '15 at 17:29
  • Oh no, sorry, my fault for not being clear enough. `numbers` is the example attribute name which contains an *array* of values. Sorry for making it seem like it was an array of property names, I have updated my post. – Brett Sep 27 '15 at 17:40
  • 1
    @brett Yii2 will get error. If rule integer, therefore numbers should be integer. You need `each` rule. – Onedev_Link Sep 27 '15 at 17:49