[英]Select2 Widget & Pjax Yii2
我正在尝试使用 Pjax( Yii2中的内置 Ajax 组件)在 TabularForm 中动态添加多个Select2小部件。 出于某种原因,Select2 输入在视图顶部的错误位置呈现(请参见下面的gif1 )。 据我了解,这个问题与 Select2 小部件特别相关,因为如果我使用一些默认组件,例如 Html::a(请参阅下面的gif2 ),一切都可以正常工作。
gif1 : https : //i.imgur.com/YMh5dNb.gif
gif2 : https : //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.