Yii2:使用Pjax更新网格视图 [英] Yii2: Updating Grid-view using Pjax

查看:105
本文介绍了Yii2:使用Pjax更新网格视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

继维基 Yii 2.0:Pjax on ActiveForm和GridView - Yii2



我尝试使用我的gridview在Ajax上进行更新,而无需重新加载页面,但无法成功。 b
$ b

我的_form.php代码

 < php 
$ b $ this-> registerJs(
'$(document)。ready(function(){
$(#new_medicine)。on(pjax :end(); function(){
$ .pjax.reload({container:#medicine}); // Reload GridView
});
});'
);
?>


<?php

使用yii\helpers\Html;
使用yii\widgets\ActiveForm;
使用kartik \grid\GridView;
//使用yii\grid\Gridview;
使用yii\data\ActiveDataProvider;
$ b $ * @var $这个yii\web\View * /
/ * @var $模型app\models\Medicine * /
/ * @var $ form yii\widgets\ActiveForm * /
?>
<! - < div class =row>
< div class =col-lg-6 col-lg-offset-3> - >
< div class =medicine-form>
<?php yii\widgets\Pjax :: begin(['id'=>'new_medicine'])?>>

<?php $ form = ActiveForm :: begin(['options'=> ['data-pjax'=> true]]); ?>

<?= $ form->字段($ model,'medicine_id') - > textInput(['maxlength'=> 10])?>

<?= $ form->字段($ model,'medicine_name') - > textInput(['maxlength'=> 50])?>

< div class =form-group>
<?= Html :: submitButton($ model-> isNewRecord?'Create':'Update',['class'=> $ model-> isNewRecord?'btn btn-success':' btn btn-primary'])?>>
<?= Html :: submitButton($ model-> isNewRecord?'Save& New':'',$ option = ['class'=> $ model-> isNewRecord?'btn btn -success':'btn btn-primary','name'=>'save_and_new'])?>>
< / div>

<?php ActiveForm :: end(); ?>
<?php yii\widgets\Pjax :: end()?>

< / div>

我的控制器中的代码

  public function actionIndex()
{
$ model = new Medicine();
$ b $ if if($ model-> load(Yii :: $ app-> request-> post())&& $ model-> save())
{
$ model = new Medicine(); //重置模型
}
$ searchModel = new MedicineSearch();
$ dataProvider = $ searchModel->搜索(Yii :: $ app-> request-> queryParams);

return $ this-> render('index',[
'searchModel'=> $ searchModel,
'dataProvider'=> $ dataProvider,
'model'=> $ model,
]);
}

index.php中的代码

 <?php 

使用yii \helpers\Html;
使用yii\grid\GridView;

/ * @var $ this yii\web\View * /
/ * @var $ searchModel app \models\MedicineSearch * /
/ * @var $ dataProvider yii\data\ActiveDataProvider * /

$ this-> title ='Medicines';
$ this-> params ['breadcrumbs'] [] = $ this-> title;
?>
< div class =medicine-index>

< h1><?= Html :: encode($ this-> title)?>< / h1>
<?php // echo $ this-> render('_ search',['model'=> $ searchModel]); ?>

< p>
<?= Html :: a('Create Medicine',['create'],['class'=>'btn btn-success'])?>>
< / p>
<?php \yii\widgets\Pjax :: begin(['id'=>'medicine']); ?>
<?= GridView :: widget([
'dataProvider'=> $ dataProvider,
'filterModel'=> $ searchModel,
'columns'=> [
['class'=>'yii\grid\SerialColumn'],

'id',
'medicine_id',
'medicine_name' ,

['class'=>'yii\grid\ActionColumn'],
],
]); ?>
<?php \yii\widgets\Pjax :: end(); ?>
< / div>

我认为我非常仔细地遵循了这些说明,但是肯定我缺少一些网格视图没有显示新的记录没有页面重新加载。



任何帮助将不胜感激。
Thanks。

解决方案

尝试解释如何将其作为一个小部件来完成;这是一个通用的解决方案,所以在发生问题时与我联系:

控制器(@ your-alias / controllers / yourController):

  ... 
public function actionManage($ param =''){
$ model = new YourModel(); (Yii :: $ app-> request-> isPjax&& $ model-> load(Yii :: $ app-> request-> post()) && $ model-> save())
{
$ model = new YourModel(); //重置模型
}
$ model-> paramId = $ param;
$ queryParams = Yii :: $ app-> request-> getQueryParams();
$ queryParams ['YourModelSearch'] ['param'] = $ param;
$ searchModel = new YourModelSearch();
$ dataProvider = $ searchModel-> search($ queryParams);

return $ this-> renderAjax('@ your-alias / widgets / views / index',[
'searchModel'=> $ searchModel,
'dataProvider' => $ dataProvider,
'model'=> $ model,
]);
} ...

小部件(@ your-alias / widgets /)[form,查看]:

_form:

 使用yii \helpers\\ \\Html; 
