0
votes

I've a form containing array elements and I've to validate it. i cant validate it by using the in-built validation rules, because the elements are not present in the database. i'm serialising the data and save them in a single field in database. so i tried to do the validation with custom validation. my actual problem is the array field is validating but it doesn't shows the validation error message in the corresponding field.

This is the form

<div class="col-md-6">
    <?php Portlet::begin(['title' => t('Shipper')]) ?>

    <?= $form->field($model, 'shipper[name]')
        ->textInput(['maxlength' => true])->label(t('Name'))?>

    <div class="row">
        <div class="col-md-8">

            <?= $form->field($model, 'shipper[address_line1]')
                ->textInput(['maxlength' => true])->label(t('Address Line 1')) ?>

            <?= $form->field($model, 'shipper[address_line2]')
                ->textInput(['maxlength' => true])->label(t('Address Line 2')) ?>

       </div>
       <div class="col-md-4">

             <?= $form->field($model, 'shipper[city]')
                ->textInput(['maxlength' => true])->label(t('City')) ?>

             <?= $form->field($model, 'shipper[pin]')
                ->textInput(['maxlength' => true])->label(t('Pin Code')) ?>
      </div>
</div>

Model

.....
['shipper', function ($attribute, $params) {
   if (!filter_var($this->{$attribute}['email'], FILTER_VALIDATE_EMAIL)) {
         $this->addError('shipper', 'The email format is invalid!');
  }
}],
....
1

1 Answers

0
votes

You could add attributes to your model class like the following:

class MyModel extends \yii\db\ActiveRecord {
    public $shipperAddressLine1;
    public $shipperAddressLine2;
    public $shipperCity;
    public $shipperPin;
    ...
}

Then you can add validation rules for them just like your database attributes.