myks92
@myks92
Нашёл решение — пометь вопрос ответом!

Как сделать несколько kartik crud -ов (моделей) на одной странице?

Хочу совместить несколько CRUD (моделей) в одном контроллере. Получилось реализовать только index страницу
public function actionIndex()
    {
        $searchModel = new SettingSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        $searchHall = new HallSearch();
        $dataHall = $searchHall->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,

            'searchHall' => $searchHall,
            'dataHall' => $dataHall,
        ]);
    }


Остальную часть кода не могу понять как совместить. Модель Setting работает прекрасно, а вот views модели Hall использует данные и форму модели Setting. Необходимо разделить udate, create, delete для модели Hall. Помогите ссылками или описанием как это сделать. Благодарю!

КОД КОНТРОЛЛЕРА

<?php

namespace backend\controllers\setting;

use backend\models\setting\Hall;
use backend\models\setting\HallSearch;
use Yii;
use backend\models\setting\Setting;
use backend\models\setting\SettingSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use \yii\web\Response;
use yii\helpers\Html;

    /**
     * Updates an existing Setting model.
     * For ajax request will return json object
     * and for non-ajax request if update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $request = Yii::$app->request;
        $model = $this->findModel($id);

        if($request->isAjax){
            /*
            *   Process for ajax request
            */
            Yii::$app->response->format = Response::FORMAT_JSON;
            if($request->isGet){
                return [
                    'title'=> " ".Yii::t('backend', 'Update')." ".Yii::t('backend', 'Setting')." #".$id." ",
                    'content'=>$this->renderAjax('update', [
                        'model' => $model,
                    ]),
                    'footer'=> Html::button(Yii::t('backend', 'Close'),['class'=>'btn btn-default pull-left','data-dismiss'=>"modal"]).
                                Html::button(Yii::t('backend', 'Save'),['class'=>'btn btn-primary','type'=>"submit"])
                ];         
            }else if($model->load($request->post()) && $model->save()){
                return [
                    'forceReload'=>'#crud-datatable-pjax',
                    'title'=> " ".Yii::t('backend', 'Setting')." #".$id." ",
                    'content'=>$this->renderAjax('view', [
                        'model' => $model,
                    ]),
                    'footer'=> Html::button(Yii::t('backend', 'Close'),['class'=>'btn btn-default','data-dismiss'=>"modal"]).
                            Html::a(Yii::t('backend', 'Edit'),['update','id'=>$id],['class'=>'btn btn-primary  pull-left','role'=>'modal-remote'])
                ];    
            }else{
                 return [
                    'title'=> "Изменение  ".Yii::t('backend', 'Setting')." #".$id." ",
                    'content'=>$this->renderAjax('update', [
                        'model' => $model,
                    ]),
                    'footer'=> Html::button(Yii::t('backend', 'Close'),['class'=>'btn btn-default pull-left','data-dismiss'=>"modal"]).
                                Html::button(Yii::t('backend', 'Save'),['class'=>'btn btn-primary','type'=>"submit"])
                ];        
            }
        }else{
            /*
            *   Process for non-ajax request
            */
            if ($model->load($request->post()) && $model->save()) {
                return $this->redirect(['view', 'id' => $model->id]);
            } else {
                return $this->render('update', [
                    'model' => $model,
                ]);
            }
        }
    }

    /**
     * Delete an existing Setting model.
     * For ajax request will return json object
     * and for non-ajax request if deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $request = Yii::$app->request;
        $this->findModel($id)->delete();

        if($request->isAjax){
            /*
            *   Process for ajax request
            */
            Yii::$app->response->format = Response::FORMAT_JSON;
            return ['forceClose'=>true,'forceReload'=>'#crud-datatable-pjax'];
        }else{
            /*
            *   Process for non-ajax request
            */
            return $this->redirect(['index']);
        }


    }

     /**
     * Delete multiple existing Setting model.
     * For ajax request will return json object
     * and for non-ajax request if deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionBulkDelete()
    {        
        $request = Yii::$app->request;
        $pks = explode(',', $request->post( 'pks' )); // Array or selected records primary keys
        foreach ( $pks as $pk ) {
            $model = $this->findModel($pk);
            $model->delete();
        }

        if($request->isAjax){
            /*
            *   Process for ajax request
            */
            Yii::$app->response->format = Response::FORMAT_JSON;
            return ['forceClose'=>true,'forceReload'=>'#crud-datatable-pjax'];
        }else{
            /*
            *   Process for non-ajax request
            */
            return $this->redirect(['index']);
        }
       
    }

    /**
     * Finds the Setting model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Setting the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Setting::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
  • Вопрос задан
  • 309 просмотров
Решения вопроса 1
qonand
@qonand
Software Engineer
1. Сделать вывод нескольких GridView можно сделать так
2. Если вывод нескольких GridView на странице это вполне реальная задача, то реализация круда множества моделей в одном контроллере - это плохая практика, превращающая код в кашу. Поэтому настоятельно рекомендую отказаться от этой идеи
3. Что касается формирования ссылок, то рекомендую почитать вот это
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы