【问题标题】:Select2 Widget & Pjax Yii2Select2 小部件和 Pjax Yii2
【发布时间】:2020-10-30 12:54:57
【问题描述】:

我正在尝试使用 Pjax(Yii2 中的内置 Ajax 组件)在 TabularForm 中动态添加多个 Select2 小部件。由于某种原因,Select2 输入在视图顶部的错误位置呈现(请参阅下面的 gif1)。据我了解,这个问题与 Select2 小部件特别相关,因为如果我使用一些默认组件,例如,一切都可以正常工作。 Html::a(参见下面的 gif2)。

gif1https://i.imgur.com/YMh5dNb.gif

gif2https://i.imgur.com/sJkTDkO.gif

如何使用 Select2 小部件摆脱这种奇怪的行为?谢谢提前!

控制器:

class ProfileController extends Controller
{
// ...
    public function actionCreate()
    {   
        if (Yii::$app->request->isAjax) { 
            // some logic here ...
            return $this->renderAjax('object/create', [
                // ...
            ]);
        }
    }
// ...

}

查看:

// ...
use kartik\select2\Select2;
use kartik\select2\Select2Asset;

Select2Asset::register($this);

// a bunch of html code

<?php Pjax::begin(['id' => 'product-add']); ?>
    $form1 = ActiveForm::begin();
    $attribs = [
        'name' => [
         'type' => TabularForm::INPUT_RAW,
          'value' => function($productModel) { 
               return Select2::widget([
                   'name' => 'state_10',
                   'data' => ['1' => '1', '2' => '2'],
                   'pjaxContainerId' => 'product-add',
                   'options' => [
                       'placeholder' => $productModel->tmpId,
                       'multiple' => true
                   ],
               ]);
               //return Html::a('product ' . $productModel->tmpId); <- works fine if I use this piece of code
           },
    ],

    // ...

    Html::a("Add", ['profile/create'], ['class' => 'btn btn-primary'])

    // ...
    <?php ActiveForm::end(); ?>
<?php Pjax::end(); ?>

// ...

【问题讨论】:

    标签: php ajax yii2 jquery-select2 pjax


    【解决方案1】:

    经过仔细检查,我找到了解决方案。对于那些也将面临同样问题的人,您需要在 pjax 响应之前初始化您的小部件(在我的情况下为 Select2),例如在您的控制器中:

    class ProfileController extends Controller
    {
    // ...
        public function actionCreate()
        {   
            if (Yii::$app->request->isAjax) { 
                // some logic here ...
    
                // initialize the widget with an appropriate id
                $this->view->registerJs("$({$product->tmpId}).select2();"); 
    
                return $this->renderAjax('object/create', [
                    // ...
                ]);
            }
        }
    // ...
    
    }
    

    在您的视图中某处:

    Select2::widget([
        'id' => $productModel->tmpId, // set your unique id here
        'name' => $productModel->tmpId,
        'data' => ['1' => '1', '2' => '2'],
        // ...
    ]);
    

    【讨论】:

      猜你喜欢
      • 2015-11-14
      • 2016-07-14
      • 1970-01-01
      • 1970-01-01
      • 2016-12-03
      • 1970-01-01
      • 2019-10-19
      • 2017-11-07
      • 1970-01-01
      相关资源
      最近更新 更多