使用yii\widgets\ActiveForm;
使用yii\widgets\Pjax;

/ **
* @var yii\web\View $ this
* @var yourModule / models / YourModel $ model
* @var yii\\ \\ widgets \ActiveForm $ form
* /
?>
<?php
$ js =<<<< JS
//获取表单ID并设置事件
$('form#{$ model-> ;('beforeSubmit',function(e){
var \ $ form = $(this);
//在这里做任何事,看参数\ $ form?是一个jQuery元素到你的表单
console.log(\ $ form);
console.log(MODEL CODE =+ $(#yourmodel-code).val() );
})。on('submit',function(e){
e.preventDefault();
});
JS;
// $ this-> registerJs($ js);
$ this-> registerJs(
'$(#new-your-model)on(pjax:end,function(){
commonLib.divAction(# div_new_model,hide); //隐藏表单
$ .pjax.reload({container:#models}); //重新加载GridView
});',\yii\ web\View :: POS_READY
);
?>

< div class =model-form>

<?php Pjax :: begin(['id'=>'new-model','timeout'=> false,'enablePushState'=> false])?>>
<?php $ form = ActiveForm :: begin([
'id'=> $ model-> formName(),
//'method'=>'post ',
'action'=> ['/module/controller/manage?param='.$model-> code],
'options'=> ['data-pjax'= > true],
//'layout'=>'default',
]); ?>

<?= $ form-> field($ model,'code') - > textInput(['maxlength'=> 255])?>>

...


< div class =form-group>
<?= Html :: submitButton($ model-> isNewRecord?'Create':'Update',['class'=> $ model-> isNewRecord?'btn btn-success':' btn btn-primary'])?>>
< / div>

<?php ActiveForm :: end(); ?>
<?php yii\widgets\Pjax :: end()?>

< / div>

索引视图(网格视图):

 使用yii \helpers\Html; 
使用yii\grid\GridView;
使用yii\widgets\Pjax;

/ **
* @var yii\web\查看$ this
* @var yii\data\ActiveDataProvider $ dataProvider
* @var yourModule\models\search\YourModelSearch $ searchModel
* /
?>
< div class =model-index>

<! - h1><! - ?= Html :: encode($ this-> title)?>< / h1 - >

<?php // echo $ this-> render('_ search',['model'=> $ searchModel]); ?>

< p>


<?= Html :: button(Yii :: t('bp','Add ...'),[
'class'=>' btn btn-success',
'onclick'=>'js:commonLib.divAction(#div_new_model,show)'
])?>>
< / p>

< div id =div_new_modelstyle =display:none>
<?= Html :: button(Yii :: t('common','Cancel'),[
'class'=>'btn btn-success',
' onclick'=>'js:commonLib.divAction(#div_new_model,hide)'
])?>>

<! - Render create form - >
<?= $ this-> render('_ formModel',[
'model'=> $ model,
])?>
< / div>

<?php Pjax :: begin(['id'=>'models','timeout'=> false,'enablePushState'=> false])?>>
<?= GridView :: widget([
'dataProvider'=> $ dataProvider,
'filterModel'=> $ searchModel,
'columns'=> [
['class'=>'yii\grid\SerialColumn'],

...

['class'=>'' yii\grid\ActionColumn'],
],
]); ?>
<?php Pjax :: end()?>
< / div>

小部件调用(在视图中):

  echo @ your-alias \widgets\YourWidget :: widget([
'param'=> $ model-> param,]);


Following this Wiki Yii 2.0: Pjax on ActiveForm and GridView - Yii2

I have tried to use my gridview to update on Ajax without page-reload, but couldn't succeed.

code of my _form.php

<?php

$this->registerJs(
   '$("document").ready(function(){ 
        $("#new_medicine").on("pjax:end", function() {
            $.pjax.reload({container:"#medicine"});  //Reload GridView
        });
    });'
);
?>


<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use kartik\grid\GridView;
//use yii\grid\Gridview;
use yii\data\ActiveDataProvider;

/* @var $this yii\web\View */
/* @var $model app\models\Medicine */
/* @var $form yii\widgets\ActiveForm */
?>
<!-- <div class="row">
    <div class="col-lg-6 col-lg-offset-3"> -->
<div class="medicine-form">
    <?php yii\widgets\Pjax::begin(['id' => 'new_medicine']) ?>

     <?php $form = ActiveForm::begin(['options' => ['data-pjax' => true ]]); ?>

    <?= $form->field($model, 'medicine_id')->textInput(['maxlength' => 10]) ?>

    <?= $form->field($model, 'medicine_name')->textInput(['maxlength' => 50]) ?>

    <div class="form-group">
        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
        <?= Html::submitButton($model->isNewRecord ? 'Save & New' : '',$option=['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary','name'=>'save_and_new']) ?>
    </div>

    <?php ActiveForm::end(); ?>
    <?php yii\widgets\Pjax::end() ?>

</div>

Code in my controller

public function actionIndex()
    {
        $model = new Medicine();

        if ($model->load(Yii::$app->request->post()) && $model->save())
        {
            $model = new Medicine(); //reset model
        }
        $searchModel = new MedicineSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'model' => $model,
        ]);
    }

