7

Is there a way to require an array of elements in the rules() method of a Yii model? For example:

public function rules()
{
   return array(
            array('question[0],question[1],...,question[k]','require'),
   );
}

I have been running into situations where I need to validate several arrays of elements coming from a form and I can't seem to find a good way of going about it other than doing the above. I have the same problem when specifying attributeLables(). If anyone has some advice or a better way of doing this I would really appreciate it.

3
  • dlnGd0nG, the link doesn't mention how to validate arrays of elements. Commented Feb 3, 2013 at 9:26
  • I thought you want to add tabular input. What are those question[x]? Are they class attributes ? and by Yii model you re referring to what? CActiveRecord,CfromModel or CModel ? Commented Feb 3, 2013 at 9:32
  • dlnGd0nG, the question[x] are name values of the forms I am submitting. The Yii model I mention are specifically CFormModels. Commented Feb 3, 2013 at 10:06

2 Answers 2

13

You can use the CTypeValidator aliased by type

public function rules()
{
   return array(
            array('question','type','type'=>'array','allowEmpty'=>false),
   );
}
Sign up to request clarification or add additional context in comments.

1 Comment

That's totally what I was looking for. I just aliased 'type', like you mentioned: array('question','CTypeValidator','type'=>'array','allowEmpty'=>false), and it worked perfectly. Thanks!
2

With array('question','type','type'=>'array','allowEmpty'=>false), you can just verify that you receive exactly array, but you don't know what inside this array. To validate array elements you should do something like:

<?php

class TestForm extends CFormModel
{
    public $ids;

    public function rules()
    {
        return [
            ['ids', 'arrayOfInt', 'allowEmpty' => false],
        ];
    }

    public function arrayOfInt($attributeName, $params)
    {
        $allowEmpty = false;
        if (isset($params['allowEmpty']) and is_bool($params['allowEmpty'])) {
            $allowEmpty = $params['allowEmpty'];
        }
        if (!is_array($this->$attributeName)) {
            $this->addError($attributeName, "$attributeName must be array.");
        }
        if (empty($this->$attributeName) and !$allowEmpty) {
            $this->addError($attributeName, "$attributeName cannot be empty array.");
        }
        foreach ($this->$attributeName as $key => $value) {
            if (!is_int($value)) {
                $this->addError($attributeName, "$attributeName contains invalid value: $value.");
            }
        }
    }
}

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.