javascript - Yii2 在 yii2-formwizard 的表格步骤中使用 Select2

标签 javascript yii2 kartik-v yii2-formwizard

我正在使用 yii2-formwizard在我使用 kartik\select2 的项目中,这是一个方便的工具。一切正常,除了当我按下添加以获取下一组时,select2 上一组的下拉列表消失了。

当我按照我之前的 post 中的解释修改我的 Controller 以从我的模型捕获数据时,就会发生这种情况。 ,我在脚本方面遗漏了一些东西我在 jquery/JS 等方面有点差,除了数据被保存和小部件工作完美之外

我的 Controller

<?php

public function actionCreatemulti()
{
    $this->layout = 'layout2';
    $model = [new Todelete()];
    $sex = [['id' => 1, 'name' => 'male'], ['id' => 2, 'name' => 'female']];

    if (Yii::$app->request->isPost) {

        $count = count(Yii::$app->request->post('Todelete', []));
        //start the loop from 1 rather than 0 and use the $count for limit
        for ($i = 1; $i < $count; $i++) {
            $model[] = new Todelete();
        }

        if (Model::loadMultiple($model, Yii::$app->request->post()) && Model::validateMultiple($model)) {
            foreach ($model as $md) {
                $md->save(false);
            }
            return $this->render('index');
        }
    }

    return $this->render('create', [
        'model' => $model,
        'sex' => $sex
    ]);
}

我的看法

echo FormWizard::widget(
    [
        'formOptions' => [
            'id' => 'my_form_tabular'
        ],
        'steps' => [
            [
                //should be a single model or array of Activerecord model objects but for a single model only see wiki on github
                'model' => $model,

                //set step type to tabular
                'type' => FormWizard::STEP_TYPE_TABULAR,

                'fieldConfig' => [
                    'sex' => [
                        'widget' => Select2::class,
                        'containerOptions' => [
                            'class' => 'form-group'
                        ],
                        'options' => [
                            'data' => $data,
                            'options' => [
                                'class' => 'form-control'
                            ],
                            'theme' => Select2::THEME_BOOTSTRAP,
                            'pluginOptions' => [
                                'allowClear' => true,
                                'placeholder' => 'Select sex'
                            ]
                        ],

                        //set tabular events for select2 fix which doesnot work correctly after cloning

                        'tabularEvents' => [

                            'beforeClone' => "function(event, params){
                                //fix for select2 destroy the plugin

                                let element = $(this);
                                element.select2('destroy');
                            }",
                            "afterClone" => "function(event, params){

                                //bind select2 again after clone

                                let element = $(this);
                                let elementId = $(this).attr('id');
                                let dataKrajee = eval(element.data('krajee-select2'));
                                let dataSelect2Options = element.data('s2-options');
                                $.when(element.select2(dataKrajee)).done(initS2Loading(elementId, dataSelect2Options));
                            }",
                            "afterInsert" => "function(event,params){
                                //initialize the options for the select2 after initializing
//changed according to my environment

                                let selectElement = $(this).find('.field-todelete-'+params.rowIndex+'-sex > select');
                                let dataKrajee = eval(selectElement.data('krajee-select2'));
                                selectElement.select2(dataKrajee);
                            }"
                        ]
                    ]
                ]
            ]

        ]
    ]
);

https://cdn1.imggmi.com/uploads/2019/8/31/158dc0f338e0d780747c5f72fa2ed6bb-full.png https://cdn1.imggmi.com/uploads/2019/8/31/4e394e87aa162d3f457c32af8d30373b-full.png

最佳答案

原因

您指出的问题确实存在,您说得对。但是这个问题与最近对 kartik\select2 @V2.1.4 的更改有关。演示链接使用的是旧版本的 select2 V2.1.3,它没有此 dataset 属性已定义,因此可以正常工作。

小部件没有集成所有这些更改,并留给了正在集成小部件的用户

The reason is that it won't be possible to control it correctly inside the plugin as there could be any widget a user wants to use and going to keep adding the code for every other widget isn't what I would vote for. So a better approach would be to provide the event triggers for the specific actions which require a pre or post-processing of an element, where according to the needs the user can adjust his code

疑难解答

现在关于这个问题,有一个新的数据集属性 data-select2-id,它包含 select2 绑定(bind)到的输入的名称,并且在克隆之后该属性未更新为较新元素 ID 的新元素,这导致您的旧选择元素消失。

请看下面的图片,它来 self 自己的代码,所以请忽略 address-0-city 字段名称,因为它与您的代码无关,仅供理解

enter image description here

解决方案

所以我们需要将afterInsert事件中的代码改成下面的代码

let selectElement = $(this).find('.field-todelete-'+params.rowIndex+'-sex > select');
let dataKrajee = eval(selectElement.data('krajee-select2'));

//update the dataset attribute to the
if (typeof selectElement[0].dataset.select2Id !== 'undefined') {

    //get the old dataset which has the old id of the input the select2 is bind to 
    let oldDataSelect2Id = selectElement[0].dataset.select2Id;

    //delete the old dataset
    delete selectElement[0].dataset.select2Id;

    //add the new dataselect pointing to the new id of the cloned element
    let newDataSelect2Id = oldDataSelect2Id.replace(
    /\-([\d]+)\-/,
    '-' + parseInt(params.rowIndex) + '-'
    );

    //add the new dataset with the new cloned input id 
    selectElement[0].dataset.select2Id= newDataSelect2Id;
}
selectElement.select2(dataKrajee);

我将在接下来的几天内更新 wiki 文档上的代码和代码示例以及演示。

希望对你有所帮助。

关于javascript - Yii2 在 yii2-formwizard 的表格步骤中使用 Select2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57737968/

相关文章:

php - 使用 authclient 的 Yii2 框架 facebook 和 google 登录不起作用

php - 如何与Yii2 faker数据库关联

checkbox - yii2\kartik\grid\CheckboxColumn

javascript - 如何对齐输入组插件的宽度

javascript - 使用Jquery控制表宽度问题

javascript - Office.context.document.getFileAsync 抛出错误

javascript - 如何编写 jQuery/JS 函数以使其返回值?

javascript - ActiveRecord 自定义验证器在调用 form.yiiActiveForm ("validate"时不执行)

yii2 - 无法安装 Kartik 对话框

javascript - Yii2:从 gridView 复选框列中获取选定的行数据到 Controller 中