Yii2:使用 Pjax 更新网格视图


Yii2: Updating Grid-view using Pjax

遵循这个维基Yii 2.0:ActiveForm和GridView上的Pjax - Yii2

我尝试使用我的网格视图在不重新加载页面的情况下在 Ajax 上更新,但无法成功。

我的_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>

控制器中的代码

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,
        ]);
    }

索引中的代码.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>

我想我已经非常仔细地遵循了说明,但肯定我错过了一些东西,因为网格视图没有显示在没有页面重新加载的情况下添加的新记录。

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

尝试解释如何将其作为小部件进行操作;这是一个通用解决方案,因此如果遇到麻烦,请与我联系:

控制器(@your别名/控制器/您的控制器):

...
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,
    ]);
}...

小部件(@your-别名/小部件/) [表单,视图]:

_形式:

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>

索引视图(网格视图):

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>

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

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

$.pjax.reload('#my-grid-pjax' , {timeout : false});

要使用 pjax 更新GridView表而不重新加载页面:

use yii'grid'GridView;
use yii'widgets'Pjax;
Pjax::begin(['id' => 'todaysactivity', 'timeout' => false, 'enablePushState' => false])

按如下方式使用 jQuery/JavaScript:

var url = baseurl + '/activity/logging'; // url where the gridview table need to update
$.pjax.reload({container: "#todaysactivity", url: url}); // refresh the grid

我找不到合适的解决方案来使用 pjax 更新网格视图小部件。我通过使用网格视图页面的自动刷新方法解决了这个问题。我知道这不是最好的解决方案,我仍在寻找合适的解决方案。

我使用的方法如下:

<script>
function autoRefresh()
{
   window.location.reload();
}
setInterval('autoRefresh()', 60000); // this will reload page after every 1 minute.
</script>

你要找的是

<script type="text/javascript">
$.pjax.defaults.timeout = false;
</script>

默认的 pjax 超时设置不会给页面时间执行任何操作,因此它会重新加载。

参考