Yii2 Pjax删除不起作用

时间:2015-04-03 23:25:57

标签: php yii2 crud pjax

我正在尝试使用带有删除按钮的Pjax创建Ajax GridView。删除没有Ajax。我是Yii2的新手,所以任何帮助都将不胜感激。谢谢。

的index.php

<?php Pjax::begin(['id' => 'countries']) ?>
<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],

        'id',
        'title',


        ['class' => 'yii\grid\ActionColumn',
            'buttons' => [
                'delete' => function ($url, $model, $key) {
                    return Html::a('<span class="glyphicon glyphicon-trash"></span>', $url, [
                        'title' => Yii::t('yii', 'Delete'),
                        'data-confirm' => Yii::t('yii', 'Are you sure you want to delete this item?'),
                        'data-method' => 'post',
                    ]);
                },
            ]
        ],
    ],
]); ?>
<?php Pjax::end() ?>

控制器

public function actionDelete($id)
{   
    $model = new Category();
    $this->findModel($id)->delete();
    $dataProvider = new ActiveDataProvider([
        'query' => Category::find(),
    ]);
    return $this->render('index', [
        'dataProvider' => $dataProvider,
        'model' => $model,
    ]);
}

这是控制器

中的公共功能actionIndex()
public function actionIndex()
{
    $model = new Category();

    $dataProvider = new ActiveDataProvider([
        'query' => Category::find(),
    ]);

    if ($model->load(Yii::$app->request->post()) && $model->save())
    {
        $model = new Category();
    }
    return $this->render('index', [
        'dataProvider' => $dataProvider,
        'model' => $model,
    ]);
}

7 个答案:

答案 0 :(得分:3)

data-methoddata-confirm不允许您通过pjax创建ajax请求,您应该实现自己的确认对话框并删除POST动词过滤器,或者您可以使用确认实现自己的ajax插件对话框并指定http方法。

另外,我认为必须有通过确认对话框扩展pjax插件的方法,但Yii2默认不提供此功能。

答案 1 :(得分:3)

<?php Pjax::begin(['id' => 'model-grid']);
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    //...
    [
            'class' => 'yii\grid\ActionColumn',
            'template' => '{update} {delete}',
            'contentOptions' => ['class' => 'action-column'],
            'buttons' => [
                'delete' => function ($url, $model, $key) {
                    return Html::a('<span class="glyphicon glyphicon-trash"></span>', $url, [
                        'title' => 'Delete',
                        'data-pjax' => '#model-grid',
                    ]);
                },
            ],
        ],
    ],
]); 
Pjax::end(); ?>

在控制器中

public function actionDelete($id)
{
    $this->findModel($id)->delete();
    $searchModel = new ModelSearch();
    $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
    return $this->render('index', [
        'searchModel' => $searchModel,
        'dataProvider' => $dataProvider,
    ]);
}

答案 2 :(得分:2)

请尝试修改actionDelete()

public function actionDelete($id)
{   
    $this->findModel($id)->delete();
    return \yii\web\Response::redirect(['index'] , 302 , false);
    // return $this->redirect(['index']);
}

因为Controller-&gt; redirect()无法禁用ajaxCheck,所以需要使用Response来执行此操作。

我在https://github.com/yiisoft/yii2/issues/11058中创建了相同的问题。

答案 3 :(得分:2)

首先删除&#39;数据确认&#39;和&#39;数据方法&#39; =&GT; &#39;后&#39 ;. pjax无法正常工作。 如果你想实现一个带有动作按钮的确认框,我将在我的视图中执行index.php文件。

extension Object {

    public convenience init( withDictionary rawData: [String:AnyObject] ) {

        var sanitizedData = rawData

        let dynamicSelf = self.dynamicType

        let schema = dynamicSelf.sharedSchema()


        for property in schema.properties {

            guard let value = sanitizedData[property.name] else { continue }

            var isValid = true

            switch property.type {

                case .Double:

                    let val = Double(String(value))

                    if val == nil || val!.isNaN {
                        isValid = false
                    }

                case .Float:

                    let val = Float(String(value))

                    if val == nil || val!.isNaN {
                        isValid = false
                    }

                case .Int:

                    if Int(String(value)) == nil {
                        isValid = false
                    }

                case .Date:

                    if Int64(String(value)) == nil {

                        isValid = false

                    } else {

                        sanitizedData[property.name] = NSDate(timeIntervalSince1970: value.doubleValue / 1000)

                    }

                default:
                    break

            }


            if !isValid {

                log.error( "Found invalid value: \(value) for property \(property.name) of \(dynamicSelf)" )

                sanitizedData.removeValueForKey(property.name)

            }

        }

        self.init( value: sanitizedData )

    }

}

并在我的控制器中

<?php  Pjax::begin(['id' => 'pjax-container']); 
echo GridView::widget([
    'test' => function ($url, $dataProvider) {
    return Html::a('Test',
        ['/site/test'],
        ['title'=>'Test',
         'onclick' => "if (confirm('ok?')) {
              $.ajax('/site/test', {
                  type: 'POST'
              }).done(function(data) {
                   $.pjax.reload({container: '#pjax-container'});
              });
          }
          return false;
          ",
          ]);
        },
    ])
Pjax::end();
?>

这样你也会得到确认等。如果您需要,您可以使用其他第三方引导程序确认等,并且可以正常工作。

答案 4 :(得分:1)

可以这样使用:

在视图中:

'delete' => function ($url, $model, $key) {
  $options = [
    'title' => Yii::t('common', 'delete'),
    'aria-label' => Yii::t('common', 'delete'),
    'data-pjax' => 'w0',//id
    'data-confirm' => Yii::t('yii', 'Are you sure you want to delete this item?'),
    'data-method' => 'post',
    'class' => 'btn btn-xs btn-danger'
  ];
  return Html:: a('<i class="fa fa-fw fa-trash"></i>', [
    'delete',
    'id' => $model -> id
  ], $options);
}
控制器中的

$this -> findModel($id) -> delete ();
$searchModel = new AdminSearch();
//get the referer url
$url = Yii::$app -> request -> referrer;
$arr = parse_url($url, PHP_URL_QUERY);
parse_str($arr, $output);//get the $_GET array
$dataProvider = $searchModel -> search($output);
return $this -> render('index', [
  'searchModel' => $searchModel,
  'dataProvider' => $dataProvider,
]);

答案 5 :(得分:0)

首先在gridview的末尾添加Pjax::end(); 然后指定:

    'delete' => function ($url, $model, $key)
    {
         return Html::a('<span class="glyphicon glyphicon-trash"></span>', $url, [
                'title' => Yii::t('yii', 'Delete'),
                'data-confirm' => Yii::t('yii', 'Are you sure you want to delete this item?'),
                'data-method' => 'post',
      ]);
   },

请注意,您不需要指定'data-pjax' => '0',因为它会禁用pjax链接。

有关详细信息,请查看此link

你的控制器应该是:

public function actionDelete($id)
{   
    $this->findModel($id)->delete();
    return $this->redirect(['index']);
}

答案 6 :(得分:0)

不要设置data-methoddata-confirm,因为Pjax不支持。

删除两个仍然不工作后,是的,因为你的控制器的下面的代码不允许Pjax得到请求。

return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'], // **remove this**
                ],
            ],
        ];

您需要使用Pjax Post Method 在你的Pjax中应用它

'clientOptions' => ['method' => 'POST']