/** * @inheritdoc */ public function init() { $linkTags = function ($event) { if ($this->tagIds === null) { return; } if (!is_array($this->tagIds)) { $this->tagIds = []; } $whereIds = $models = $newTagIds = []; foreach ($this->tagIds as $tagId) { if (empty($tagId)) { continue; } if (preg_match("/^\\d+\$/", $tagId)) { $whereIds[] = $tagId; continue; } // если tagId не число, то значит надо создать новый тег if (!($tag = Tag::findOne(['name' => $tagId]))) { $tag = new Tag(); $tag->name = $tagId; if (!$tag->save()) { continue; } } $newTagIds[] = $tag->id; $models[] = $tag; } $this->unlinkAll('tags', true); if ($whereIds) { $models = array_merge($models, Tag::find()->where(['id' => $whereIds])->all()); } foreach ($models as $model) { $this->link('tags', $model); } // что бы после сохранения в значение были новые теги $this->tagIds = array_merge($whereIds, $newTagIds); }; $this->on(static::EVENT_AFTER_INSERT, $linkTags); $this->on(static::EVENT_AFTER_UPDATE, $linkTags); }
<?php use pendalf89\filemanager\Module; use pendalf89\filemanager\models\Tag; use yii\helpers\ArrayHelper; use yii\helpers\Html; use yii\bootstrap\ActiveForm; /* @var $this yii\web\View */ $form = ActiveForm::begin(['action' => '?', 'method' => 'get']); ?> <?php echo $form->field($model, 'tagIds')->widget(\kartik\select2\Select2::className(), ['maintainOrder' => true, 'data' => ArrayHelper::map(Tag::find()->all(), 'id', 'name'), 'options' => ['multiple' => true], 'addon' => ['append' => ['content' => Html::submitButton(Module::t('main', 'Search'), ['class' => 'btn btn-primary']), 'asButton' => true]]])->label(false); ActiveForm::end();
echo Html::a(Module::t('main', 'Delete'), ['file/delete/', 'id' => $model->id], ['class' => 'text-danger', 'data-message' => Yii::t('yii', 'Are you sure you want to delete this item?'), 'data-id' => $model->id, 'role' => 'delete']); ?> </li> </ul> <div class="filename"><?php echo $model->filename; ?> </div> <?php $form = ActiveForm::begin(['action' => ['file/update', 'id' => $model->id], 'enableClientValidation' => false, 'options' => ['id' => 'control-form']]); ?> <?php echo $form->field($model, 'tagIds')->widget(\kartik\select2\Select2::className(), ['id' => 'update-image-tag', 'maintainOrder' => true, 'data' => ArrayHelper::map(Tag::find()->all(), 'id', 'name'), 'options' => ['multiple' => true], 'pluginOptions' => ['tags' => true, 'maximumInputLength' => 10, 'createTag' => new \yii\web\JsExpression("function (params) {\n if (/^\\d+\$/.test(params.term)) {\n return null;\n }\n return {id: params.term, text: params.term};\n }")]]); ?> <?php if ($model->isImage()) { ?> <?php echo $form->field($model, 'alt')->textInput(['class' => 'form-control input-sm']); ?> <?php } ?> <?php echo $form->field($model, 'description')->textarea(['class' => 'form-control input-sm']); ?>