|
1 | 1 | #Single column example
|
2 | 2 |
|
| 3 | + |
| 4 | + |
3 | 5 | For example your application contains the model `User` that has the related model `UserEmail`
|
4 | 6 | You can add virtual attribute `emails` for collect emails from form and then you can save them to database.
|
5 | 7 |
|
6 | 8 | In this case you can use `yii2-multiple-input` widget for supporting multiple inputs how to describe below.
|
7 | 9 |
|
8 | 10 | First of all we have to declare virtual attribute in model
|
9 | 11 |
|
10 |
| -``` |
| 12 | +```php |
11 | 13 | class ExampleModel extends Model
|
12 | 14 | {
|
13 | 15 | /**
|
14 | 16 | * @var array virtual attribute for keeping emails
|
15 | 17 | */
|
16 | 18 | public $emails;
|
17 |
| -``` |
| 19 | +``` |
| 20 | + |
| 21 | +Then we have to use `MultipleInput` widget for rendering form field in the view file |
| 22 | + |
| 23 | +```php |
| 24 | +use yii\bootstrap\ActiveForm; |
| 25 | +use unclead\widgets\MultipleInput; |
| 26 | +use unclead\widgets\examples\models\ExampleModel; |
| 27 | +use yii\helpers\Html; |
| 28 | + |
| 29 | +/* @var $this \yii\base\View */ |
| 30 | +/* @var $model ExampleModel */ |
| 31 | +?> |
| 32 | + |
| 33 | +<?php $form = ActiveForm::begin([ |
| 34 | + 'enableAjaxValidation' => true, |
| 35 | + 'enableClientValidation' => false, |
| 36 | + 'validateOnChange' => false, |
| 37 | + 'validateOnSubmit' => true, |
| 38 | + 'validateOnBlur' => false, |
| 39 | +]);?> |
| 40 | + |
| 41 | +<?= $form->field($model, 'emails')->widget(MultipleInput::className(), [ |
| 42 | + 'limit' => 4, |
| 43 | + ]); |
| 44 | +?> |
| 45 | +<?= Html::submitButton('Update', ['class' => 'btn btn-success']);?> |
| 46 | +<?php ActiveForm::end();?> |
| 47 | +``` |
| 48 | + |
| 49 | +Options `limit` means that user able to input only 4 emails |
| 50 | + |
| 51 | +For validation emails you can use the following code |
| 52 | + |
| 53 | +```php |
| 54 | + /** |
| 55 | + * Email validation. |
| 56 | + * |
| 57 | + * @param $attribute |
| 58 | + */ |
| 59 | + public function validateEmails($attribute) |
| 60 | + { |
| 61 | + $items = $this->$attribute; |
| 62 | + |
| 63 | + if (!is_array($items)) { |
| 64 | + $items = []; |
| 65 | + } |
| 66 | + |
| 67 | + foreach ($items as $index => $item) { |
| 68 | + $validator = new EmailValidator(); |
| 69 | + $error = null; |
| 70 | + $validator->validate($item, $error); |
| 71 | + if (!empty($error)) { |
| 72 | + $key = $attribute . '[' . $index . ']'; |
| 73 | + $this->addError($key, $error); |
| 74 | + } |
| 75 | + } |
| 76 | + } |
| 77 | +``` |
0 commit comments