Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
358 views
in Technique[技术] by (71.8m points)

php - Yii2: Updating Grid-view using Pjax

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 yiihelpersHtml;
use yiiwidgetsActiveForm;
use kartikgridGridView;
//use yiigridGridview;
use yiidataActiveDataProvider;

/* @var $this yiiwebView */
/* @var $model appmodelsMedicine */
/* @var $form yiiwidgetsActiveForm */
?>
<!-- <div class="row">
    <div class="col-lg-6 col-lg-offset-3"> -->
<div class="medicine-form">
    <?php yiiwidgetsPjax::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 yiiwidgetsPjax::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 yiihelpersHtml;
use yiigridGridView;

/* @var $this yiiwebView */
/* @var $searchModel appmodelsMedicineSearch */
/* @var $dataProvider yiidataActiveDataProvider */

$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 yiiwidgetsPjax::begin(['id' => 'medicine']); ?>
    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yiigridSerialColumn'],

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

            ['class' => 'yiigridActionColumn'],
        ],
    ]); ?>
<?php yiiwidgetsPjax::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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 yiihelpersHtml;
use yiiwidgetsActiveForm;
use yiiwidgetsPjax;

/**
 * @var yiiwebView $this
 * @var yourModule/models/YourModel $model
 * @var yiiwidgetsActiveForm $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
    });', yiiwebView::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 yiiwidgetsPjax::end() ?>

</div>

index view (grid view):

use yiihelpersHtml;
use yiigridGridView;
use yiiwidgetsPjax;

/**
 * @var yiiwebView $this
 * @var yiidataActiveDataProvider $dataProvider
 * @var yourModulemodelssearchYourModelSearch $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' => 'yiigridSerialColumn'],

            ...

            ['class' => 'yiigridActionColumn'],
        ],
    ]); ?>
<?php Pjax::end() ?>
</div>

widget call (in view):

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...