簡體   English   中英

Select2 Widget & Pjax Yii2

[英]Select2 Widget & Pjax Yii2

我正在嘗試使用 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(); ?>

// ...

經過一些仔細檢查后,我找到了解決方案。 對於那些也將面臨同樣問題的人,您需要在 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'],
    // ...
]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM