3

How to validate two dimensional array in Yii2.

 passenger[0][name] = bell
 passenger[0][email] = [email protected]
 passenger[1][name] = carson123
 passenger[1][email] = carson##@test.com

how to validate the name and email in this array

Thanks

3

1 Answer 1

1

Probably the most clean solution for validating 2-dimensional array is treating this as array of models. So each array with set of email and name data should be validated separately.

class Passenger extends ActiveRecord {

    public function rules() {
        return [
            [['email', 'name'], 'required'],
            [['email'], 'email'],
        ];
    }
}

class PassengersForm extends Model {

    /**
     * @var Passenger[]
     */
    private $passengersModels = [];

    public function loadPassengersData($passengersData) {
        $this->passengersModels = [];
        foreach ($passengersData as $passengerData) {
            $model = new Passenger();
            $model->setAttributes($passengerData);
            $this->passengersModels[] = $model;
        }

        return !empty($this->passengers);
    }

    public function validatePassengers() {
        foreach ($this->passengersModels as $passenger) {
            if (!$passenger->validate()) {
                $this->addErrors($passenger->getErrors());
                return false;
            }
        }

        return true;
    }
}

And in controller:

$model = new PassengersForm();
$model->loadPassengersData(\Yii::$app->request->post('passenger', []));
$isValid = $model->validatePassengers();

You may also use DynamicModel instead of creating Passanger model if you're using it only for validation.


Alternatively you could just create your own validator and use it for each element of array:

public function rules() {
    return [
        [['passengers'], 'each', 'rule' => [PassengerDataValidator::class]],
    ];
}

You may also want to read Collecting tabular input section in guide (unfortunately it is still incomplete).

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.