/
v.bolshakov
/
AIEcosystem-Testing
Обзор
Документация
Войти
/
v.bolshakov
/
AIEcosystem-Testing
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
dev
common/controllers/base/ParentCrudController.php
281 строка
8 KB
Developer
Initial commit
03 авг 2026, 17:43
03 авг 2026, 17:43
7433917
Код
Авторство
О чём код?
<?php namespace common\controllers\base; use common\components\crud\FormCrud; use common\components\crud\GridPanelCrud; use common\components\crud\ViewCrud; use common\models\base\BaseModel; use common\models\base\BaseQuery; use common\models\base\IstBaseModel; use Yii; use yii\helpers\Url; use yii\httpclient\debug\SearchModel; use yii\web\NotFoundHttpException; /** * Базовый контроллер для работы с CRUD (вложенные объекты) * Данный класс используется если требуется работать с подчинёнными объектами * * @author Dmitry E. Semenov <sde.tomsk@gmail.com> * @copyright Self (c) 2020 */ abstract class ParentCrudController extends CrudController { /** * Имя базовой модели с которой работаем в текущем классе * @var string */ protected $parentModelName; /** * Родительский элемент текущего объекта * @var BaseModel */ protected $parentModel = null; /** * Список ключей для связи между текущим объектом и родительским * * [foreign_key => primary_key] * * @var array */ protected $relationKey = []; /** * Поиск родительского объекта * * @param $parentId */ protected function getParent($parentId) { $parent = Yii::createObject($this->parentModelName); if (!($this->parentModel = $parent::findOne($parentId))) { throw new NotFoundHttpException(Yii::t('app', 'Не найден базовый объект')); } return $this->parentModel; } /** * Фильтрация данных по родительскому объекту * * @param BaseQuery $query * @param BaseModel $parent * @param BaseModel $model */ protected function filterParent($query, $parent, $model) { $a = $model->getAlias(); if ($a) { $a .= '.'; } foreach ($this->relationKey as $foreign_key => $primary_key) { if ($model->hasAttribute($foreign_key)) { $query->andWhere([ $a . $foreign_key => $parent->$primary_key ]); } else { $query->andWhere([ $foreign_key => $parent->$primary_key ]); } } } /** * Установить родительский элемент * * @param BaseQuery $query * @param BaseModel $parent */ protected function setParent($model, $parent) { if (($model instanceof BaseModel) or ($model instanceof IstBaseModel)) { foreach ($this->relationKey as $foreign_key => $primary_key) { if (strpos($foreign_key, '.') === false) { $model->{$foreign_key} = $parent->{$primary_key}; } else { $pair = explode('.', $foreign_key); $model->{$pair[1]} = $parent->{$primary_key}; } } } } /** * @inheritdoc */ public function actionIndex($parent_id = null) { $parent = $this->getParent($parent_id); /** @var GridPanelCrud $crud */ $params = $this->getParams([ // 'type' => 'GridPanel', 'class' => $this->getClass('GridPanel') ]); $crud = Yii::createObject($params); /** @var SearchModel $modelSearch */ $params = $this->getParams([ // 'type' => 'Search', 'class' => $this->getClass('Search'), 'parentModel' => $parent ]); $modelSearch = Yii::createObject($params); $modelSearch->condition($this->condition()); $this->filterParent($modelSearch->query, $parent, $modelSearch->model); $dataProvider = $modelSearch->search(Yii::$app->request->queryParams); $filters = $crud->getFilters($modelSearch->getQuery()); $crud->controller = $this; $form = null; if ($this->canAdd) { $permission = $this->getPermission('create'); if (Yii::$app->user->can($permission) and ($class = $this->getClass('Form'))) { if (class_exists($class)) { /** @var FormCrud $crud */ $form = Yii::createObject($class); } } } $action = Url::to([Yii::$app->controller->getRoute(), 'parent_id' => $parent_id]); $this->breadcrumbs($crud, $parent); return $this->render($this->getTemplate('Index'), [ 'model' => $modelSearch, 'crud' => $crud, 'form' => $form, 'filters' => $filters, 'parent' => $parent, 'action' => $action, 'canAdd' => $this->canAdd, 'dataProvider' => $dataProvider, ]); } /** * @inheritdoc */ public function actionCreate($parent_id = null) { $parent = $this->getParent($parent_id); $params = $this->getParams([ // 'type' => 'Form', 'class' => $this->getClass('Form') ]); $crud = Yii::createObject($params); $model = $crud->createModel(); $crud->controller = $this; $this->setParent($model, $parent); if ($model->load(Yii::$app->request->post()) && $model->save()) { return $this->redirect(['index', 'parent_id' => $parent_id]); } else { $this->breadcrumbs($crud, $parent); return $this->render($this->getTemplate('Create'), [ 'model' => $model, 'crud' => $crud, 'canAdd' => $this->canAdd, 'parent' => $parent, ]); } } /** * @inheritdoc */ public function actionUpdate($id, $parent_id = null) { $parent = $this->getParent($parent_id); $params = $this->getParams([ // 'type' => 'Update', 'class' => $this->getClass('Form') ]); $crud = Yii::createObject($params); $model = $crud->createModel($id); $crud->controller = $this; $this->setParent($model, $parent); if ($model->load(Yii::$app->request->post()) && $model->save()) { return $this->redirect(['update', 'parent_id' => $parent_id, 'id' => $model->id]); } else { $this->breadcrumbs($crud, $parent, $model); return $this->render($this->getTemplate('Update'), [ 'model' => $model, 'parent' => $parent, 'crud' => $crud, 'canAdd' => $this->canAdd, ]); } } /** * @inheritdoc */ public function actionView($id) { $parent_id = Yii::$app->request->getDefault('parent_id', null); $parent = $this->getParent($parent_id); /** @var ViewCrud $crud */ $params = $this->getParams([ // 'type' => 'View', 'class' => $this->getClass('View') ]); $crud = Yii::createObject($params); $model = $crud->createModel($id); $crud->controller = $this; $this->setParent($model, $parent); if (!$model) { throw new NotFoundHttpException(Yii::t('app', 'No model found')); } $this->breadcrumbs($crud, $parent); return $this->render($this->getTemplate('View'), [ 'model' => $model, 'crud' => $crud, 'parent' => $parent, 'canAdd' => $this->canAdd, ]); } /** * Удаление одной модели * * @param integer $id * @return mixed */ public function actionDelete($id, $parent_id = null) { Yii::$app->request->validateSig(); $parent = $this->getParent($parent_id); $data = $this->getModel($id, $this->getClass('Form')); $this->doDelete($data['model']); return $this->redirect(['index', 'parent_id' => $parent_id]); } }