在yii2中,选择2如果该选项不存在,如何在数据库中添加值


in yii2 select2 how to add value in database if that option does not exists

如果yii2 select2中不存在,如何在数据库中添加类别。

<?= 
    $form->field($model, 'question_category')->widget(Select2::classname(), [
        'data' => ArrayHelper::map(Category::find()->all(),'category_name','category_name'),
        'maintainOrder' => true,
        'toggleAllSettings' => [
            'selectLabel' => '<i class="glyphicon glyphicon-ok-circle"></i> Tag All',
            'unselectLabel' => '<i class="glyphicon glyphicon-remove-circle"></i> Untag All',
            'selectOptions' => ['class' => 'text-success'],
            'unselectOptions' => ['class' => 'text-danger'],
        ],
        'options' => ['multiple' => true, 'placeholder' => 'Select a Category ...'],
        'pluginOptions' => [
            'tags' => true,
            'maximumInputLength' => 10
        ],
    ]);
?>

为Category创建一个模型类。以下代码将帮助您创建模型。

<?php
namespace app'models;
use Yii;
class Category extends 'yii'db'ActiveRecord
{
    
    public static function tableName()
    {
        return 'category';
    }
    
    public function rules()
    {
        return [
            [['category_code', 'category_name'], 'required'],
        ];
    }
   
 
    public static function find()
    {
        return new CategoryQuery(get_called_class());
    }
    
    
}