code in index.php

<?php

use yii\helpers\Html;
use yii\grid\GridView;

/* @var $this yii\web\View */
/* @var $searchModel app\models\MedicineSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = 'Medicines';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="medicine-index">

    <h1><?= Html::encode($this->title) ?></h1>
    <?php // echo $this->render('_search', ['model' => $searchModel]); ?>

    <p>
        <?= Html::a('Create Medicine', ['create'], ['class' => 'btn btn-success']) ?>
    </p>
<?php \yii\widgets\Pjax::begin(['id' => 'medicine']); ?>
    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],

            'id',
            'medicine_id',
            'medicine_name',

            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>
<?php \yii\widgets\Pjax::end(); ?>
</div>

I think I have followed the instructions very carefully, but surely I am missing something as the grid-view is not showing the new records added without page-reload.

Any help will be greatly appreciated. Thanks.

解决方案

try to explain how to do it as a widget; it's a generic solution, so contact me in case of troubles:

Controller (@your-alias/controllers/yourController):

...
public function actionManage($param=''){
    $model = new YourModel();

    if (Yii::$app->request->isPjax && $model->load(Yii::$app->request->post()) && $model->save())
    {
        $model = new YourModel(); //reset model
    }
    $model->paramId = $param;
    $queryParams = Yii::$app->request->getQueryParams();
    $queryParams['YourModelSearch']['param'] = $param;
    $searchModel = new YourModelSearch();
    $dataProvider = $searchModel->search($queryParams);

    return $this->renderAjax('@your-alias/widgets/views/index', [
        'searchModel' => $searchModel,
        'dataProvider' => $dataProvider,
        'model' => $model,
    ]);
}...

widgets (@your-alias/widgets/) [form, view]:

_form:

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\widgets\Pjax;

/**
 * @var yii\web\View $this
 * @var yourModule/models/YourModel $model
 * @var yii\widgets\ActiveForm $form
 */
?>
<?php
$js = <<<JS
// get the form id and set the event
$('form#{$model->formName()}').on('beforeSubmit', function(e) {
   var \$form = $(this);
   // do whatever here, see the parameter \$form? is a jQuery Element to your form
    console.log(\$form);
    console.log("MODEL CODE = " + $("#yourmodel-code").val());
}).on('submit', function(e){
    e.preventDefault();
});
JS;
//$this->registerJs($js);
$this->registerJs(
   '$("#new-your-model").on("pjax:end", function() {
        commonLib.divAction("#div_new_model", "hide"); //hide form
        $.pjax.reload({container:"#models"});  //Reload GridView
    });', \yii\web\View::POS_READY
);
?>

<div class="model-form">

    <?php Pjax::begin(['id' => 'new-model', 'timeout' => false, 'enablePushState' => false]) ?>
        <?php $form = ActiveForm::begin([
            'id' => $model->formName(),
            //'method' => 'post',
            'action' => ['/module/controller/manage?param='.$model->code],
            'options' => ['data-pjax' => true ],
            //'layout' => 'default',
            ]); ?>

        <?= $form->field($model, 'code')->textInput(['maxlength' => 255]) ?>

        ...


        <div class="form-group">
            <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
        </div>

        <?php ActiveForm::end(); ?>
    <?php yii\widgets\Pjax::end() ?>

</div>

index view (grid view):

use yii\helpers\Html;
use yii\grid\GridView;
use yii\widgets\Pjax;

/**
 * @var yii\web\View $this
 * @var yii\data\ActiveDataProvider $dataProvider
 * @var yourModule\models\search\YourModelSearch $searchModel
 */
?>
<div class="model-index">

    <!--h1><!--?= Html::encode($this->title) ?></h1-->

    <?php // echo $this->render('_search', ['model' => $searchModel]); ?>

    <p>


        <?= Html::button(Yii::t('bp', 'Add ...'), [
            'class' => 'btn btn-success',
            'onclick'=>'js:commonLib.divAction("#div_new_model", "show")'
        ])?>
    </p>

    <div id="div_new_model" style="display:none">
        <?= Html::button(Yii::t('common', 'Cancel'), [
            'class' => 'btn btn-success',
            'onclick'=>'js:commonLib.divAction("#div_new_model", "hide")'
        ])?>

        <!-- Render create form -->
        <?= $this->render('_formModel', [
            'model' => $model,
        ]) ?>
    </div>

<?php Pjax::begin(['id' => 'models', 'timeout' => false, 'enablePushState' => false]) ?>
    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],

            ...

            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>
<?php Pjax::end() ?>
</div>

widget call (in view):

echo @your-alias\widgets\YourWidget::widget([
'param' => $model->param,]);

这篇关于Yii2:使用Pjax更新网格视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