From 258bab4f4641fc2e0e89e274ef4c2a627980197a Mon Sep 17 00:00:00 2001 From: Elias Luhr Date: Tue, 7 Sep 2021 15:52:14 +0200 Subject: [PATCH 01/45] Made generate relation from current schema an configurable option --- src/commands/BatchController.php | 8 ++++++++ src/generators/model/Generator.php | 3 +-- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/src/commands/BatchController.php b/src/commands/BatchController.php index 475e96d..e5467c2 100644 --- a/src/commands/BatchController.php +++ b/src/commands/BatchController.php @@ -283,6 +283,12 @@ class BatchController extends Controller * @var bool This indicates whether the generator should generate attribute hints by using the comments of the corresponding DB columns */ public $modelGenerateHintsFromComments = true; + + /** + * @var bool Generate Relations from Current Schema + */ + public $modelGenerateRelationsFromCurrentSchema = true; + /** * @var array application configuration for creating temporary applications */ @@ -329,6 +335,7 @@ public function options($id) 'modelRemoveDuplicateRelations', 'modelCacheRelationsData', 'modelGenerateRelations', + 'modelGenerateRelationsFromCurrentSchema', 'modelGenerateJunctionRelationMode', 'modelGenerateQuery', 'modelQueryNamespace', @@ -447,6 +454,7 @@ public function actionModels() 'removeDuplicateRelations' => $this->modelRemoveDuplicateRelations, 'cacheRelationsData' => $this->modelCacheRelationsData, 'generateRelations' => $this->modelGenerateRelations, + 'generateRelationsFromCurrentSchema' => $this->modelGenerateRelationsFromCurrentSchema, 'generateJunctionRelationMode' => $this->modelGenerateJunctionRelationMode, 'tableNameMap' => $this->tableNameMap, 'generateQuery' => $this->modelGenerateQuery, diff --git a/src/generators/model/Generator.php b/src/generators/model/Generator.php index 7243cd0..5ff930d 100644 --- a/src/generators/model/Generator.php +++ b/src/generators/model/Generator.php @@ -181,7 +181,7 @@ public function formAttributes() 'db', 'generateRelations', 'generateJunctionRelationMode', - //'generateRelationsFromCurrentSchema', + 'generateRelationsFromCurrentSchema', 'generateLabelsFromComments', 'generateHintsFromComments', 'generateModelClass', @@ -274,7 +274,6 @@ public function generate() foreach ($this->getTableNames() as $tableName) { list($relations, $translations) = array_values($this->extractTranslations($tableName, $relations)); -//var_dump($relations,$tableName);exit; $className = $this->modelClass === '' || php_sapi_name() === 'cli' ? $this->generateClassName($tableName) : $this->modelClass; From acbe3b756d47837c695ca94336a6a9a4f4ab30e6 Mon Sep 17 00:00:00 2001 From: Elias Luhr Date: Tue, 7 Sep 2021 16:16:51 +0200 Subject: [PATCH 02/45] fixed model relation 1:n (pick one) n:m (pick many) --- src/generators/crud/providers/core/RelationProvider.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/generators/crud/providers/core/RelationProvider.php b/src/generators/crud/providers/core/RelationProvider.php index 97ac2af..68272c1 100644 --- a/src/generators/crud/providers/core/RelationProvider.php +++ b/src/generators/crud/providers/core/RelationProvider.php @@ -54,7 +54,7 @@ public function activeField($attribute) if (is_string($column)) { return null; } - $relation = $this->generator->getRelationByColumn($this->generator->modelClass, $column, ['belongs_to']); + $relation = $this->generator->getRelationByColumn($this->generator->modelClass, $column, ['belongs_to', 'has_one']); if ($relation) { switch (true) { case !$relation->multiple: @@ -128,7 +128,7 @@ public function attributeFormat($attribute) //return null; #TODO: double check with primary keys not named `id` of non-pivot tables } - $relation = $this->generator->getRelationByColumn($this->generator->modelClass, $column, ['belongs_to']); + $relation = $this->generator->getRelationByColumn($this->generator->modelClass, $column, ['belongs_to', 'has_one']); if ($relation) { if ($relation->multiple) { return; @@ -204,7 +204,7 @@ public function columnFormat($attribute, $model) //return null; } - $relation = $this->generator->getRelationByColumn($model, $column, ['belongs_to']); + $relation = $this->generator->getRelationByColumn($model, $column, ['belongs_to', 'has_one']); if ($relation) { if ($relation->multiple) { return; From f846803953118cda9ce03456cc15bfba14ff175c Mon Sep 17 00:00:00 2001 From: Elias Luhr Date: Mon, 20 Sep 2021 14:35:04 +0200 Subject: [PATCH 03/45] disable pluralization --- src/commands/BatchController.php | 9 ++++++++- src/generators/crud/default/views/view.php | 3 ++- src/generators/model/Generator.php | 9 +++++++++ 3 files changed, 19 insertions(+), 2 deletions(-) diff --git a/src/commands/BatchController.php b/src/commands/BatchController.php index e5467c2..2540c64 100644 --- a/src/commands/BatchController.php +++ b/src/commands/BatchController.php @@ -155,6 +155,11 @@ class BatchController extends Controller */ public $enableI18N = true; + /** + * @var bool whether to enable or disable the pluralization of the models name + */ + public $disablePluralization = false; + /** * @var bool whether the entity names will be singular or the same as the table name */ @@ -358,7 +363,8 @@ public function options($id) 'crudOverwriteSearchModelClass', 'crudOverwriteRestControllerClass', 'crudOverwriteControllerClass', - 'generateAccessFilterMigrations' + 'generateAccessFilterMigrations', + 'disablePluralization' ] ); } @@ -462,6 +468,7 @@ public function actionModels() 'queryBaseClass' => $this->modelQueryBaseClass, 'generateLabelsFromComments' => $this->modelGenerateLabelsFromComments, 'generateHintsFromComments' => $this->modelGenerateHintsFromComments, + 'disablePluralization' => $this->disablePluralization ]; $route = 'gii/giiant-model'; diff --git a/src/generators/crud/default/views/view.php b/src/generators/crud/default/views/view.php index 2e0e286..a066824 100644 --- a/src/generators/crud/default/views/view.php +++ b/src/generators/crud/default/views/view.php @@ -158,7 +158,8 @@ $showAllRecords = false; if ($relation->via !== null) { - $pivotName = Inflector::pluralize($generator->getModelByTableName($relation->via->from[0])); +// $pivotName = Inflector::pluralize($generator->getModelByTableName($relation->via->from[0])); + $pivotName = $generator->getModelByTableName($relation->via->from[0]); $pivotRelation = $model->{'get'.$pivotName}(); $pivotPk = key($pivotRelation->link); diff --git a/src/generators/model/Generator.php b/src/generators/model/Generator.php index 5ff930d..b22a5be 100644 --- a/src/generators/model/Generator.php +++ b/src/generators/model/Generator.php @@ -98,6 +98,11 @@ class Generator extends \yii\gii\generators\model\Generator */ public $baseClassSuffix = ''; + /** + * @var bool whether to enable or disable the pluralization of the models name + */ + public $disablePluralization = false; + /** * @var array key-value pairs for mapping a table-name to class-name, eg. 'prefix_FOObar' => 'FooBar' */ @@ -438,6 +443,9 @@ public function generateHints($table) */ public function generateRelationName($relations, $table, $key, $multiple) { + if ($this->disablePluralization) { + $multiple = false; + } return parent::generateRelationName($relations, $table, $key, $multiple); } @@ -449,6 +457,7 @@ protected function generateRelations() $ns = "\\{$this->ns}\\"; foreach ($relations as $model => $relInfo) { foreach ($relInfo as $relName => $relData) { +// var_dump($model, $relName);exit; // removed duplicated relations, eg. klientai, klientai0 if ($this->removeDuplicateRelations && is_numeric(substr($relName, -1))) { From 780075da03ae4b3cba6ea7d24869ab68fcc96249 Mon Sep 17 00:00:00 2001 From: Elias Luhr Date: Fri, 8 Oct 2021 13:31:19 +0200 Subject: [PATCH 04/45] updated name generation for relations --- src/generators/model/default/model.php | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/generators/model/default/model.php b/src/generators/model/default/model.php index b3f0595..cfc27bd 100644 --- a/src/generators/model/default/model.php +++ b/src/generators/model/default/model.php @@ -171,7 +171,14 @@ public function attributeHints() ]); } - $relation): ?> + $relation): + $name = $relation[1] ?? $name; + +if (isset($relation[2]) && $relation[2] === true) { + $name .= 'N'; +} + ?> /** * @return \yii\db\ActiveQuery From e98dc796853d025c07203c727851fc89c9b33e75 Mon Sep 17 00:00:00 2001 From: Elias Luhr Date: Fri, 8 Oct 2021 15:10:59 +0200 Subject: [PATCH 05/45] Disable pluralization via property and append an "N" instead for n:m --- src/commands/BatchController.php | 1 + src/generators/crud/Generator.php | 5 ++ src/generators/crud/ModelTrait.php | 24 ++++--- src/generators/crud/default/views/view.php | 12 ++-- src/generators/model/Generator.php | 81 ++++++++++++++-------- src/generators/model/default/model.php | 9 +-- 6 files changed, 81 insertions(+), 51 deletions(-) diff --git a/src/commands/BatchController.php b/src/commands/BatchController.php index 2540c64..dbc845f 100644 --- a/src/commands/BatchController.php +++ b/src/commands/BatchController.php @@ -543,6 +543,7 @@ public function actionCruds() 'formLayout' => $this->crudFormLayout, 'generateAccessFilterMigrations' => $this->generateAccessFilterMigrations, 'actionButtonColumnPosition' => $this->crudActionButtonColumnPosition, + 'disablePluralization' => $this->disablePluralization ]; $route = 'gii/giiant-crud'; $app = \Yii::$app; diff --git a/src/generators/crud/Generator.php b/src/generators/crud/Generator.php index c7bdcaa..f1f6181 100644 --- a/src/generators/crud/Generator.php +++ b/src/generators/crud/Generator.php @@ -138,6 +138,11 @@ class Generator extends \yii\gii\generators\crud\Generator */ public $fixOptions = ''; + /** + * @var bool whether to enable or disable the pluralization of the models name + */ + public $disablePluralization = false; + /** * @var string form field for selecting and loading saved gii forms */ diff --git a/src/generators/crud/ModelTrait.php b/src/generators/crud/ModelTrait.php index 037879d..0d1732b 100644 --- a/src/generators/crud/ModelTrait.php +++ b/src/generators/crud/ModelTrait.php @@ -73,7 +73,9 @@ public function getModelRelations($modelClass, $types = []) $reflector = new \ReflectionClass($modelClass); $model = new $modelClass(); $stack = []; - $modelGenerator = new ModelGenerator(); + $modelGenerator = new ModelGenerator([ + 'disablePluralization' => $this->disablePluralization + ]); foreach ($reflector->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) { if (in_array(substr($method->name, 3), $this->skipRelations)) { continue; @@ -118,12 +120,16 @@ public function getModelRelations($modelClass, $types = []) } // if types is empty, return all types -> no filter if ((count($types) == 0) || in_array($relationType, $types)) { - $name = $modelGenerator->generateRelationName( - [$relation], - $model->getTableSchema(), - substr($method->name, 3), - $relation->multiple - ); + if ($this->disablePluralization) { + $name = str_replace('get','', $method->name); + } else { + $name = $modelGenerator->generateRelationName( + [$relation], + $model->getTableSchema(), + substr($method->name, 3), + $relation->multiple + ); + } $stack[$name] = $relation; } } @@ -164,12 +170,12 @@ public function getRelationByColumn($model, $column, $types = ['belongs_to', 'ma $relations = $this->getModelRelations($model, $types); foreach ($relations as $relation) { // TODO: check multiple link(s) - if ($relation->link && reset($relation->link) == $column->name) { + if ($relation->link && reset($relation->link) === $column->name) { return $relation; } } - return; + return null; } public function createRelationRoute($relation, $action) diff --git a/src/generators/crud/default/views/view.php b/src/generators/crud/default/views/view.php index a066824..9f0f7bf 100644 --- a/src/generators/crud/default/views/view.php +++ b/src/generators/crud/default/views/view.php @@ -152,14 +152,18 @@ EOS; - foreach ($generator->getModelRelations($generator->modelClass, ['has_many', 'has_one']) as $name => $relation) { + $relations = $generator->getModelRelations($generator->modelClass, ['has_many', 'has_one']); + foreach ($relations as $name => $relation) { echo "\nbeginBlock('$name'); ?>\n"; $showAllRecords = false; - if ($relation->via !== null) { -// $pivotName = Inflector::pluralize($generator->getModelByTableName($relation->via->from[0])); - $pivotName = $generator->getModelByTableName($relation->via->from[0]); + + if ($generator->disablePluralization) { + $pivotName = $name; + } else { + $pivotName = Inflector::pluralize($generator->getModelByTableName($relation->via->from[0])); + } $pivotRelation = $model->{'get'.$pivotName}(); $pivotPk = key($pivotRelation->link); diff --git a/src/generators/model/Generator.php b/src/generators/model/Generator.php index b22a5be..ac6a51f 100644 --- a/src/generators/model/Generator.php +++ b/src/generators/model/Generator.php @@ -5,6 +5,7 @@ * @copyright Copyright (c) 2014 herzog kommunikation GmbH * @license http://www.phundament.com/license/ */ + namespace schmunk42\giiant\generators\model; use schmunk42\giiant\helpers\SaveForm; @@ -156,15 +157,30 @@ public function rules() return array_merge( parent::rules(), [ - [[ - 'generateModelClass', - 'useTranslatableBehavior', - 'generateHintsFromComments', - 'useBlameableBehavior', - 'useTimestampBehavior', - 'singularEntities', - ], 'boolean'], - [['languageTableName', 'languageCodeColumn', 'createdByColumn', 'updatedByColumn', 'createdAtColumn', 'updatedAtColumn', 'savedForm', 'timestampBehaviorClass'], 'string'], + [ + [ + 'generateModelClass', + 'useTranslatableBehavior', + 'generateHintsFromComments', + 'useBlameableBehavior', + 'useTimestampBehavior', + 'singularEntities', + ], + 'boolean' + ], + [ + [ + 'languageTableName', + 'languageCodeColumn', + 'createdByColumn', + 'updatedByColumn', + 'createdAtColumn', + 'updatedAtColumn', + 'savedForm', + 'timestampBehaviorClass' + ], + 'string' + ], [['tablePrefix'], 'safe'], ] ); @@ -207,7 +223,7 @@ public function formAttributes() 'createdAtColumn', 'updatedAtColumn', 'timestampBehaviorClass', - ]; + ]; } /** @@ -313,7 +329,7 @@ public function generate() $this->render('model.php', $params) ); - $modelClassFile = Yii::getAlias('@'.str_replace('\\', '/', $this->ns)).'/'.$className.'.php'; + $modelClassFile = Yii::getAlias('@' . str_replace('\\', '/', $this->ns)) . '/' . $className . '.php'; if ($this->generateModelClass || !is_file($modelClassFile)) { $files[] = new CodeFile( $modelClassFile, @@ -323,8 +339,8 @@ public function generate() if ($queryClassName) { $queryClassFile = Yii::getAlias( - '@'.str_replace('\\', '/', $this->queryNs) - ).'/'.$queryClassName.'.php'; + '@' . str_replace('\\', '/', $this->queryNs) + ) . '/' . $queryClassName . '.php'; if ($this->generateModelClass || !is_file($queryClassFile)) { $params = [ 'className' => $queryClassName, @@ -341,14 +357,15 @@ public function generate() * create gii/[name]GiiantModel.json with actual form data */ $suffix = str_replace(' ', '', $this->getName()); - $formDataDir = Yii::getAlias('@'.str_replace('\\', '/', $this->ns)); + $formDataDir = Yii::getAlias('@' . str_replace('\\', '/', $this->ns)); $formDataFile = StringHelper::dirname($formDataDir) - .'/'.$this->giiInfoPath.'/' - .'/'.$tableName.$suffix.'.json'; + . '/' . $this->giiInfoPath . '/' + . '/' . $tableName . $suffix . '.json'; $generatorForm = (clone $this); $generatorForm->tableName = $tableName; - $generatorForm->modelClass = $className; - $formData = json_encode(SaveForm::getFormAttributesValues($generatorForm, $this->formAttributes()), JSON_PRETTY_PRINT); + $generatorForm->modelClass = $className; + $formData = json_encode(SaveForm::getFormAttributesValues($generatorForm, $this->formAttributes()), + JSON_PRETTY_PRINT); $files[] = new CodeFile($formDataFile, $formData); } @@ -393,7 +410,7 @@ public function generateClassName($tableName, $useSchemaName = null) if (($pos = strrpos($pattern, '.')) !== false) { $pattern = substr($pattern, $pos + 1); } - $patterns[] = '/^'.str_replace('*', '(\w+)', $pattern).'$/'; + $patterns[] = '/^' . str_replace('*', '(\w+)', $pattern) . '$/'; } $className = $tableName; @@ -443,10 +460,15 @@ public function generateHints($table) */ public function generateRelationName($relations, $table, $key, $multiple) { + $suffix = ''; if ($this->disablePluralization) { + if ($multiple) { + $suffix = 'N'; + } $multiple = false; } - return parent::generateRelationName($relations, $table, $key, $multiple); + $relationName = parent::generateRelationName($relations, $table, $key, $multiple); + return $relationName . $suffix; } protected function generateRelations() @@ -457,7 +479,6 @@ protected function generateRelations() $ns = "\\{$this->ns}\\"; foreach ($relations as $model => $relInfo) { foreach ($relInfo as $relName => $relData) { -// var_dump($model, $relName);exit; // removed duplicated relations, eg. klientai, klientai0 if ($this->removeDuplicateRelations && is_numeric(substr($relName, -1))) { @@ -493,8 +514,8 @@ public function getEnum($columns) } $column_camel_name = str_replace(' ', '', ucwords(implode(' ', explode('_', $column->name)))); - $enum[$column->name]['func_opts_name'] = 'opts'.$column_camel_name; - $enum[$column->name]['func_get_label_name'] = 'get'.$column_camel_name.'ValueLabel'; + $enum[$column->name]['func_opts_name'] = 'opts' . $column_camel_name; + $enum[$column->name]['func_get_label_name'] = 'get' . $column_camel_name . 'ValueLabel'; $enum[$column->name]['values'] = []; $enum_values = explode(',', substr($column->dbType, 4, strlen($column->dbType) - 1)); @@ -502,7 +523,7 @@ public function getEnum($columns) foreach ($enum_values as $value) { $value = trim($value, "()'"); - $const_name = strtoupper($column->name.'_'.$value); + $const_name = strtoupper($column->name . '_' . $value); $const_name = preg_replace('/\s+/', '_', $const_name); $const_name = str_replace(['-', '_', ' '], '_', $const_name); $const_name = preg_replace('/[^A-Z0-9_]/', '', $const_name); @@ -560,19 +581,19 @@ public function generateRules($table) foreach ($enum as $field_name => $field_details) { $ea = array(); foreach ($field_details['values'] as $field_enum_values) { - $ea[] = 'self::'.$field_enum_values['const_name']; + $ea[] = 'self::' . $field_enum_values['const_name']; } - $rules[] = "['".$field_name."', 'in', 'range' => [\n ".implode( + $rules[] = "['" . $field_name . "', 'in', 'range' => [\n " . implode( ",\n ", $ea - ).",\n ]\n ]"; + ) . ",\n ]\n ]"; } // inject namespace for targetClass $parentRules = parent::generateRules($table); $ns = "\\{$this->ns}\\"; $match = "'targetClass' => "; - $replace = $match.$ns; + $replace = $match . $ns; foreach ($parentRules as $k => $parentRule) { $parentRules[$k] = str_replace($match, $replace, $parentRule); } @@ -710,8 +731,8 @@ protected function generateTimestamp($table) if ($this->useTimestampBehavior && ($createdAt || $updatedAt)) { return [ - 'createdAtAttribute' => $createdAt, - 'updatedAtAttribute' => $updatedAt, + 'createdAtAttribute' => $createdAt, + 'updatedAtAttribute' => $updatedAt, 'timestampBehaviorClass' => $this->timestampBehaviorClass, ]; } diff --git a/src/generators/model/default/model.php b/src/generators/model/default/model.php index cfc27bd..f9fd806 100644 --- a/src/generators/model/default/model.php +++ b/src/generators/model/default/model.php @@ -171,14 +171,7 @@ public function attributeHints() ]); } - $relation): - $name = $relation[1] ?? $name; - -if (isset($relation[2]) && $relation[2] === true) { - $name .= 'N'; -} - ?> + $relation):?> /** * @return \yii\db\ActiveQuery From a4caba45c830293b5f5a1fc8cfedff282993cdac Mon Sep 17 00:00:00 2001 From: Elias Luhr Date: Mon, 11 Oct 2021 13:50:07 +0200 Subject: [PATCH 06/45] updated model and crud generation --- src/generators/crud/ModelTrait.php | 1 + src/generators/crud/default/views/view.php | 10 ++++++---- .../crud/providers/core/RelationProvider.php | 10 ++++++---- src/generators/model/Generator.php | 2 +- 4 files changed, 14 insertions(+), 9 deletions(-) diff --git a/src/generators/crud/ModelTrait.php b/src/generators/crud/ModelTrait.php index 0d1732b..4fb3c5a 100644 --- a/src/generators/crud/ModelTrait.php +++ b/src/generators/crud/ModelTrait.php @@ -152,6 +152,7 @@ public function getColumnByAttribute($attribute, $model = null) $model = $this; } + // omit schema for NOSQL models if (method_exists($model,'getTableSchema') && $model->getTableSchema()) { return $model->getTableSchema()->getColumn($attribute); diff --git a/src/generators/crud/default/views/view.php b/src/generators/crud/default/views/view.php index 9f0f7bf..b43fd38 100644 --- a/src/generators/crud/default/views/view.php +++ b/src/generators/crud/default/views/view.php @@ -159,10 +159,11 @@ $showAllRecords = false; if ($relation->via !== null) { + $modelNameByTable = $generator->getModelByTableName($relation->via->from[0]); if ($generator->disablePluralization) { - $pivotName = $name; + $pivotName = $modelNameByTable; } else { - $pivotName = Inflector::pluralize($generator->getModelByTableName($relation->via->from[0])); + $pivotName = Inflector::pluralize($modelNameByTable); } $pivotRelation = $model->{'get'.$pivotName}(); $pivotPk = key($pivotRelation->link); @@ -181,7 +182,8 @@ } // relation list, add, create buttons - echo "
\n
\n"; +// echo "
\n
\n"; + echo "
\n"; echo " \n
\n"; #
\n"; + echo "
\n
"; #
\n"; // render pivot grid if ($relation->via !== null) { $pjaxId = "pjax-{$pivotName}"; diff --git a/src/generators/crud/providers/core/RelationProvider.php b/src/generators/crud/providers/core/RelationProvider.php index 68272c1..8f2cba6 100644 --- a/src/generators/crud/providers/core/RelationProvider.php +++ b/src/generators/crud/providers/core/RelationProvider.php @@ -141,7 +141,9 @@ public function attributeFormat($attribute) $routeIndex = $this->generator->createRelationRoute($relation, 'index'); $modelClass = $this->generator->modelClass; - $relationProperty = lcfirst((new ModelGenerator())->generateRelationName( + $relationProperty = lcfirst((new ModelGenerator([ + 'disablePluralization' => $this->generator->disablePluralization + ]))->generateRelationName( [$relation], $modelClass::getTableSchema(), $column->name, @@ -315,7 +317,7 @@ public function relationGrid($name, $relation, $showAllRecords = false) 'class' => '{$this->generator->actionButtonClass}', 'template' => '$template', 'contentOptions' => ['nowrap'=>'nowrap'], - 'urlCreator' => function (\$action, \$model, \$key, \$index) { + 'urlCreator' => function (\$action, \$model, \$key) { // using the column name as key, not mapping to 'id' like the standard generator \$params = is_array(\$key) ? \$key : [\$model->primaryKey()[0] => (string) \$key]; \$params[0] = '$controller' . '/' . \$action; @@ -330,7 +332,7 @@ public function relationGrid($name, $relation, $showAllRecords = false) EOS; // add action column - if ($this->generator->actionButtonColumnPosition != 'right') { + if ($this->generator->actionButtonColumnPosition !== 'right') { $columns .= $actionColumn . ",\n"; } @@ -363,7 +365,7 @@ public function relationGrid($name, $relation, $showAllRecords = false) ++$counter; } - if ($this->generator->actionButtonColumnPosition == 'right') { + if ($this->generator->actionButtonColumnPosition === 'right') { $columns .= $actionColumn . ",\n"; } diff --git a/src/generators/model/Generator.php b/src/generators/model/Generator.php index ac6a51f..e493a63 100644 --- a/src/generators/model/Generator.php +++ b/src/generators/model/Generator.php @@ -463,7 +463,7 @@ public function generateRelationName($relations, $table, $key, $multiple) $suffix = ''; if ($this->disablePluralization) { if ($multiple) { - $suffix = 'N'; +// $suffix = 'N'; } $multiple = false; } From a3d439c94adcd73a40f7b617103653246f5930cb Mon Sep 17 00:00:00 2001 From: Elias Luhr Date: Tue, 12 Oct 2021 17:12:38 +0200 Subject: [PATCH 07/45] updated model and query template --- src/generators/model/default/model.php | 30 ++++++++------------- src/generators/model/default/query.php | 36 ++++++++------------------ 2 files changed, 22 insertions(+), 44 deletions(-) diff --git a/src/generators/model/default/model.php b/src/generators/model/default/model.php index f9fd806..73328c9 100644 --- a/src/generators/model/default/model.php +++ b/src/generators/model/default/model.php @@ -11,6 +11,8 @@ * @var schmunk42\giiant\generators\model\Generator $generator * @var string $tableName full table name * @var string $className class name + * @var string $ns class namespace + * @var string $queryClassName queryclass name * @var yii\db\TableSchema $tableSchema * @var string[] $labels list of attribute labels (name => label) * @var string[] $rules list of validation rules @@ -34,6 +36,9 @@ use ; + +use ns .'\\base' === $generator->queryNs ? $queryClassName : '\\' . $generator->queryNs . '\\' . $queryClassName) ?>; + /** * This is the base-model class for table "". @@ -47,19 +52,15 @@ * @property \\ - * @property string $aliasModel */ abstract class extends baseClass, '\\') . "\n" ?> { - baseTraits; if ($traits) { echo "use {$traits};"; } ?> - - @@ -85,6 +86,7 @@ public static function tableName() /** * @return \yii\db\Connection the database connection used by this AR class. + * @throws \yii\base\InvalidConfigException */ public static function getDb() { @@ -190,25 +192,20 @@ public function getTranslations() { } - + - ns .'\\base' === $generator->queryNs) ? $queryClassName : '\\' . $generator->queryNs . '\\' . $queryClassName; - echo "\n"; - ?> /** * @inheritdoc - * @return the active query used by this AR class. + * @return the active query used by this AR class. */ public static function find() { - return new (get_called_class()); + return new (static::class); } - $column_data){ + foreach($enum as $column_name => $column_data): ?> /** @@ -238,10 +235,5 @@ public static function () ?> ]; } - - + } diff --git a/src/generators/model/default/query.php b/src/generators/model/default/query.php index e6f4b81..69a2839 100644 --- a/src/generators/model/default/query.php +++ b/src/generators/model/default/query.php @@ -8,9 +8,10 @@ /* @var $className string class name */ /* @var $modelClassName string related model class name */ -$modelFullClassName = $modelClassName; if ($generator->ns !== $generator->queryNs) { - $modelFullClassName = '\\' . $generator->ns . '\\' . $modelFullClassName; + $modelFullClassName = '\\' . $generator->ns . '\\' . $modelClassName; +} else { + $modelFullClassName = $modelClassName; } echo "queryNs ?>; +use ; + /** - * This is the ActiveQuery class for [[]]. + * This is the ActiveQuery class for [[]]. * * @see + * @method [] all($db = null) + * @method one($db = null) */ class extends queryBaseClass, '\\') . "\n" ?> { - /*public function active() - { - $this->andWhere('[[status]]=1'); - return $this; - }*/ - - /** - * @inheritdoc - * @return []|array - */ - public function all($db = null) - { - return parent::all($db); - } - - /** - * @inheritdoc - * @return |array|null - */ - public function one($db = null) + /* public function active() { - return parent::one($db); - } + return $this->andWhere(['status' => 1]); + } */ } From 77457e807e60300316216e96d948c83691b9cf24 Mon Sep 17 00:00:00 2001 From: Elias Luhr Date: Wed, 13 Oct 2021 13:54:01 +0200 Subject: [PATCH 08/45] updated relation name and fixed view.php template --- src/commands/BatchController.php | 8 +- src/generators/crud/ModelTrait.php | 9 +-- src/generators/crud/default/views/view.php | 80 +++++++++---------- src/generators/model/Generator.php | 7 +- .../model/default/model-extended.php | 18 +---- 5 files changed, 60 insertions(+), 62 deletions(-) diff --git a/src/commands/BatchController.php b/src/commands/BatchController.php index dbc845f..844c4af 100644 --- a/src/commands/BatchController.php +++ b/src/commands/BatchController.php @@ -160,6 +160,11 @@ class BatchController extends Controller */ public $disablePluralization = false; + /** + * @var string prefix to prepend to the many many relation methods + */ + public $modelManyManyRelationSuffix = ''; + /** * @var bool whether the entity names will be singular or the same as the table name */ @@ -468,7 +473,8 @@ public function actionModels() 'queryBaseClass' => $this->modelQueryBaseClass, 'generateLabelsFromComments' => $this->modelGenerateLabelsFromComments, 'generateHintsFromComments' => $this->modelGenerateHintsFromComments, - 'disablePluralization' => $this->disablePluralization + 'disablePluralization' => $this->disablePluralization, + 'manyManyRelationSuffix' => $this->modelManyManyRelationSuffix ]; $route = 'gii/giiant-model'; diff --git a/src/generators/crud/ModelTrait.php b/src/generators/crud/ModelTrait.php index 4fb3c5a..99cac59 100644 --- a/src/generators/crud/ModelTrait.php +++ b/src/generators/crud/ModelTrait.php @@ -63,7 +63,7 @@ public function getModelByTableName($name) * * return values can be filtered by types 'belongs_to', 'many_many', 'has_many', 'has_one', 'pivot' * - * @param ActiveRecord $modelClass + * @param \yii\db\ActiveRecord $modelClass * @param array $types * * @return array @@ -77,11 +77,11 @@ public function getModelRelations($modelClass, $types = []) 'disablePluralization' => $this->disablePluralization ]); foreach ($reflector->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) { - if (in_array(substr($method->name, 3), $this->skipRelations)) { + if (in_array(substr($method->name, 3), $this->skipRelations, true)) { continue; } // look for getters - if (substr($method->name, 0, 3) !== 'get') { + if (strpos($method->name, 'get') !== 0) { continue; } // skip class specific getters @@ -119,7 +119,7 @@ public function getModelRelations($modelClass, $types = []) $relationType = 'has_many'; } // if types is empty, return all types -> no filter - if ((count($types) == 0) || in_array($relationType, $types)) { + if ((count($types) === 0) || in_array($relationType, $types, true)) { if ($this->disablePluralization) { $name = str_replace('get','', $method->name); } else { @@ -186,7 +186,6 @@ public function createRelationRoute($relation, $action) '-', true ).'/'.$action; - return $route; } diff --git a/src/generators/crud/default/views/view.php b/src/generators/crud/default/views/view.php index b43fd38..ba8985e 100644 --- a/src/generators/crud/default/views/view.php +++ b/src/generators/crud/default/views/view.php @@ -61,7 +61,7 @@

- '.$generator->getModelNameAttribute($generator->modelClass).") ?>\n" ?> + ' . $generator->getModelNameAttribute($generator->modelClass) . ") ?>\n" ?> modelMessageCategory}', '{$modelName}') ?>\n" ?> @@ -72,23 +72,23 @@
- Html::a( + Html::a( ' ' . generateString('Edit') ?>, [ 'update', ], ['class' => 'btn btn-info']) - ?> + ?> - Html::a( + Html::a( ' ' . generateString('Copy') ?>, ['create', , 'modelClass) ?>'=>$copyParams], ['class' => 'btn btn-success']) - ?> + ?> - Html::a( + Html::a( ' ' . generateString('New') ?>, ['create'], ['class' => 'btn btn-success']) - ?> + ?>
@@ -106,7 +106,7 @@ partialView('detail_prepend', $model); ?> - DetailView::widget([ + DetailView::widget([ 'model' => $model, 'attributes' => [ ], ]); - ?> + ?> partialView('detail_append', $model); ?>
- Html::a(' ' . generateString( + Html::a(' ' + . generateString( 'Delete' ) ?>, ['delete', ], [ @@ -135,7 +136,7 @@ 'data-confirm' => '' . generateString('Are you sure to delete this item?') ?> . '', 'data-method' => 'post', ]); - ?> + ?> endBlock(); ?>\n\n"; ?> getModelRelations($generator->modelClass, ['has_many', 'has_one']); - foreach ($relations as $name => $relation) { + foreach ($generator->getModelRelations($generator->modelClass, ['has_many', 'has_one']) as $name => $relation) { echo "\nbeginBlock('$name'); ?>\n"; $showAllRecords = false; if ($relation->via !== null) { - - $modelNameByTable = $generator->getModelByTableName($relation->via->from[0]); - if ($generator->disablePluralization) { - $pivotName = $modelNameByTable; - } else { - $pivotName = Inflector::pluralize($modelNameByTable); - } - $pivotRelation = $model->{'get'.$pivotName}(); + $modelName = $generator->getModelByTableName($relation->via->from[0]); + if ($generator->disablePluralization) { + $pivotName = $name; + } else { + $pivotName = Inflector::pluralize($modelName); + } + $label = Inflector::camel2words($pivotName); + $pivotRelation = $model->{'get' . $pivotName}(); $pivotPk = key($pivotRelation->link); $addButton = " ' . ".$generator->generateString('Attach')." . ' ". - Inflector::singularize(Inflector::camel2words($name)). - "', ['".$generator->createRelationRoute($pivotRelation, 'create')."', '". - Inflector::singularize($pivotName)."'=>['".key( + ' ' . " . $generator->generateString('Attach') . " . ' " . + $label . + "', ['" . $generator->createRelationRoute($pivotRelation, 'create') . "', '" . + $modelName . "'=>['" . key( $pivotRelation->link - )."'=>\$model->{$model->primaryKey()[0]}]], + ) . "'=>\$model->{$model->primaryKey()[0]}]], ['class'=>'btn btn-info btn-xs'] ) ?>\n"; } else { $addButton = ''; + $label = Inflector::camel2words($name); } // relation list, add, create buttons -// echo "
\n
\n"; echo "
\n"; echo " ' . ".$generator->generateString('List All')." . ' ". - Inflector::camel2words($name)."', - ['".$generator->createRelationRoute($relation, 'index')."'], + ' ' . " . $generator->generateString('List All') . " . ' " . + $label . "', + ['" . $generator->createRelationRoute($relation, 'index') . "'], ['class'=>'btn text-muted btn-xs'] ) ?>\n"; // TODO: support multiple PKs // pivot check if ($relation->via !== null) { - $url = "['".$generator->createRelationRoute($relation, 'create')."']"; + $url = "['" . $generator->createRelationRoute($relation, 'create') . "']"; } else { - $url = "['".$generator->createRelationRoute($relation, 'create')."', '". + $url = "['" . $generator->createRelationRoute($relation, 'create') . "', '" . Inflector::id2camel($generator->generateRelationTo($relation), '-', - true)."' => ['".key($relation->link)."' => \$model->".$model->primaryKey()[0]."]]"; + true) . "' => ['" . key($relation->link) . "' => \$model->" . $model->primaryKey()[0] . "]]"; } - echo " ' . ".$generator->generateString('New')." . ' ". - Inflector::camel2words($name)."', + echo " ' . " . $generator->generateString('New') . " . ' " . + $label . "', {$url}, ['class'=>'btn btn-success btn-xs'] ); ?>\n"; echo $addButton; - echo "
\n
"; #
\n"; + echo "
\n
"; // render pivot grid if ($relation->via !== null) { $pjaxId = "pjax-{$pivotName}"; @@ -230,14 +230,12 @@ // render relation grid if (!empty($output)): echo "'pjax-{$name}', 'enableReplaceState'=> false, 'linkSelector'=>'#pjax-{$name} ul.pagination a, th a']) ?>\n"; - echo "\n"; + echo "\n"; echo "\n"; endif; echo "endBlock() ?>\n\n"; - // build tab items - $label = Inflector::camel2words($name); $items .= << \$this->blocks['$name'], diff --git a/src/generators/model/Generator.php b/src/generators/model/Generator.php index e493a63..c0aafa2 100644 --- a/src/generators/model/Generator.php +++ b/src/generators/model/Generator.php @@ -94,6 +94,11 @@ class Generator extends \yii\gii\generators\model\Generator */ public $baseClassPrefix = ''; + /** + * @var string prefix to prepend to the many many relation methods + */ + public $manyManyRelationSuffix = ''; + /** * @var string suffix to append to the base model, setting "Base" will result in a model named "PostBase" */ @@ -463,7 +468,7 @@ public function generateRelationName($relations, $table, $key, $multiple) $suffix = ''; if ($this->disablePluralization) { if ($multiple) { -// $suffix = 'N'; + $suffix = $this->manyManyRelationSuffix; } $multiple = false; } diff --git a/src/generators/model/default/model-extended.php b/src/generators/model/default/model-extended.php index 4a6f510..3e75e1e 100644 --- a/src/generators/model/default/model-extended.php +++ b/src/generators/model/default/model-extended.php @@ -17,9 +17,7 @@ namespace ns ?>; -use Yii; use \ns ?>\base\ as Base; -use yii\helpers\ArrayHelper; /** * This is the model class for table "". @@ -29,21 +27,13 @@ class extends Base public function behaviors() { - return ArrayHelper::merge( - parent::behaviors(), - [ - # custom behaviors - ] - ); + $behaviors = parent::behaviors(); + return $behaviors; } public function rules() { - return ArrayHelper::merge( - parent::rules(), - [ - # custom validation rules - ] - ); + $rules = parent::rules(); + return $rules; } } From 10381a90f9fc97e93d0b27a40c73435413eee955 Mon Sep 17 00:00:00 2001 From: Elias Luhr Date: Wed, 20 Oct 2021 13:22:11 +0200 Subject: [PATCH 09/45] Fixed relation provider --- src/generators/crud/providers/core/RelationProvider.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/generators/crud/providers/core/RelationProvider.php b/src/generators/crud/providers/core/RelationProvider.php index 8f2cba6..a084539 100644 --- a/src/generators/crud/providers/core/RelationProvider.php +++ b/src/generators/crud/providers/core/RelationProvider.php @@ -235,7 +235,7 @@ public function columnFormat($attribute, $model) $name = $this->generator->getModelNameAttribute($relation->modelClass); $pk = key($relation->link); - $filter = "\n'filter' => \yii\helpers\ArrayHelper::map({$relation->modelClass}::find()->select(['{$pk}', '{$name}'])->asArray()->all(), '{$pk}', '{$name}'),"; + $filter = "\n'filter' => \yii\helpers\ArrayHelper::map({$relation->modelClass}::find()->all(), '{$pk}', '{$name}'),"; } $code = << Date: Thu, 4 Nov 2021 10:36:29 +0100 Subject: [PATCH 10/45] Added translatables in view and index --- src/generators/crud/default/views/index.php | 10 ++-- src/generators/crud/default/views/view.php | 56 +++++++-------------- 2 files changed, 23 insertions(+), 43 deletions(-) diff --git a/src/generators/crud/default/views/index.php b/src/generators/crud/default/views/index.php index bfc4047..42b3e58 100644 --- a/src/generators/crud/default/views/index.php +++ b/src/generators/crud/default/views/index.php @@ -95,10 +95,8 @@ 'pjax-main', 'enableReplaceState'=> false, 'linkSelector'=>'#pjax-main ul.pagination a, th a', 'clientOptions' => ['pjax:success'=>'function(){alert(\"yo\")}']]) ?>\n"; ?>

- modelMessageCategory}.plural', '{$modelName}') ?>\n" ?> - - messageCategory}', 'List') ?>\n" ?> - + generateString($modelName) . "?>\n" ?> + generateString('List') . "?>\n" ?>

Html::a(' ' . generateString( - 'New' + 'New ' . $modelName ) ?>, ['create'], ['class' => 'btn btn-success']) ?>
Html::a(' ' . generateString( - 'New' + 'New ' . $modelName ) ?>, ['create'], ['class' => 'btn btn-success']) ?>
modelClass(); @@ -20,11 +17,11 @@ $safeAttributes = $model->safeAttributes(); } if (empty($safeAttributes)) { - $safeAttributes = $model->getTableSchema()->columnNames; + $safeAttributes = $model::getTableSchema()->columnNames; } -$modelName = Inflector::camel2words(StringHelper::basename($model::className())); $className = $model::className(); +$modelName = Inflector::camel2words(StringHelper::basename($className)); $urlParams = $generator->generateUrlParams(); echo "attributes; -$this->title = Yii::t('modelMessageCategory ?>', ''); -$this->params['breadcrumbs'][] = ['label' => Yii::t('modelMessageCategory ?>.plural', ''), 'url' => ['index']]; +$this->title = generateString($modelName) ?>; +$this->params['breadcrumbs'][] = ['label' => generateString($modelName) ?>, 'url' => ['index']]; $this->params['breadcrumbs'][] = ['label' => (string)$model->getNameAttribute() ?>, 'url' => ['view', ]]; $this->params['breadcrumbs'][] = generateString('View') ?>; ?>
- - session->getFlash('deleteError') !== null) : ?> - - - session->getFlash('deleteError') ?> - - " ?> - -

' . $generator->getModelNameAttribute($generator->modelClass) . ") ?>\n" ?> - - modelMessageCategory}', '{$modelName}') ?>\n" ?> - + generateString($modelName) . ' ?>' ?>

-
Html::a( - ' ' . generateString('Edit') ?>, + ' ' . generateString('Edit ' . $modelName) ?>, [ 'update', ], ['class' => 'btn btn-info']) ?> Html::a( - ' ' . generateString('Copy') ?>, + ' ' . generateString('Copy ' . $modelName) ?>, ['create', , 'modelClass) ?>'=>$copyParams], ['class' => 'btn btn-success']) ?> Html::a( - ' ' . generateString('New') ?>, + ' ' . generateString('New ' . $modelName) ?>, ['create'], ['class' => 'btn btn-success']) ?> @@ -129,7 +113,7 @@ Html::a(' ' . generateString( - 'Delete' + 'Delete ' . $modelName ) ?>, ['delete', ], [ 'class' => 'btn btn-danger', @@ -169,9 +153,8 @@ $pivotPk = key($pivotRelation->link); $addButton = " ' . " . $generator->generateString('Attach') . " . ' " . - $label . - "', ['" . $generator->createRelationRoute($pivotRelation, 'create') . "', '" . + ' ' . " . $generator->generateString('Attach ' . $label) . + ", ['" . $generator->createRelationRoute($pivotRelation, 'create') . "', '" . $modelName . "'=>['" . key( $pivotRelation->link ) . "'=>\$model->{$model->primaryKey()[0]}]], @@ -187,8 +170,7 @@ echo " ' . " . $generator->generateString('List All') . " . ' " . - $label . "', + ' ' . " . $generator->generateString('List All ' . $label) . ", ['" . $generator->createRelationRoute($relation, 'index') . "'], ['class'=>'btn text-muted btn-xs'] ) ?>\n"; @@ -205,8 +187,7 @@ } echo " ' . " . $generator->generateString('New') . " . ' " . - $label . "', + ' ' . " . $generator->generateString('New ' . $label) . ", {$url}, ['class'=>'btn btn-success btn-xs'] ); ?>\n"; @@ -236,10 +217,11 @@ echo "endBlock() ?>\n\n"; // build tab items + $itemLabel = $generator->generateString($label); $items .= << \$this->blocks['$name'], - 'label' => '$label '. \$model->get{$name}()->count() . '', + 'label' => '' . $itemLabel .' '. \$model->get{$name}()->count() . '', 'active' => false, ],\n EOS; From c3d7fd8d9c4f7c4a5716831a10ed8002d969f8e8 Mon Sep 17 00:00:00 2001 From: Elias Luhr Date: Thu, 9 Dec 2021 12:21:06 +0100 Subject: [PATCH 11/45] translatable for detail tab label --- src/generators/crud/default/views/view.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/generators/crud/default/views/view.php b/src/generators/crud/default/views/view.php index 00b4f1e..b0c4caf 100644 --- a/src/generators/crud/default/views/view.php +++ b/src/generators/crud/default/views/view.php @@ -130,7 +130,7 @@ $items = << '# '.Html::encode(\$model->{$model->primaryKey()[0]}).'', + 'label' => '' . \Yii::t('{$generator->messageCategory}', '# {primaryKey}', ['primaryKey' => Html::encode(\$model->{$model->primaryKey()[0]})]) . '', 'content' => \$this->blocks['{$generator->modelClass}'], 'active' => true, ], From 667f8e2622163109642d33578cdec464f036d50e Mon Sep 17 00:00:00 2001 From: Elias Luhr Date: Tue, 14 Dec 2021 12:30:29 +0100 Subject: [PATCH 12/45] updated controller --- src/generators/crud/default/controller.php | 290 ++++++++++----------- 1 file changed, 141 insertions(+), 149 deletions(-) diff --git a/src/generators/crud/default/controller.php b/src/generators/crud/default/controller.php index d8c965e..edf9577 100644 --- a/src/generators/crud/default/controller.php +++ b/src/generators/crud/default/controller.php @@ -2,11 +2,12 @@ use yii\helpers\StringHelper; -/* +/** * This is the template for generating a CRUD controller class file. * * @var yii\web\View $this * @var schmunk42\giiant\generators\crud\Generator $generator + * @var array $accessDefinitions */ $controllerClass = StringHelper::basename($generator->controllerClass); @@ -37,20 +38,23 @@ use modelClass, '\\') ?>; - use searchModelClass, '\\' ) ?> as ; use baseControllerClass, '\\') ?>; -use yii\web\HttpException; use yii\helpers\Url; +accessFilter): ?> use yii\filters\AccessControl; + use dmstr\bootstrap\Tabs; +use Yii; +use yii\web\NotFoundHttpException; /** -* implements the CRUD actions for model. -*/ + * implements the CRUD actions for model. + */ class extends baseControllerClass)."\n" ?> { @@ -61,11 +65,11 @@ class extends bas } ?> -/** -* @var boolean whether to enable CSRF validation for the actions in this controller. -* CSRF validation is enabled only when both this property and [[Request::enableCsrfValidation]] are true. -*/ -public $enableCsrfValidation = false; + /** + * @var boolean whether to enable CSRF validation for the actions in this controller. + * CSRF validation is enabled only when both this property and [[Request::enableCsrfValidation]] are true. + */ + public $enableCsrfValidation = false; accessFilter): ?> /** @@ -94,151 +98,139 @@ public function behaviors() } -/** -* Lists all models. -* @return mixed -*/ -public function actionIndex() -{ - - $searchModel = new ; - $dataProvider = $searchModel->search($_GET); - - $dataProvider = new \yii\data\ActiveDataProvider([ - 'query' => ::find(), - ]); - - -Tabs::clearLocalStorage(); - -Url::remember(); -\Yii::$app->session['__crudReturnUrl'] = null; - -return $this->render('index', [ -'dataProvider' => $dataProvider, - + /** + * Lists all models. + * + * @return string + */ + public function actionIndex() + { + + $searchModel = new (); + $dataProvider = $searchModel->search($_GET); + + $dataProvider = new \yii\data\ActiveDataProvider([ + 'query' => ::find(), + ]); + + + Tabs::clearLocalStorage(); + + Url::remember(); + Yii::$app->session->set('__crudReturnUrl', null); + + return $this->render('index', [ + 'dataProvider' => $dataProvider, + 'searchModel' => $searchModel, - + ]); -} - -/** -* Displays a single model. -* -* -* @return mixed -*/ -public function actionView() -{ -\Yii::$app->session['__crudReturnUrl'] = Url::previous(); -Url::remember(); -Tabs::rememberActiveState(); - -return $this->render('view', [ -'model' => $this->findModel(), -]); -} - -/** -* Creates a new model. -* If creation is successful, the browser will be redirected to the 'view' page. -* @return mixed -*/ -public function actionCreate() -{ -$model = new ; - -try { -if ($model->load($_POST) && $model->save()) { -return $this->redirect(['view', ]); -} elseif (!\Yii::$app->request->isPost) { -$model->load($_GET); -} -} catch (\Exception $e) { -$msg = (isset($e->errorInfo[2]))?$e->errorInfo[2]:$e->getMessage(); -$model->addError('_exception', $msg); -} -return $this->render('create', ['model' => $model]); -} - -/** -* Updates an existing model. -* If update is successful, the browser will be redirected to the 'view' page. -* -* @return mixed -*/ -public function actionUpdate() -{ -$model = $this->findModel(); + } -if ($model->load($_POST) && $model->save()) { -return $this->redirect(Url::previous()); -} else { -return $this->render('update', [ -'model' => $model, -]); -} -} + /** + * Displays a single model. + * + * + * + * @return string + * @throws \yii\web\HttpException + */ + public function actionView() + { + Yii::$app->session->set('__crudReturnUrl', Url::previous()); + Url::remember(); + Tabs::rememberActiveState(); + return $this->render('view', ['model' => $this->findModel()]); + } -/** -* Deletes an existing model. -* If deletion is successful, the browser will be redirected to the 'index' page. -* -* @return mixed -*/ -public function actionDelete() -{ -try { -$this->findModel()->delete(); -} catch (\Exception $e) { -$msg = (isset($e->errorInfo[2]))?$e->errorInfo[2]:$e->getMessage(); -\Yii::$app->getSession()->addFlash('error', $msg); -return $this->redirect(Url::previous()); -} + /** + * Creates a new model. + * If creation is successful, the browser will be redirected to the 'view' page. + * + * @return string|\yii\web\Response + */ + public function actionCreate() + { + $model = new (); + try { + if ($model->load(Yii::$app->request->post()) && $model->save()) { + return $this->redirect(['view', ]); + } + if (!Yii::$app->request->isPost) { + $model->load(Yii::$app->request->get()); + } + } catch (\Exception $e) { + $model->addError('_exception', $e->errorInfo[2] ?? $e->getMessage()); + } + return $this->render('create', ['model' => $model]); + } -// TODO: improve detection -$isPivot = strstr('',','); -if ($isPivot == true) { -return $this->redirect(Url::previous()); -} elseif (isset(\Yii::$app->session['__crudReturnUrl']) && \Yii::$app->session['__crudReturnUrl'] != '/') { -Url::remember(null); -$url = \Yii::$app->session['__crudReturnUrl']; -\Yii::$app->session['__crudReturnUrl'] = null; + /** + * Updates an existing model. + * If update is successful, the browser will be redirected to the 'view' page. + * + * + * @return string|\yii\web\Response + * @throws \yii\web\HttpException + */ + public function actionUpdate() + { + $model = $this->findModel(); + if ($model->load($_POST) && $model->save()) { + return $this->redirect(Url::previous()); + } + return $this->render('update', ['model' => $model]); + } -return $this->redirect($url); -} else { -return $this->redirect(['index']); -} -} + /** + * Deletes an existing model. + * If deletion is successful, the browser will be redirected to the 'index' page. + * + * + * @return \yii\web\Response + * @throws \Throwable + */ + public function actionDelete() + { + try { + $this->findModel()->delete(); + } catch (\Exception $e) { + Yii::$app->getSession()->addFlash('error', $e->errorInfo[2] ?? $e->getMessage()); + return $this->redirect(Url::previous()); + } + + return $this->redirect(['index']); + } -/** -* Finds the model based on its primary key value. -* If the model is not found, a 404 HTTP exception will be thrown. -* -* @return the loaded model -* @throws HttpException if the model cannot be found -*/ -protected function findModel() -{ - \$$pk"; + /** + * Finds the model based on its primary key value. + * If the model is not found, a 404 HTTP exception will be thrown. + * + * + * @return the loaded model + * @throws NotFoundHttpException if the model cannot be found + */ + protected function findModel() + { + \$$pk"; + } + $condition = '['.implode(', ', $condition).']'; + } + ?> + $model = ::findOne(); + if ($model !== null) { + return $model; + } + throw new NotFoundHttpException(generateString('The requested page does not exist.')?>); } - $condition = '['.implode(', ', $condition).']'; -} -?> -if (($model = ::findOne()) !== null) { -return $model; -} else { -throw new HttpException(404, 'The requested page does not exist.'); -} -} } From d2a659f966c7227c4e06759ec2876211391ae5b1 Mon Sep 17 00:00:00 2001 From: Elias Luhr Date: Thu, 20 Jan 2022 15:33:42 +0100 Subject: [PATCH 13/45] Grid max columns --- src/commands/BatchController.php | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/commands/BatchController.php b/src/commands/BatchController.php index 844c4af..338bd1f 100644 --- a/src/commands/BatchController.php +++ b/src/commands/BatchController.php @@ -274,6 +274,11 @@ class BatchController extends Controller */ public $crudFixOutput = false; + /** + * @var int maximum number of columns to show in grid + */ + public $crudGridMaxColumns = 8; + /** * @var string the namespace of the ActiveQuery class to be generated */ @@ -523,7 +528,6 @@ public function actionCruds() 'overwriteSearchModelClass' => $this->crudOverwriteSearchModelClass, 'overwriteRestControllerClass' => $this->crudOverwriteRestControllerClass, 'overwriteControllerClass' => $this->crudOverwriteControllerClass, - 'template' => $this->template, 'modelClass' => $this->modelNamespace . '\\' . $name, 'searchModelClass' => $this->crudSearchModelNamespace . '\\' . $name . $this->crudSearchModelSuffix, 'controllerNs' => $this->crudControllerNamespace, @@ -549,7 +553,8 @@ public function actionCruds() 'formLayout' => $this->crudFormLayout, 'generateAccessFilterMigrations' => $this->generateAccessFilterMigrations, 'actionButtonColumnPosition' => $this->crudActionButtonColumnPosition, - 'disablePluralization' => $this->disablePluralization + 'disablePluralization' => $this->disablePluralization, + 'gridMaxColumns' => $this->crudGridMaxColumns ]; $route = 'gii/giiant-crud'; $app = \Yii::$app; From 0e3376a1f050d18e3b6d81b73387b2fe50ffa9a7 Mon Sep 17 00:00:00 2001 From: Elias Luhr Date: Mon, 24 Jan 2022 12:18:18 +0100 Subject: [PATCH 14/45] introduce different optional scenarios --- src/generators/crud/default/views/_form.php | 10 ++++++--- src/generators/crud/default/views/index.php | 21 ++++++++++++------- src/generators/crud/default/views/view.php | 6 +++++- .../crud/providers/core/RelationProvider.php | 12 +++++++---- 4 files changed, 33 insertions(+), 16 deletions(-) diff --git a/src/generators/crud/default/views/_form.php b/src/generators/crud/default/views/_form.php index e8b2be2..27d3507 100644 --- a/src/generators/crud/default/views/_form.php +++ b/src/generators/crud/default/views/_form.php @@ -2,7 +2,7 @@ use yii\helpers\StringHelper; -/* +/** * @var yii\web\View $this * @var yii\gii\generators\crud\Generator $generator */ @@ -10,14 +10,18 @@ /** @var \yii\db\ActiveRecord $model */ ## TODO: move to generator (?); cleanup $model = new $generator->modelClass(); -$model->setScenario('crud'); +if (array_key_exists('crud-form', $model->scenarios())) { + $model->setScenario('crud-form'); +} else { + $model->setScenario('crud'); +} $safeAttributes = $model->safeAttributes(); if (empty($safeAttributes)) { $model->setScenario('default'); $safeAttributes = $model->safeAttributes(); } if (empty($safeAttributes)) { - $safeAttributes = $model->getTableSchema()->columnNames; + $safeAttributes = $model::getTableSchema()->columnNames; } echo "generateUrlParams(); @@ -13,7 +14,11 @@ /** @var \yii\db\ActiveRecord $model */ $model = new $generator->modelClass(); -$model->setScenario('crud'); +if (array_key_exists('crud-list', $model->scenarios())) { + $model->setScenario('crud-list'); +} else { + $model->setScenario('crud'); +} $baseName = StringHelper::basename($model::className()); $modelName = Inflector::camel2words($baseName); @@ -24,7 +29,7 @@ $model = new $generator->modelClass(); $safeAttributes = $model->safeAttributes(); if (empty($safeAttributes)) { - $safeAttributes = $model->getTableSchema()->columnNames; + $safeAttributes = $model::getTableSchema()->columnNames; } } @@ -144,7 +149,7 @@ true ); $route = $generator->createRelationRoute($relation, 'index'); - $label = Inflector::titleize(StringHelper::basename($relation->modelClass), '-', true); + $label = Inflector::titleize(StringHelper::basename($relation->modelClass), '-'); $items .= << ['{$route}'], @@ -222,25 +227,25 @@ $count = 0; // action buttons first - if ($generator->actionButtonColumnPosition != 'right') { + if ($generator->actionButtonColumnPosition !== 'right') { echo $actionButtonColumn; echo "\n"; // code-formatting } + foreach ($safeAttributes as $attribute) { $format = trim($generator->columnFormat($attribute, $model)); if ($format == false) { continue; } - if (++$count < $generator->gridMaxColumns) { + if (++$count <= $generator->gridMaxColumns) { echo "\t\t\t" . str_replace("\n", "\n\t\t\t", $format) . ",\n"; } else { echo "\t\t\t/*" . str_replace("\n", "\n\t\t\t", $format) . ",*/\n"; } } - ?> - actionButtonColumnPosition == 'right') { + actionButtonColumnPosition === 'right') { echo $actionButtonColumn; echo "\n"; // code-formatting } ?> diff --git a/src/generators/crud/default/views/view.php b/src/generators/crud/default/views/view.php index d7e8017..39eef38 100644 --- a/src/generators/crud/default/views/view.php +++ b/src/generators/crud/default/views/view.php @@ -10,7 +10,11 @@ ## TODO: move to generator (?); cleanup $model = new $generator->modelClass(); -$model->setScenario('crud'); +if (array_key_exists('crud-view', $model->scenarios())) { + $model->setScenario('crud-view'); +} else { + $model->setScenario('crud'); +} $safeAttributes = $model->safeAttributes(); if (empty($safeAttributes)) { $model->setScenario('default'); diff --git a/src/generators/crud/providers/core/RelationProvider.php b/src/generators/crud/providers/core/RelationProvider.php index a084539..0fad4ef 100644 --- a/src/generators/crud/providers/core/RelationProvider.php +++ b/src/generators/crud/providers/core/RelationProvider.php @@ -337,14 +337,18 @@ public function relationGrid($name, $relation, $showAllRecords = false) } // prepare grid column formatters - $model->setScenario('crud'); + if (array_key_exists('crud-list', $model->scenarios())) { + $model->setScenario('crud-list'); + } else { + $model->setScenario('crud'); + } $safeAttributes = $model->safeAttributes(); if (empty($safeAttributes)) { $safeAttributes = $model->getTableSchema()->columnNames; } foreach ($safeAttributes as $attr) { - // max seven columns + // max defined amount of columns if ($counter > $this->generator->gridRelationMaxColumns) { continue; } @@ -353,12 +357,12 @@ public function relationGrid($name, $relation, $showAllRecords = false) continue; } // don't show current model - if (key($relation->link) == $attr) { + if (key($relation->link) === $attr) { continue; } $code = $this->generator->columnFormat($attr, $model); - if ($code == false) { + if ($code === false) { continue; } $columns .= $code.",\n"; From 813ccb454a51dfa6b207e8e51ac1d6562458032b Mon Sep 17 00:00:00 2001 From: Elias Luhr Date: Tue, 1 Feb 2022 13:00:48 +0100 Subject: [PATCH 15/45] removed not needed code --- src/generators/crud/default/views/index.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/generators/crud/default/views/index.php b/src/generators/crud/default/views/index.php index c12f06d..fb079a5 100644 --- a/src/generators/crud/default/views/index.php +++ b/src/generators/crud/default/views/index.php @@ -97,7 +97,7 @@ indexWidgetType === 'grid'): ?> - 'pjax-main', 'enableReplaceState'=> false, 'linkSelector'=>'#pjax-main ul.pagination a, th a', 'clientOptions' => ['pjax:success'=>'function(){alert(\"yo\")}']]) ?>\n"; ?> + 'pjax-main', 'enableReplaceState'=> false, 'linkSelector'=>'#pjax-main ul.pagination a, th a']) ?>\n"; ?>

generateString($modelName) . "?>\n" ?> From b4a80b998b51bc6fc728ebaac08be9242939f6ec Mon Sep 17 00:00:00 2001 From: Elias Luhr Date: Tue, 22 Feb 2022 12:43:37 +0100 Subject: [PATCH 16/45] another scenario for detail relation --- .../crud/providers/core/RelationProvider.php | 35 +++++++++++-------- 1 file changed, 20 insertions(+), 15 deletions(-) diff --git a/src/generators/crud/providers/core/RelationProvider.php b/src/generators/crud/providers/core/RelationProvider.php index 0fad4ef..a6294ff 100644 --- a/src/generators/crud/providers/core/RelationProvider.php +++ b/src/generators/crud/providers/core/RelationProvider.php @@ -5,6 +5,7 @@ * Date: 14.03.14 * Time: 10:21. */ + namespace schmunk42\giiant\generators\crud\providers\core; use schmunk42\giiant\generators\model\Generator as ModelGenerator; @@ -54,7 +55,8 @@ public function activeField($attribute) if (is_string($column)) { return null; } - $relation = $this->generator->getRelationByColumn($this->generator->modelClass, $column, ['belongs_to', 'has_one']); + $relation = $this->generator->getRelationByColumn($this->generator->modelClass, $column, + ['belongs_to', 'has_one']); if ($relation) { switch (true) { case !$relation->multiple: @@ -128,7 +130,8 @@ public function attributeFormat($attribute) //return null; #TODO: double check with primary keys not named `id` of non-pivot tables } - $relation = $this->generator->getRelationByColumn($this->generator->modelClass, $column, ['belongs_to', 'has_one']); + $relation = $this->generator->getRelationByColumn($this->generator->modelClass, $column, + ['belongs_to', 'has_one']); if ($relation) { if ($relation->multiple) { return; @@ -144,11 +147,11 @@ public function attributeFormat($attribute) $relationProperty = lcfirst((new ModelGenerator([ 'disablePluralization' => $this->generator->disablePluralization ]))->generateRelationName( - [$relation], - $modelClass::getTableSchema(), - $column->name, - $relation->multiple - )); + [$relation], + $modelClass::getTableSchema(), + $column->name, + $relation->multiple + )); $relationModel = new $relation->modelClass(); $relationModelName = StringHelper::basename($modelClass); $pks = $relationModel->primaryKey(); @@ -216,11 +219,11 @@ public function columnFormat($attribute, $model) $method = __METHOD__; $modelClass = $this->generator->modelClass; $relationProperty = lcfirst((new ModelGenerator())->generateRelationName( - [$relation], - $modelClass::getTableSchema(), - $column->name, - $relation->multiple - )); + [$relation], + $modelClass::getTableSchema(), + $column->name, + $relation->multiple + )); $relationModel = new $relation->modelClass(); $pks = $relationModel->primaryKey(); $paramArrayItems = ''; @@ -310,7 +313,7 @@ public function relationGrid($name, $relation, $showAllRecords = false) } $reflection = new \ReflectionClass($relation->modelClass); - $controller = $this->generator->pathPrefix.Inflector::camel2id($reflection->getShortName(), '-', true); + $controller = $this->generator->pathPrefix . Inflector::camel2id($reflection->getShortName(), '-', true); $relKey = key($relation->link); $actionColumn = <<scenarios())) { + if (array_key_exists('crud-relation-list', $model->scenarios())) { + $model->setScenario('crud-relation-list'); + } else if (array_key_exists('crud-list', $model->scenarios())) { $model->setScenario('crud-list'); } else { $model->setScenario('crud'); @@ -365,7 +370,7 @@ public function relationGrid($name, $relation, $showAllRecords = false) if ($code === false) { continue; } - $columns .= $code.",\n"; + $columns .= $code . ",\n"; ++$counter; } From 6a2bc961a3bb95be04b7f24be02c5632e9599d75 Mon Sep 17 00:00:00 2001 From: Elias Luhr Date: Tue, 22 Feb 2022 13:25:51 +0100 Subject: [PATCH 17/45] bug fix for not defined relations --- src/generators/crud/providers/core/RelationProvider.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/generators/crud/providers/core/RelationProvider.php b/src/generators/crud/providers/core/RelationProvider.php index a6294ff..d7fca36 100644 --- a/src/generators/crud/providers/core/RelationProvider.php +++ b/src/generators/crud/providers/core/RelationProvider.php @@ -351,6 +351,7 @@ public function relationGrid($name, $relation, $showAllRecords = false) if (empty($safeAttributes)) { $safeAttributes = $model->getTableSchema()->columnNames; } + foreach ($safeAttributes as $attr) { // max defined amount of columns @@ -362,7 +363,7 @@ public function relationGrid($name, $relation, $showAllRecords = false) continue; } // don't show current model - if (key($relation->link) === $attr) { + if (key($relation->link) === $attr && !in_array($attr, $safeAttributes, true)) { continue; } From f2352c7b39d14f36de493d5c780d2b232229ddd7 Mon Sep 17 00:00:00 2001 From: Elias Luhr Date: Thu, 23 Mar 2023 15:28:37 +0100 Subject: [PATCH 18/45] merge with parent method calls --- src/generators/model/default/model.php | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/generators/model/default/model.php b/src/generators/model/default/model.php index b3f0595..b7f8eeb 100644 --- a/src/generators/model/default/model.php +++ b/src/generators/model/default/model.php @@ -98,7 +98,7 @@ public static function getDb() */ public function behaviors() { - return [ + return ArrayHelper::merge(parent::behaviors(), [ [ 'class' => BlameableBehavior::className(), @@ -134,7 +134,7 @@ public function behaviors() ], ], - ]; + ]); } @@ -143,7 +143,7 @@ public function behaviors() */ public function rules() { - return []; + return ArrayHelper::merge(parent::rules(), []); } /** @@ -151,11 +151,11 @@ public function rules() */ public function attributeLabels() { - return [ + return ArrayHelper::merge(parent::attributeLabels(), [ $label): ?> " . $generator->generateString($label) . ",\n" ?> - ]; + ]); } @@ -164,7 +164,7 @@ public function attributeLabels() */ public function attributeHints() { - return array_merge(parent::attributeHints(), [ + return ArrayHelper::merge(parent::attributeHints(), [ $hint): ?> " . $generator->generateString($hint) . ",\n" ?> From 40c195b2df0345677a39ea112fdf52b0519637bc Mon Sep 17 00:00:00 2001 From: Elias Luhr Date: Fri, 24 Mar 2023 23:02:46 +0100 Subject: [PATCH 19/45] catch throwable because a component can be wrong implemented --- src/commands/BatchController.php | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/src/commands/BatchController.php b/src/commands/BatchController.php index ac3d5c1..c3a3177 100644 --- a/src/commands/BatchController.php +++ b/src/commands/BatchController.php @@ -629,9 +629,14 @@ private function closeTempAppConnections(Application $app) // since we don't know if there are any other than the "known" modelDb if (isset($app->components)) { foreach ($app->components as $cid => $component) { - $cObj = $app->get($cid); - if ($cObj instanceof \yii\db\Connection) { - $cObj->close(); + try { + $cObj = $app->get($cid); + if ($cObj instanceof \yii\db\Connection) { + $cObj->close(); + } + } catch (\Throwable $e) { + // ignore because we don't know if the component is a db connection + Yii::warning($e->getMessage()); } } } From 08bd2a50ccc34e4c1d4b33b8943de8eae72769f8 Mon Sep 17 00:00:00 2001 From: Elias Luhr Date: Fri, 24 Mar 2023 23:15:04 +0100 Subject: [PATCH 20/45] cleanup controller --- src/generators/crud/default/controller.php | 44 ++++++++-------------- 1 file changed, 16 insertions(+), 28 deletions(-) diff --git a/src/generators/crud/default/controller.php b/src/generators/crud/default/controller.php index edf9577..05f99c3 100644 --- a/src/generators/crud/default/controller.php +++ b/src/generators/crud/default/controller.php @@ -48,7 +48,6 @@ accessFilter): ?> use yii\filters\AccessControl; -use dmstr\bootstrap\Tabs; use Yii; use yii\web\NotFoundHttpException; @@ -65,12 +64,6 @@ class extends bas } ?> - /** - * @var boolean whether to enable CSRF validation for the actions in this controller. - * CSRF validation is enabled only when both this property and [[Request::enableCsrfValidation]] are true. - */ - public $enableCsrfValidation = false; - accessFilter): ?> /** * @inheritdoc @@ -81,7 +74,7 @@ public function behaviors() 'access' => [ 'class' => AccessControl::className(), 'rules' => [ - $actions){ ?> [ @@ -89,9 +82,9 @@ public function behaviors() 'actions' => [''], 'roles' => [''], ], - +?> ], ], ]; @@ -101,28 +94,24 @@ public function behaviors() /** * Lists all models. * + * @throws yii\base\InvalidConfigException * @return string */ public function actionIndex() { - $searchModel = new (); - $dataProvider = $searchModel->search($_GET); + $searchModel = Yii::createObject(::class); + $dataProvider = $searchModel->search($this->request->get()); - $dataProvider = new \yii\data\ActiveDataProvider([ + $dataProvider = new ActiveDataProvider([ 'query' => ::find(), ]); - Tabs::clearLocalStorage(); - - Url::remember(); - Yii::$app->session->set('__crudReturnUrl', null); - return $this->render('index', [ 'dataProvider' => $dataProvider, @@ -141,9 +130,6 @@ public function actionIndex() */ public function actionView() { - Yii::$app->session->set('__crudReturnUrl', Url::previous()); - Url::remember(); - Tabs::rememberActiveState(); return $this->render('view', ['model' => $this->findModel()]); } @@ -151,17 +137,18 @@ public function actionView() * Creates a new model. * If creation is successful, the browser will be redirected to the 'view' page. * + * @throws yii\base\InvalidConfigException * @return string|\yii\web\Response */ public function actionCreate() { - $model = new (); + $model = Yii::createObject(::class); try { - if ($model->load(Yii::$app->request->post()) && $model->save()) { + if ($model->load($this->request->post()) && $model->save()) { return $this->redirect(['view', ]); } if (!Yii::$app->request->isPost) { - $model->load(Yii::$app->request->get()); + $model->load($this->request->get()); } } catch (\Exception $e) { $model->addError('_exception', $e->errorInfo[2] ?? $e->getMessage()); @@ -174,13 +161,14 @@ public function actionCreate() * If update is successful, the browser will be redirected to the 'view' page. * * - * @return string|\yii\web\Response + * * @throws \yii\web\HttpException + * @return string|\yii\web\Response */ public function actionUpdate() { $model = $this->findModel(); - if ($model->load($_POST) && $model->save()) { + if ($model->load($this->request->post()) && $model->save()) { return $this->redirect(Url::previous()); } return $this->render('update', ['model' => $model]); @@ -200,7 +188,6 @@ public function actionDelete() $this->findModel()->delete(); } catch (\Exception $e) { Yii::$app->getSession()->addFlash('error', $e->errorInfo[2] ?? $e->getMessage()); - return $this->redirect(Url::previous()); } return $this->redirect(['index']); @@ -211,8 +198,9 @@ public function actionDelete() * If the model is not found, a 404 HTTP exception will be thrown. * * - * @return the loaded model + * * @throws NotFoundHttpException if the model cannot be found + * @return the loaded model */ protected function findModel() { From 47bf6212e2b5fd33f9bcd8ba2e8ac3dd733e6600 Mon Sep 17 00:00:00 2001 From: Elias Luhr Date: Fri, 24 Mar 2023 23:17:47 +0100 Subject: [PATCH 21/45] added comment for model extended --- src/generators/model/default/model-extended.php | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/generators/model/default/model-extended.php b/src/generators/model/default/model-extended.php index 3e75e1e..cb2334c 100644 --- a/src/generators/model/default/model-extended.php +++ b/src/generators/model/default/model-extended.php @@ -24,13 +24,18 @@ */ class extends Base { - + /** + * @inheritdoc + */ public function behaviors() { $behaviors = parent::behaviors(); return $behaviors; } + /** + * @inheritdoc + */ public function rules() { $rules = parent::rules(); From 51972d618e0210654a1a7267039639be653d9744 Mon Sep 17 00:00:00 2001 From: Elias Luhr Date: Fri, 24 Mar 2023 23:26:31 +0100 Subject: [PATCH 22/45] className() is deprecated since 2.0.14 --- .../crud/callbacks/devgroup/Jsoneditor.php | 6 +- src/generators/crud/callbacks/dmstr/Pages.php | 6 +- .../crud/default/controller-rest.php | 2 +- src/generators/crud/default/controller.php | 2 +- src/generators/crud/default/views/_form.php | 2 +- src/generators/crud/default/views/create.php | 4 +- src/generators/crud/default/views/index.php | 4 +- src/generators/crud/default/views/update.php | 6 +- src/generators/crud/default/views/view.php | 2 +- .../crud/editable/controller-rest.php | 2 +- src/generators/crud/editable/controller.php | 60 +++++++++---------- src/generators/crud/editable/views/_form.php | 6 +- src/generators/crud/editable/views/create.php | 6 +- src/generators/crud/editable/views/index.php | 8 +-- src/generators/crud/editable/views/update.php | 6 +- src/generators/crud/editable/views/view.php | 28 ++++----- .../crud/providers/core/CallbackProvider.php | 4 +- .../crud/providers/core/OptsProvider.php | 2 +- .../crud/providers/core/RelationProvider.php | 6 +- .../providers/extensions/DateProvider.php | 2 +- .../providers/extensions/DateTimeProvider.php | 2 +- .../providers/extensions/EditorProvider.php | 10 ++-- .../extension/default/Bootstrap.php | 8 +-- src/generators/model/default/model.php | 6 +- 24 files changed, 96 insertions(+), 94 deletions(-) diff --git a/src/generators/crud/callbacks/devgroup/Jsoneditor.php b/src/generators/crud/callbacks/devgroup/Jsoneditor.php index 3568674..c0d3ace 100644 --- a/src/generators/crud/callbacks/devgroup/Jsoneditor.php +++ b/src/generators/crud/callbacks/devgroup/Jsoneditor.php @@ -12,8 +12,8 @@ class Jsoneditor public static function field() { return function ($attribute) { - $collapse = Collapse::className(); - $editor = \devgroup\jsoneditor\Jsoneditor::className(); + $collapse = Collapse::class; + $editor = \devgroup\jsoneditor\Jsoneditor::class; return <<'. @@ -39,7 +39,7 @@ public static function field() public static function attribute() { return function ($attribute, $generator) { - $formattter = StringFormatter::className(); + $formattter = StringFormatter::class; $method = __METHOD__; return <<field(\$model, 'request_param')->widget( - {$input}::className(), + {$input}::class, [ // single query fetch to render the tree 'query' => {$tree}::find()->addOrderBy('root, lft'), diff --git a/src/generators/crud/default/controller-rest.php b/src/generators/crud/default/controller-rest.php index 4fe1940..5a355c2 100644 --- a/src/generators/crud/default/controller-rest.php +++ b/src/generators/crud/default/controller-rest.php @@ -27,7 +27,7 @@ public function behaviors() parent::behaviors(), [ 'access' => [ - 'class' => AccessControl::className(), + 'class' => AccessControl::class, 'rules' => [ [ 'allow' => true, diff --git a/src/generators/crud/default/controller.php b/src/generators/crud/default/controller.php index 05f99c3..0188a9a 100644 --- a/src/generators/crud/default/controller.php +++ b/src/generators/crud/default/controller.php @@ -72,7 +72,7 @@ public function behaviors() { return [ 'access' => [ - 'class' => AccessControl::className(), + 'class' => AccessControl::class, 'rules' => [ $actions){ diff --git a/src/generators/crud/default/views/_form.php b/src/generators/crud/default/views/_form.php index 27d3507..b43f134 100644 --- a/src/generators/crud/default/views/_form.php +++ b/src/generators/crud/default/views/_form.php @@ -92,7 +92,7 @@ endBlock(); ?>'; ?> modelClass(); $model->setScenario('crud'); -$modelName = Inflector::camel2words(StringHelper::basename($model::className())); +$modelName = Inflector::camel2words(StringHelper::basename($model::class)); echo "setScenario('crud'); } -$baseName = StringHelper::basename($model::className()); +$baseName = StringHelper::basename($model::class); $modelName = Inflector::camel2words($baseName); $safeAttributes = $model->safeAttributes(); @@ -190,7 +190,7 @@ GridView::widget([ 'dataProvider' => $dataProvider, 'pager' => [ - 'class' => yii\widgets\LinkPager::className(), + 'class' => yii\widgets\LinkPager::class, 'firstPageLabel' => generateString('First') ?>, 'lastPageLabel' => generateString('Last').",\n" ?> ], diff --git a/src/generators/crud/default/views/update.php b/src/generators/crud/default/views/update.php index 3d52aa2..2a24d08 100644 --- a/src/generators/crud/default/views/update.php +++ b/src/generators/crud/default/views/update.php @@ -3,7 +3,7 @@ use yii\helpers\Inflector; use yii\helpers\StringHelper; -/* +/** * @var yii\web\View $this * @var yii\gii\generators\crud\Generator $generator */ @@ -11,8 +11,8 @@ $urlParams = $generator->generateUrlParams(); $model = new $generator->modelClass(); $model->setScenario('crud'); -$className = $model::className(); -$modelName = Inflector::camel2words(StringHelper::basename($model::className())); +$className = $model::class; +$modelName = Inflector::camel2words(StringHelper::basename($model::class)); echo " diff --git a/src/generators/crud/default/views/view.php b/src/generators/crud/default/views/view.php index 39eef38..19f4d3a 100644 --- a/src/generators/crud/default/views/view.php +++ b/src/generators/crud/default/views/view.php @@ -24,7 +24,7 @@ $safeAttributes = $model::getTableSchema()->columnNames; } -$className = $model::className(); +$className = $model::class; $modelName = Inflector::camel2words(StringHelper::basename($className)); $urlParams = $generator->generateUrlParams(); diff --git a/src/generators/crud/editable/controller-rest.php b/src/generators/crud/editable/controller-rest.php index 4fe1940..5a355c2 100644 --- a/src/generators/crud/editable/controller-rest.php +++ b/src/generators/crud/editable/controller-rest.php @@ -27,7 +27,7 @@ public function behaviors() parent::behaviors(), [ 'access' => [ - 'class' => AccessControl::className(), + 'class' => AccessControl::class, 'rules' => [ [ 'allow' => true, diff --git a/src/generators/crud/editable/controller.php b/src/generators/crud/editable/controller.php index 02ddd4e..9395a85 100644 --- a/src/generators/crud/editable/controller.php +++ b/src/generators/crud/editable/controller.php @@ -62,9 +62,9 @@ public function behaviors() { return [ 'access' => [ - 'class' => AccessControl::className(), + 'class' => AccessControl::class, 'rules' => [ - $actions){ ?> [ @@ -74,7 +74,7 @@ public function behaviors() ], 'roles' => [''], ], - ], ], @@ -85,12 +85,12 @@ public function behaviors() public function actions() { return [ 'editable-column-update' => [ - 'class' => EditableColumnAction::className(), // action class name - 'modelClass' => ::className(), + 'class' => EditableColumnAction::class, // action class name + 'modelClass' => ::class, ], ]; - } - + } + /** * Lists all models. * @return mixed @@ -101,13 +101,13 @@ public function actionIndex() ?> $searchModel = new ; $dataProvider = $searchModel->search($_GET); - $dataProvider = new ActiveDataProvider([ 'query' => ::find(), ]); - Url::remember(); @@ -139,7 +139,7 @@ public function actionView() /** * Creates a new model. - * If creation is successful, the browser will be redirected + * If creation is successful, the browser will be redirected * to the 'view' page or back, if parameter $goBack is true. * @return mixed */ @@ -148,12 +148,12 @@ public function actionCreate() $model = new ; $model->load($_GET); $relAttributes = $model->attributes; - + try { if ($model->load($_POST) && $model->save()) { if($relAttributes){ return $this->goBack(); - } + } return $this->redirect(['view', ]); } elseif (!\Yii::$app->request->isPost) { $model->load($_GET); @@ -162,13 +162,13 @@ public function actionCreate() $msg = (isset($e->errorInfo[2]))?$e->errorInfo[2]:$e->getMessage(); $model->addError('_exception', $msg); } - + return $this->render('create', [ 'model' => $model, - 'relAttributes' => $relAttributes, + 'relAttributes' => $relAttributes, ]); } - + /** * Add a new TestContacts record for relation grid and redirect back. * @return mixed @@ -181,7 +181,7 @@ public function actionCreateForRel() $model->save(); return $this->goBack(); } - + /** * Updates an existing model. * If update is successful, the browser will be redirected to the 'view' page. @@ -193,7 +193,7 @@ public function actionUpdate() $model = new ; $model->load($_GET); $relAttributes = $model->attributes; - + $model = $this->findModel(); if ($model->load($_POST) && $model->save()) { @@ -201,7 +201,7 @@ public function actionUpdate() } else { return $this->render('update', [ 'model' => $model, - 'relAttributes' => $relAttributes + 'relAttributes' => $relAttributes ]); } } @@ -224,11 +224,11 @@ public function actionDelete() $model = new ; $model->load($_GET); - $relAttributes = $model->attributes; + $relAttributes = $model->attributes; if($relAttributes){ return $this->redirect(Url::previous()); - } - + } + // TODO: improve detection $isPivot = strstr('',','); if ($isPivot == true) { @@ -248,23 +248,23 @@ public function actionDelete() * Update model record by editable. * * @return mixed - */ + */ public function actionEditable(){ - + // Check if there is an Editable ajax request if (!isset($_POST['hasEditable'])) { return false; } - + $post = []; foreach($_POST as $name => $value){ //if(in_array($name,$this->editAbleFileds)){ $post[$name] = $value; //} } - + // use Yii's response format to encode output as JSON - \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; + \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; if(!$post){ return ['output'=>'', 'message'=> generateString('Can not update this field') ?>]; } @@ -288,16 +288,16 @@ public function actionEditable(){ $errors = []; foreach($model->errors as $field => $messages){ foreach($messages as $message){ - $errors[] = $model->getAttributeLabel($field) + $errors[] = $model->getAttributeLabel($field) . ': ' . $message; } } return ['output'=>'', 'message'=>implode('
',$errors)]; - + } - - } + + } /** * Finds the model based on its primary key value. diff --git a/src/generators/crud/editable/views/_form.php b/src/generators/crud/editable/views/_form.php index 47ed8ea..27a8c01 100644 --- a/src/generators/crud/editable/views/_form.php +++ b/src/generators/crud/editable/views/_form.php @@ -27,7 +27,7 @@ * @var yii\web\View $this * @var modelClass, '\\') ?> $model * @var yii\widgets\ActiveForm $form -* @var string $relAttributes relation fields names for disabling +* @var string $relAttributes relation fields names for disabling */ ?> @@ -79,11 +79,11 @@ endBlock(); ?>'; ?> Yii::t('$generator->messageCategory', StringHelper::basename('{$model::className()}')), + 'label' => Yii::t('$generator->messageCategory', StringHelper::basename('{$model::class}')), 'content' => \$this->blocks['main'], 'active' => true, ], diff --git a/src/generators/crud/editable/views/create.php b/src/generators/crud/editable/views/create.php index 7383a65..782fae2 100644 --- a/src/generators/crud/editable/views/create.php +++ b/src/generators/crud/editable/views/create.php @@ -3,7 +3,7 @@ use yii\helpers\Inflector; use yii\helpers\StringHelper; -/* +/** * @var yii\web\View $this * @var yii\gii\generators\crud\Generator $generator */ @@ -11,7 +11,7 @@ /** @var \yii\db\ActiveRecord $model */ $model = new $generator->modelClass(); $model->setScenario('crud'); -$modelName = StringHelper::basename($model::className()); +$modelName = StringHelper::basename($model::class); echo "title = generateString('Create') ?>; -$this->params['breadcrumbs'][] = ['label' => Yii::t('messageCategory ?>', ''), 'url' => ['index']]; +$this->params['breadcrumbs'][] = ['label' => Yii::t('messageCategory ?>', ''), 'url' => ['index']]; $this->params['breadcrumbs'][] = $this->title; ?>
diff --git a/src/generators/crud/editable/views/index.php b/src/generators/crud/editable/views/index.php index 382b21b..1911289 100644 --- a/src/generators/crud/editable/views/index.php +++ b/src/generators/crud/editable/views/index.php @@ -15,7 +15,7 @@ $model = new $generator->modelClass(); $model->setScenario('crud'); -$modelName = Inflector::pluralize(StringHelper::basename($model::className())); +$modelName = Inflector::pluralize(StringHelper::basename($model::class)); $safeAttributes = $model->safeAttributes(); if (empty($safeAttributes)) { @@ -56,7 +56,7 @@ */ $actionColumnTemplates = []; -if (\Yii::$app->user->can('')) { +if (\Yii::$app->user->can('')) { $actionColumnTemplates[] = '{view}'; } @@ -102,7 +102,7 @@

accessFilter){ +if($generator->accessFilter){ echo " if(\Yii::$app->user->can('')){ @@ -187,7 +187,7 @@ 'layout' => '{summary}{pager}{items}{pager}', 'dataProvider' => $dataProvider, 'pager' => [ - 'class' => yii\widgets\LinkPager::className(), + 'class' => yii\widgets\LinkPager::class, 'firstPageLabel' => generateString('First') ?>, 'lastPageLabel' => generateString('Last') ?> ], diff --git a/src/generators/crud/editable/views/update.php b/src/generators/crud/editable/views/update.php index 93d8fed..e4116df 100644 --- a/src/generators/crud/editable/views/update.php +++ b/src/generators/crud/editable/views/update.php @@ -3,7 +3,7 @@ use yii\helpers\Inflector; use yii\helpers\StringHelper; -/* +/** * @var yii\web\View $this * @var yii\gii\generators\crud\Generator $generator */ @@ -11,8 +11,8 @@ $urlParams = $generator->generateUrlParams(); $model = new $generator->modelClass(); $model->setScenario('crud'); -$className = $model::className(); -$modelName = StringHelper::basename($model::className()); +$className = $model::class; +$modelName = StringHelper::basename($model::class); echo " diff --git a/src/generators/crud/editable/views/view.php b/src/generators/crud/editable/views/view.php index a21ad79..1f785fd 100644 --- a/src/generators/crud/editable/views/view.php +++ b/src/generators/crud/editable/views/view.php @@ -3,7 +3,7 @@ use yii\helpers\Inflector; use yii\helpers\StringHelper; -/* +/** * @var yii\web\View $this * @var schmunk42\giiant\generators\crud\Generator $generator */ @@ -11,9 +11,9 @@ /** @var \yii\db\ActiveRecord $model */ $model = new $generator->modelClass(); $model->setScenario('crud'); -$modelName = StringHelper::basename($model::className()); +$modelName = StringHelper::basename($model::class); -$className = $model::className(); +$className = $model::class; $safeAttributes = $model->safeAttributes(); if (empty($safeAttributes)) { @@ -104,12 +104,12 @@ 'attributes' => [ isPrimaryKey([$attribute])){ continue; - } - + } + $format = $generator->attributeEditable($attribute); if (!$format) { continue; @@ -156,10 +156,10 @@ $pjaxId = "pjax-{$name}"; $gridRelation = $relation; $gridName = $name; - } - - $gridModel = new $gridRelation->modelClass(); - + } + + $gridModel = new $gridRelation->modelClass(); + $showAllRecords = false; if ($relation->via !== null) { @@ -181,7 +181,7 @@ } // HEADER, relation list, add, create buttons - $headerLabel = Inflector::camel2words($name); + $headerLabel = Inflector::camel2words($name); echo "
@@ -218,7 +218,7 @@ // render relation grid if (!empty($output)): echo "'pjax-{$name}', 'enableReplaceState'=> false, 'linkSelector'=>'#pjax-{$name} ul.pagination a, th a', 'clientOptions' => ['pjax:success'=>'function(){alert(\"yo\")}']]) ?>\n"; - echo '
'.PHP_EOL; + echo '
'.PHP_EOL; echo ' \n"; echo '
'.PHP_EOL; echo "\n"; @@ -235,7 +235,7 @@
=$this->blocks['modelClass?>']?>
-
@@ -244,5 +244,5 @@ -
+
diff --git a/src/generators/crud/providers/core/CallbackProvider.php b/src/generators/crud/providers/core/CallbackProvider.php index f69c576..0899e74 100755 --- a/src/generators/crud/providers/core/CallbackProvider.php +++ b/src/generators/crud/providers/core/CallbackProvider.php @@ -7,6 +7,8 @@ */ namespace schmunk42\giiant\generators\crud\providers\core; +use yii\base\BaseObject; + class CallbackProvider extends \schmunk42\giiant\base\Provider { public $activeFields = []; @@ -66,7 +68,7 @@ public function partialView($name, $model, $generator) private function getModelKey($attribute, $model) { - return $model::className().'.'.$attribute; + return $model::className() . '.' . $attribute; } private function findValue($subject, $array) diff --git a/src/generators/crud/providers/core/OptsProvider.php b/src/generators/crud/providers/core/OptsProvider.php index 3ce3091..a34d13d 100644 --- a/src/generators/crud/providers/core/OptsProvider.php +++ b/src/generators/crud/providers/core/OptsProvider.php @@ -42,7 +42,7 @@ public function activeField($attribute) case 'select2': return <<field(\$model, '{$attribute}')->widget(\kartik\select2\Select2::classname(), [ + \$form->field(\$model, '{$attribute}')->widget(\kartik\select2\Select2::class, [ 'name' => 'class_name', 'model' => \$model, 'attribute' => '{$attribute}', diff --git a/src/generators/crud/providers/core/RelationProvider.php b/src/generators/crud/providers/core/RelationProvider.php index d7fca36..d3e5bb0 100644 --- a/src/generators/crud/providers/core/RelationProvider.php +++ b/src/generators/crud/providers/core/RelationProvider.php @@ -67,7 +67,7 @@ public function activeField($attribute) case 'select2': $code = <<field(\$model, '{$column->name}')->widget(\kartik\select2\Select2::classname(), [ +\$form->field(\$model, '{$column->name}')->widget(\kartik\select2\Select2::class, [ 'name' => 'class_name', 'model' => \$model, 'attribute' => '{$column->name}', @@ -244,7 +244,7 @@ public function columnFormat($attribute, $model) $code = << yii\\grid\\DataColumn::className(), + 'class' => yii\\grid\\DataColumn::class, 'attribute' => '{$column->name}', 'value' => function (\$model) { if (\$rel = \$model->{$relationProperty}) { @@ -397,7 +397,7 @@ public function relationGrid($name, $relation, $showAllRecords = false) ] ]), 'pager' => [ - 'class' => yii\widgets\LinkPager::className(), + 'class' => yii\widgets\LinkPager::class, 'firstPageLabel' => {$firstPageLabel}, 'lastPageLabel' => {$lastPageLabel} ], diff --git a/src/generators/crud/providers/extensions/DateProvider.php b/src/generators/crud/providers/extensions/DateProvider.php index 51651eb..583ac54 100644 --- a/src/generators/crud/providers/extensions/DateProvider.php +++ b/src/generators/crud/providers/extensions/DateProvider.php @@ -17,7 +17,7 @@ public function activeField($attribute) $this->generator->requires[] = 'zhuravljov/yii2-datetime-widgets'; return <<field(\$model, '{$column->name}')->widget(\zhuravljov\widgets\DatePicker::className(), [ +\$form->field(\$model, '{$column->name}')->widget(\zhuravljov\widgets\DatePicker::class, [ 'options' => ['class' => 'form-control'], 'clientOptions' => [ 'autoclose' => true, diff --git a/src/generators/crud/providers/extensions/DateTimeProvider.php b/src/generators/crud/providers/extensions/DateTimeProvider.php index c3a8284..c82c773 100644 --- a/src/generators/crud/providers/extensions/DateTimeProvider.php +++ b/src/generators/crud/providers/extensions/DateTimeProvider.php @@ -11,7 +11,7 @@ public function activeField($attribute) $this->generator->requires[] = 'zhuravljov/yii2-datetime-widgets'; return <<field(\$model, '{$attribute}')->widget(\zhuravljov\widgets\DateTimePicker::className(), [ +\$form->field(\$model, '{$attribute}')->widget(\zhuravljov\widgets\DateTimePicker::class, [ 'options' => ['class' => 'form-control'], 'clientOptions' => [ 'autoclose' => true, diff --git a/src/generators/crud/providers/extensions/EditorProvider.php b/src/generators/crud/providers/extensions/EditorProvider.php index fec59a0..1875ca3 100644 --- a/src/generators/crud/providers/extensions/EditorProvider.php +++ b/src/generators/crud/providers/extensions/EditorProvider.php @@ -29,29 +29,29 @@ public function activeField($attribute) case 'redactor': $this->generator->requires[] = 'yiidoc/yii2-redactor'; - return "\$form->field(\$model, '{$attribute}')->widget(\\yii\\redactor\\widgets\\Redactor::className())"; + return "\$form->field(\$model, '{$attribute}')->widget(\\yii\\redactor\\widgets\\Redactor::class)"; break; case 'aceHTML': $this->generator->requires[] = 'trntv/aceeditor'; - return "\$form->field(\$model, '{$attribute}')->widget(\\trntv\\aceeditor\\AceEditor::className(), ['mode' => 'html', 'theme' => 'twilight'])"; + return "\$form->field(\$model, '{$attribute}')->widget(\\trntv\\aceeditor\\AceEditor::class, ['mode' => 'html', 'theme' => 'twilight'])"; break; case 'aceLESS': $this->generator->requires[] = 'trntv/aceeditor'; - return "\$form->field(\$model, '{$attribute}')->widget(\\trntv\\aceeditor\\AceEditor::className(), ['mode' => 'less', 'theme' => 'twilight'])"; + return "\$form->field(\$model, '{$attribute}')->widget(\\trntv\\aceeditor\\AceEditor::class, ['mode' => 'less', 'theme' => 'twilight'])"; break; case 'aceJS': $this->generator->requires[] = 'trntv/aceeditor'; - return "\$form->field(\$model, '{$attribute}')->widget(\\trntv\\aceeditor\\AceEditor::className(), ['mode' => 'javascript', 'theme' => 'twilight'])"; + return "\$form->field(\$model, '{$attribute}')->widget(\\trntv\\aceeditor\\AceEditor::class, ['mode' => 'javascript', 'theme' => 'twilight'])"; break; default: $this->generator->requires[] = '2amigos/yii2-ckeditor-widget'; return <<field(\$model, '{$attribute}')->widget( - \dosamigos\ckeditor\CKEditor::className(), + \dosamigos\ckeditor\CKEditor::class, [ 'options' => ['rows' => 6], 'preset' => 'basic' diff --git a/src/generators/extension/default/Bootstrap.php b/src/generators/extension/default/Bootstrap.php index 7054e2a..7cbeb80 100644 --- a/src/generators/extension/default/Bootstrap.php +++ b/src/generators/extension/default/Bootstrap.php @@ -11,19 +11,19 @@ class Bootstrap implements BootstrapInterface { /** @inheritdoc */ public function bootstrap($app) { -enableI18N){ -?> +?> if (!isset($app->get('i18n')->translations['messageCategory ?>*'])) { $app->get('i18n')->translations['messageCategory ?>*'] = [ - 'class' => PhpMessageSource::className(), + 'class' => PhpMessageSource::class, 'basePath' => __DIR__ . '/messages', 'sourceLanguage' => 'en-US' ]; } +?> } } diff --git a/src/generators/model/default/model.php b/src/generators/model/default/model.php index b94bdd6..b041eae 100644 --- a/src/generators/model/default/model.php +++ b/src/generators/model/default/model.php @@ -104,7 +104,7 @@ public function behaviors() return ArrayHelper::merge(parent::behaviors(), [ [ - 'class' => BlameableBehavior::className(), + 'class' => BlameableBehavior::class, 'createdByAttribute' => , @@ -115,7 +115,7 @@ public function behaviors() [ - 'class' => TimestampBehavior::className(), + 'class' => TimestampBehavior::class, 'createdAtAttribute' => , @@ -126,7 +126,7 @@ public function behaviors() 'translatable' => [ - 'class' => TranslateableBehavior::className(), + 'class' => TranslateableBehavior::class, // in case you renamed your relation, you can setup its name // 'relation' => 'translations', languageCodeColumn !== 'language'): ?> From 059de44583bdc7a5d807c3a4a06f67ea90fa3e4c Mon Sep 17 00:00:00 2001 From: Elias Luhr Date: Sat, 25 Mar 2023 00:25:25 +0100 Subject: [PATCH 23/45] adapt changes from other experiences --- src/commands/BatchController.php | 6 +- src/generators/crud/Generator.php | 101 ++++++++++- src/generators/crud/default/search.php | 16 +- .../crud/default/views/_form-fields.php | 36 ++++ src/generators/crud/default/views/_form.php | 47 +---- src/generators/crud/default/views/_search.php | 4 +- src/generators/crud/default/views/view.php | 2 +- src/generators/model/Generator.php | 93 +++++++++- src/generators/model/default/model.php | 164 ++++++++++++++---- 9 files changed, 379 insertions(+), 90 deletions(-) create mode 100644 src/generators/crud/default/views/_form-fields.php diff --git a/src/commands/BatchController.php b/src/commands/BatchController.php index c3a3177..a882bf5 100644 --- a/src/commands/BatchController.php +++ b/src/commands/BatchController.php @@ -310,13 +310,15 @@ class BatchController extends Controller */ public $modelGenerateRelationsFromCurrentSchema = true; + public $modelTranslationTableAdditions = ['name' => 'meta', 'fallbackLanguage' => false]; + /** * @var array application configuration for creating temporary applications */ protected $appConfig; /** - * @var instance of class schmunk42\giiant\generators\model\Generator + * @var \schmunk42\giiant\generators\model\Generator instance of class schmunk42\giiant\generators\model\Generator */ protected $modelGenerator; @@ -357,6 +359,7 @@ public function options($id) 'modelCacheRelationsData', 'modelGenerateRelations', 'modelGenerateRelationsFromCurrentSchema', + 'modelTranslationTableAdditions', 'modelGenerateJunctionRelationMode', 'modelGenerateQuery', 'modelQueryNamespace', @@ -477,6 +480,7 @@ public function actionModels() 'cacheRelationsData' => $this->modelCacheRelationsData, 'generateRelations' => $this->modelGenerateRelations, 'generateRelationsFromCurrentSchema' => $this->modelGenerateRelationsFromCurrentSchema, + 'translationTableAdditions' => $this->modelTranslationTableAdditions, 'generateJunctionRelationMode' => $this->modelGenerateJunctionRelationMode, 'tableNameMap' => $this->tableNameMap, 'generateQuery' => $this->modelGenerateQuery, diff --git a/src/generators/crud/Generator.php b/src/generators/crud/Generator.php index f1f6181..aa3944e 100644 --- a/src/generators/crud/Generator.php +++ b/src/generators/crud/Generator.php @@ -163,6 +163,8 @@ class Generator extends \yii\gii\generators\crud\Generator private $_p = []; + public $translateRelations = ['translation', 'translation_meta']; + /** * {@inheritdoc} */ @@ -370,12 +372,31 @@ public function generate() $viewPath = $this->getViewPath(); $templatePath = $this->getTemplatePath().'/views'; + $model = Yii::createObject($this->modelClass); + if (array_key_exists('crud-form', $model->scenarios())) { + $model->setScenario('crud-form'); + } else { + $model->setScenario('crud'); + } + + $safeAttributes = $model->safeAttributes(); + if (empty($safeAttributes)) { + $model->setScenario('default'); + $safeAttributes = $model->safeAttributes(); + } + if (empty($safeAttributes)) { + $safeAttributes = $model::getTableSchema()->columnNames; + } + foreach (scandir($templatePath) as $file) { if (empty($this->searchModelClass) && $file === '_search.php') { continue; } if (is_file($templatePath.'/'.$file) && pathinfo($file, PATHINFO_EXTENSION) === 'php') { - $files[] = new CodeFile("$viewPath/$file", $this->render("views/$file", ['permisions' => $permisions])); + $files[] = new CodeFile("$viewPath/$file", $this->render("views/$file", [ + 'model' => $model, + 'safeAttributes' => $safeAttributes + ])); } } @@ -467,4 +488,82 @@ public function var_export54($var, $indent = '') return var_export($var, true); } } + + /** + * @return array + * @throws \yii\base\InvalidConfigException + */ + public function generateSearchRules() + { + + $rules = parent::generateSearchRules(); + $model = \Yii::createObject($this->modelClass); + foreach ($model->behaviors() as $key => $behavior) { + if (!empty($behavior['translationAttributes'])) { + $rules[] = "[['" . implode("', '", $behavior['translationAttributes']) . "'], 'safe']"; + } + } + return $rules; + } + + /** + * @return array + * @throws \yii\base\InvalidConfigException + */ + public function generateSearchConditions() + { + + $searchConditions = parent::generateSearchConditions(); + $model = \Yii::createObject($this->modelClass); + foreach ($model->behaviors() as $key => $behavior) { + if (!empty($behavior['translationAttributes'])) { + foreach ($behavior['translationAttributes'] as $translationAttribute) { + $searchConditions[] = "\$query->andFilterWhere(['like','{$translationAttribute}', \$this->$translationAttribute]);"; + } + } + } + return $searchConditions; + } + + + /** + * @return array + */ + public function getTranslationRelationModels() + { + $translationRelationModels = []; + foreach ($this->translateRelations as $translateRelation) { + $translationRelationModels[] = $this->modelClass . Inflector::camelize($translateRelation); + } + return $translationRelationModels; + } + + /** + * @return string + */ + public function getTranslationModelClass() { + return '\\' . $this->modelClass . Inflector::camelize('translation'); + } + /** + * @return string + */ + public function getTranslationMetaModelClass() { + return '\\' . $this->modelClass . Inflector::camelize('translation_meta'); + } + + /** + * @return bool + * @throws \yii\base\InvalidConfigException + */ + public function getHasTranslationRelation() { + return isset(\Yii::createObject($this->modelClass)->behaviors()['translation']); + } + + /** + * @return bool + * @throws \yii\base\InvalidConfigException + */ + public function getHasTranslationMetaRelation() { + return isset(\Yii::createObject($this->modelClass)->behaviors()['translation_meta']); + } } diff --git a/src/generators/crud/default/search.php b/src/generators/crud/default/search.php index 441df99..36f56f0 100644 --- a/src/generators/crud/default/search.php +++ b/src/generators/crud/default/search.php @@ -61,7 +61,16 @@ public function scenarios() */ public function search($params) { -$query = ::find(); +$query = ::find(); + +hasTranslationRelation): ?> + $query->leftJoin(translationModelClass?>::tableName(),::tableName() . '.id = ' . translationModelClass?>::tableName() . '._id'); + + +hasTranslationMetaRelation): ?> + $query->leftJoin(translationMetaModelClass?>::tableName(),::tableName() . '.id = ' . translationMetaModelClass?>::tableName() . '._id'); + + $dataProvider = new ActiveDataProvider([ 'query' => $query, @@ -74,9 +83,12 @@ public function search($params) // $query->where('0=1'); return $dataProvider; } +hasTranslationRelation): ?> + $query->groupBy(::tableName() . '.id'); + return $dataProvider; } -} \ No newline at end of file +} diff --git a/src/generators/crud/default/views/_form-fields.php b/src/generators/crud/default/views/_form-fields.php new file mode 100644 index 0000000..11fcf69 --- /dev/null +++ b/src/generators/crud/default/views/_form-fields.php @@ -0,0 +1,36 @@ + +/** + * @var yii\web\View $this + * @var modelClass, '\\') ?> $model + * @var yii\widgets\ActiveForm $form + */ + +?> +\n"; + $prepend = $generator->prependActiveField($attribute, $model); + $field = $generator->activeField($attribute, $model); + $append = $generator->appendActiveField($attribute, $model); + + if ($prepend) { + echo $prepend; + } + if ($field) { + echo "'; + } + if ($append) { + echo $append; + } +} diff --git a/src/generators/crud/default/views/_form.php b/src/generators/crud/default/views/_form.php index b43f134..300a667 100644 --- a/src/generators/crud/default/views/_form.php +++ b/src/generators/crud/default/views/_form.php @@ -5,31 +5,16 @@ /** * @var yii\web\View $this * @var yii\gii\generators\crud\Generator $generator + * @var \yii\db\ActiveRecord $model + * @var array $safeAttributes */ -/** @var \yii\db\ActiveRecord $model */ -## TODO: move to generator (?); cleanup -$model = new $generator->modelClass(); -if (array_key_exists('crud-form', $model->scenarios())) { - $model->setScenario('crud-form'); -} else { - $model->setScenario('crud'); -} -$safeAttributes = $model->safeAttributes(); -if (empty($safeAttributes)) { - $model->setScenario('default'); - $safeAttributes = $model->safeAttributes(); -} -if (empty($safeAttributes)) { - $safeAttributes = $model::getTableSchema()->columnNames; -} - echo " use yii\helpers\Html; use yii\bootstrap\ActiveForm; -use \dmstr\bootstrap\Tabs; +use yii\bootstrap\Tabs; use yii\helpers\StringHelper; /** @@ -55,7 +40,6 @@ 'template' => "{label}\n{beginWrapper}\n{input}\n{hint}\n{error}\n{endWrapper}", 'horizontalCssClasses' => [ 'label' => 'col-sm-2', - #'offset' => 'col-sm-offset-4', 'wrapper' => 'col-sm-8', 'error' => '', 'hint' => '', @@ -67,28 +51,9 @@
beginBlock('main'); ?>\n"; ?> - -

- "; - $prepend = $generator->prependActiveField($attribute, $model); - $field = $generator->activeField($attribute, $model); - $append = $generator->appendActiveField($attribute, $model); - - if ($prepend) { - echo "\n\t\t\t".$prepend; - } - if ($field) { - echo "\n\t\t\t'; - } - if ($append) { - echo "\n\t\t\t".$append; - } - } - ?> - -

+
+ render('_form-fields', ['form' => \$form, 'model' => \$model])?>\n"?> +
endBlock(); ?>'; ?> getTableSchema()->getColumnNames() as $attribute) { if (++$count < 6) { - echo "\t\tgenerateActiveSearchField($attribute)." ?>\n\n"; + echo "\t\tgenerateActiveSearchField($attribute)." ?>\n\n"; } else { echo "\t\tgenerateActiveSearchField($attribute)." ?>\n\n"; } diff --git a/src/generators/crud/default/views/view.php b/src/generators/crud/default/views/view.php index 19f4d3a..c9f4e59 100644 --- a/src/generators/crud/default/views/view.php +++ b/src/generators/crud/default/views/view.php @@ -36,7 +36,7 @@ use yii\grid\GridView; use yii\widgets\DetailView; use yii\widgets\Pjax; -use dmstr\bootstrap\Tabs; +use yii\bootstrap\Tabs; /** * @var yii\web\View $this diff --git a/src/generators/model/Generator.php b/src/generators/model/Generator.php index c0aafa2..2f3abf3 100644 --- a/src/generators/model/Generator.php +++ b/src/generators/model/Generator.php @@ -138,6 +138,24 @@ class Generator extends \yii\gii\generators\model\Generator protected static $_relationsCache = null; + /** + * the names given here are used as suffixes to the base_translation table name, eg. + * + * $languageTableName = '{table}_translation'; + * $translationTableAdditions = ['meta']; + * + * will process {table}_translation AND {table}_translation_meta + * + * to be able to set the 'fallbackLanguage' flag fot the behaviour of this translation, items can be arrays like: + * + * $translationTableAdditions = ['name' => 'meta', 'fallbackLanguage' => false] + * + * if fallbackLanguage is not specified, 'true' is used as default + * + * @var array af additional translation tables + */ + public $translationTableAdditions = ['name' => 'meta', 'fallbackLanguage' => false]; + /** * {@inheritdoc} */ @@ -627,10 +645,10 @@ protected function getDbConnection() public function validateDb() { if (Yii::$container->has($this->db)) { - return true; - } else { - return parent::validateDb(); + return; } + + parent::validateDb(); } /** @@ -642,11 +660,65 @@ public function getTableNames() } /** - * @param $relations all database's relations + * @return array associative array containing the extracted relations and the modified translations (from parent) + translations_meta fields if exists + */ + protected function extractTranslations($tableName, $relations) { + + $translations = [ + 'relations' => $relations, + 'translations' => [], + ]; + + # check if we have base translations + $baseTranslations = $this->extractBaseTranslations($tableName, $relations); + // we do not want timestamp columns as translatable fields + $unsetFields = [$this->createdAtColumn, $this->updatedAtColumn, $this->createdByColumn, $this->updatedByColumn]; + if (!empty($baseTranslations['translations']['fields'])) { + $translations = $baseTranslations; + $translations['translations']['fields'] = array_diff($baseTranslations['translations']['fields'], $unsetFields); + } + + $baseLanguageTableName = $this->languageTableName; + foreach ($this->translationTableAdditions as $addition) { + + if (is_array($addition)) { + $additionName = $addition['name']; + $additionFallbackLanguage = $addition['fallbackLanguage'] ?? true; + } else { + $additionName = $addition; + $additionFallbackLanguage = true; + } + + # in the following runs we must use possibly modified relations from previous extractTranslations() call + $prevRelations = $translations['relations']; + # to be able to reuse extractTranslations() set $this->languageTableName for one method call + $this->languageTableName .= '_' . $additionName; + # here we must use possibly modified relations from previous extractTranslations() call + $additionTranslations = $this->extractBaseTranslations($tableName, $prevRelations); + + # if we get meta-translations fields, overwrite relations, + # otherwise we get the relation as TranslationMetas and translationMetas + if (!empty($additionTranslations['translations']['fields'])) { + $translations['relations'] = $additionTranslations['relations']; + $translations['translations']['additions'][$additionName]['fields'] = array_diff($additionTranslations['translations']['fields'], $unsetFields); + $translations['translations']['additions'][$additionName]['code'] = $additionTranslations['translations']['code']; + # set flag if this addition should use the fallback language feature + $translations['translations']['additions'][$additionName]['fallbackLanguage'] = $additionFallbackLanguage; + } + # reset languageTableName to default value (without prefix) + $this->languageTableName = $baseLanguageTableName; + } + + return $translations; + + } + + /** + * @param array $relations All database's relations * * @return array associative array containing the extracted relations and the modified translations */ - protected function extractTranslations($tableName, $relations) + protected function extractBaseTranslations($tableName, $relations) { $langTableName = str_replace('{{table}}', $tableName, $this->languageTableName); @@ -734,7 +806,18 @@ protected function generateTimestamp($table) $createdAt = $table->getColumn($this->createdAtColumn) !== null ? $this->createdAtColumn : false; $updatedAt = $table->getColumn($this->updatedAtColumn) !== null ? $this->updatedAtColumn : false; + #var_dump($table->getColumn($this->createdAtColumn)); exit; if ($this->useTimestampBehavior && ($createdAt || $updatedAt)) { + // check column type, if datetime set NOW() as Value + if ($table->getColumn($this->createdAtColumn)->type === 'datetime') { + return [ + 'value' => 'new \yii\db\Expression(\'NOW()\')', + 'createdAtAttribute' => $createdAt, + 'updatedAtAttribute' => $updatedAt, + 'timestampBehaviorClass' => $this->timestampBehaviorClass, + ]; + + } return [ 'createdAtAttribute' => $createdAt, 'updatedAtAttribute' => $updatedAt, diff --git a/src/generators/model/default/model.php b/src/generators/model/default/model.php index b041eae..fcb5962 100644 --- a/src/generators/model/default/model.php +++ b/src/generators/model/default/model.php @@ -19,6 +19,9 @@ * @var array $relations list of relations (name => relation declaration) */ +$activeRecordClass = '\\' . ltrim($generator->baseClass, '\\'); +$translationExists = false; + echo " // This class was automatically generated by a giiant build task @@ -54,7 +57,7 @@ */ -abstract class extends baseClass, '\\') . "\n" ?> +abstract class extends { baseTraits; @@ -101,43 +104,80 @@ public static function getDb() */ public function behaviors() { - return ArrayHelper::merge(parent::behaviors(), [ - - [ - 'class' => BlameableBehavior::class, - - 'createdByAttribute' => , - - - 'updatedByAttribute' => , - - ], - - - [ - 'class' => TimestampBehavior::class, - - 'createdAtAttribute' => , - - - 'updatedAtAttribute' => , - - ], - - - 'translatable' => [ - 'class' => TranslateableBehavior::class, - // in case you renamed your relation, you can setup its name - // 'relation' => 'translations', -languageCodeColumn !== 'language'): ?> + $behaviors = parent::behaviors(); + + $behaviors['blameable'] = [ + 'class' => BlameableBehavior::class, + + 'createdByAttribute' => , + + + 'updatedByAttribute' => , + + ]; + + + $behaviors['timestamp'] = [ + 'class' => TimestampBehavior::class, + + 'value' => , + + + 'createdAtAttribute' => , + + + 'updatedAtAttribute' => , + + ]; + + + + + $behaviors['translation'] = [ + 'class' => TranslateableBehavior::class, + // in case you renamed your relation, you can setup its name + // 'relation' => 'translations', + languageCodeColumn !== 'language'): ?> 'languageField' => 'languageCodeColumn ?>', - - 'translationAttributes' => [ - - ], + + 'skipSavingDuplicateTranslation' => true, + 'translationAttributes' => [ + ], - - ]); + 'deleteEvent' => ::EVENT_BEFORE_DELETE, + 'restrictDeletion' => TranslateableBehavior::DELETE_LAST + ]; + + + + $values): ?> + + + $behaviors['translation_'] = [ + 'class' => TranslateableBehavior::class, + 'relation' => 'translations', + languageCodeColumn !== 'language'): ?> + 'languageField' => 'languageCodeColumn ?>', + + + // This is not a boolean parameter it only sets the fallbackLanguage to an invalid value! + 'fallbackLanguage' => false, + 'skipSavingDuplicateTranslation' => false, + + 'skipSavingDuplicateTranslation' => true, + + 'translationAttributes' => [ + + ], + 'deleteEvent' => ::EVENT_BEFORE_DELETE + ]; + + + + + + + return $behaviors; } @@ -146,7 +186,11 @@ public function behaviors() */ public function rules() { - return ArrayHelper::merge(parent::rules(), []); + $parentRules = parent::rules(); + + $parentRules += $this->importTranslationAttributeRules(); + + return ArrayHelper::merge($parentRules, []); } /** @@ -194,6 +238,52 @@ public function getTranslations() } + + $values): ?> + + /** + * @return \yii\db\ActiveQuery + */ + public function getTranslations() + { + + } + + + + + + /** + * get validation rules from translation* relationModels + * @return array + */ + protected function importTranslationAttributeRules() { + + $rules = []; + + foreach ($this->getBehaviors() as $key => $behavoir) { + + if ($behavoir instanceof TranslateableBehavior) { + + $translationModelClass = $this->getRelation($behavoir->relation)->modelClass; + $importRules = (new $translationModelClass)->rules(); + foreach ($importRules as $rule) { + foreach ((array)$rule[0] as $rule_key => $attribute) { + if (!in_array($attribute, $behavoir->translationAttributes, true)) { + unset ($rule[0][$rule_key]); + } + } + if (!empty($rule[0])) { + $rules[] = $rule; + } + } + } + } + + return $rules; + } + + /** From 9cdfdeb73270351048a4c7cd108d13c3e9ef1eaa Mon Sep 17 00:00:00 2001 From: Elias Luhr Date: Sat, 25 Mar 2023 00:44:02 +0100 Subject: [PATCH 24/45] render searchfile only when needed --- src/generators/crud/Generator.php | 21 +++++---- src/generators/crud/default/views/_search.php | 2 +- src/generators/crud/default/views/index.php | 45 +++++++++---------- 3 files changed, 35 insertions(+), 33 deletions(-) diff --git a/src/generators/crud/Generator.php b/src/generators/crud/Generator.php index aa3944e..39c9166 100644 --- a/src/generators/crud/Generator.php +++ b/src/generators/crud/Generator.php @@ -312,20 +312,20 @@ public function getControllerID() public function getModuleId() { if (!$this->moduleNs) { - $controllerNs = \yii\helpers\StringHelper::dirname(ltrim($this->controllerClass, '\\')); - $this->moduleNs = \yii\helpers\StringHelper::dirname(ltrim($controllerNs, '\\')); + $controllerNs = StringHelper::dirname(ltrim($this->controllerClass, '\\')); + $this->moduleNs = StringHelper::dirname(ltrim($controllerNs, '\\')); } - return \yii\helpers\StringHelper::basename($this->moduleNs); + return StringHelper::basename($this->moduleNs); } public function generate() { $accessDefinitions = require $this->getTemplatePath().'/access_definition.php'; - $this->controllerNs = \yii\helpers\StringHelper::dirname(ltrim($this->controllerClass, '\\')); - $this->moduleNs = \yii\helpers\StringHelper::dirname(ltrim($this->controllerNs, '\\')); - $controllerName = substr(\yii\helpers\StringHelper::basename($this->controllerClass), 0, -10); + $this->controllerNs = StringHelper::dirname(ltrim($this->controllerClass, '\\')); + $this->moduleNs = StringHelper::dirname(ltrim($this->controllerNs, '\\')); + $controllerName = substr(StringHelper::basename($this->controllerClass), 0, -10); if ($this->singularEntities) { $this->modelClass = Inflector::singularize($this->modelClass); @@ -352,7 +352,7 @@ public function generate() } $files[] = new CodeFile($baseControllerFile, $this->render('controller.php', ['accessDefinitions' => $accessDefinitions])); - $params['controllerClassName'] = \yii\helpers\StringHelper::basename($this->controllerClass); + $params['controllerClassName'] = StringHelper::basename($this->controllerClass); if ($this->overwriteControllerClass || !is_file($controllerFile)) { $files[] = new CodeFile($controllerFile, $this->render('controller-extended.php', $params)); @@ -389,7 +389,7 @@ public function generate() } foreach (scandir($templatePath) as $file) { - if (empty($this->searchModelClass) && $file === '_search.php') { + if ($file === '_search.php' && !$this->getRenderWithSearch()) { continue; } if (is_file($templatePath.'/'.$file) && pathinfo($file, PATHINFO_EXTENSION) === 'php') { @@ -566,4 +566,9 @@ public function getHasTranslationRelation() { public function getHasTranslationMetaRelation() { return isset(\Yii::createObject($this->modelClass)->behaviors()['translation_meta']); } + + public function getRenderWithSearch() + { + return $this->indexWidgetType !== 'grid' && $this->searchModelClass !== ''; + } } diff --git a/src/generators/crud/default/views/_search.php b/src/generators/crud/default/views/_search.php index 80ff181..c827c4e 100644 --- a/src/generators/crud/default/views/_search.php +++ b/src/generators/crud/default/views/_search.php @@ -32,7 +32,7 @@ $count = 0; foreach ($generator->getTableSchema()->getColumnNames() as $attribute) { if (++$count < 6) { - echo "\t\tgenerateActiveSearchField($attribute)." ?>\n\n"; + echo "\t\tgenerateActiveSearchField($attribute)." ?>\n\n"; } else { echo "\t\tgenerateActiveSearchField($attribute)." ?>\n\n"; } diff --git a/src/generators/crud/default/views/index.php b/src/generators/crud/default/views/index.php index 8097a2c..0153057 100644 --- a/src/generators/crud/default/views/index.php +++ b/src/generators/crud/default/views/index.php @@ -23,15 +23,15 @@ $baseName = StringHelper::basename($model::class); $modelName = Inflector::camel2words($baseName); -$safeAttributes = $model->safeAttributes(); -if (empty($safeAttributes)) { - /** @var \yii\db\ActiveRecord $model */ - $model = new $generator->modelClass(); - $safeAttributes = $model->safeAttributes(); - if (empty($safeAttributes)) { - $safeAttributes = $model::getTableSchema()->columnNames; - } -} +//$safeAttributes = $model->safeAttributes(); +//if (empty($safeAttributes)) { +// /** @var \yii\db\ActiveRecord $model */ +// $model = new $generator->modelClass(); +// $safeAttributes = $model->safeAttributes(); +// if (empty($safeAttributes)) { +// $safeAttributes = $model::getTableSchema()->columnNames; +// } +//} echo " @@ -56,7 +56,7 @@ ?> /** -* create action column template depending acces rights +* create action column template depending on user's access rights */ $actionColumnTemplates = []; @@ -88,12 +88,9 @@
- indexWidgetType === 'grid' ? '// ' : '') ?> - searchModelClass !== ''): ?> - echo $this->render('_search', ['model' =>$searchModel]); - - ?> + indexWidgetType !== 'grid' && $generator->searchModelClass !== '') { + echo "render('_search', ['model' => \$searchModel]); ?>"; + } ?> indexWidgetType === 'grid'): ?> @@ -150,10 +147,11 @@ ); $route = $generator->createRelationRoute($relation, 'index'); $label = Inflector::titleize(StringHelper::basename($relation->modelClass), '-'); + $i18nMessageLabel = $generator->generateString($label); $items .= << ['{$route}'], - 'label' => ' ' . Yii::t('$generator->modelMessageCategory', '$label'), + 'url' => ['$route'], + 'label' => ' ' . $i18nMessageLabel, ], PHP; @@ -187,7 +185,7 @@
- GridView::widget([ + GridView::widget([ 'dataProvider' => $dataProvider, 'pager' => [ 'class' => yii\widgets\LinkPager::class, @@ -197,10 +195,9 @@ searchModelClass !== ''): ?> 'filterModel' => $searchModel, - 'tableOptions' => ['class' => 'table table-striped table-bordered table-hover'], - 'headerRowOptions' => ['class'=>'x'], 'columns' => [ generateString('View'); $actionButtonColumn = << '{$generator->actionButtonClass}', @@ -208,8 +205,8 @@ 'buttons' => [ 'view' => function (\$url, \$model, \$key) { \$options = [ - 'title' => Yii::t('{$generator->messageCategory}', 'View'), - 'aria-label' => Yii::t('{$generator->messageCategory}', 'View'), + 'title' => $i18nMessageView, + 'aria-label' => $i18nMessageView, 'data-pjax' => '0', ]; return Html::a('', \$url, \$options); @@ -263,7 +260,7 @@ ListView::widget([ 'dataProvider' => $dataProvider, 'itemOptions' => ['class' => 'item'], - 'itemView' => function ($model, $key, $index, $widget) { + 'itemView' => function ($model) { return Html::a(Html::encode($model->), ['view', ]); }, ]); ?> From e5579bcb0bdcee8dd2ec47f1e1dcd224d2635df1 Mon Sep 17 00:00:00 2001 From: Elias Luhr Date: Sat, 25 Mar 2023 00:45:55 +0100 Subject: [PATCH 25/45] call static method --- src/generators/crud/default/views/view.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/generators/crud/default/views/view.php b/src/generators/crud/default/views/view.php index c9f4e59..7601110 100644 --- a/src/generators/crud/default/views/view.php +++ b/src/generators/crud/default/views/view.php @@ -46,13 +46,13 @@ $this->title = Yii::t('modelMessageCategory ?>', ''); $this->params['breadcrumbs'][] = ['label' => Yii::t('modelMessageCategory ?>.plural', ''), 'url' => ['index']]; -$this->params['breadcrumbs'][] = ['label' => (string)$model->getModelNameAttribute($model)?>, 'url' => ['view', ]]; +$this->params['breadcrumbs'][] = ['label' => (string)$model->, 'url' => ['view', ]]; $this->params['breadcrumbs'][] = generateString('View') ?>; ?>

- ' . $generator->getModelNameAttribute($generator->modelClass) . ") ?>\n" ?> + ' . $generator::getModelNameAttribute($generator->modelClass) . ") ?>\n" ?> generateString($modelName) . ' ?>' ?>

From 9dd40b66a37c809c81d641fc1513c15e01e5347d Mon Sep 17 00:00:00 2001 From: Elias Luhr Date: Sat, 25 Mar 2023 01:20:52 +0100 Subject: [PATCH 26/45] no meta search --- src/generators/crud/Generator.php | 14 -------------- src/generators/crud/default/search.php | 4 ---- 2 files changed, 18 deletions(-) diff --git a/src/generators/crud/Generator.php b/src/generators/crud/Generator.php index 39c9166..45ba427 100644 --- a/src/generators/crud/Generator.php +++ b/src/generators/crud/Generator.php @@ -544,12 +544,6 @@ public function getTranslationRelationModels() public function getTranslationModelClass() { return '\\' . $this->modelClass . Inflector::camelize('translation'); } - /** - * @return string - */ - public function getTranslationMetaModelClass() { - return '\\' . $this->modelClass . Inflector::camelize('translation_meta'); - } /** * @return bool @@ -559,14 +553,6 @@ public function getHasTranslationRelation() { return isset(\Yii::createObject($this->modelClass)->behaviors()['translation']); } - /** - * @return bool - * @throws \yii\base\InvalidConfigException - */ - public function getHasTranslationMetaRelation() { - return isset(\Yii::createObject($this->modelClass)->behaviors()['translation_meta']); - } - public function getRenderWithSearch() { return $this->indexWidgetType !== 'grid' && $this->searchModelClass !== ''; diff --git a/src/generators/crud/default/search.php b/src/generators/crud/default/search.php index 36f56f0..bcbfce3 100644 --- a/src/generators/crud/default/search.php +++ b/src/generators/crud/default/search.php @@ -67,10 +67,6 @@ public function search($params) $query->leftJoin(translationModelClass?>::tableName(),::tableName() . '.id = ' . translationModelClass?>::tableName() . '._id'); -hasTranslationMetaRelation): ?> - $query->leftJoin(translationMetaModelClass?>::tableName(),::tableName() . '.id = ' . translationMetaModelClass?>::tableName() . '._id'); - - $dataProvider = new ActiveDataProvider([ 'query' => $query, From b5dd8eeee259d8b67e45db4144e26a5d397aa672 Mon Sep 17 00:00:00 2001 From: Elias Luhr Date: Mon, 27 Mar 2023 10:14:45 +0200 Subject: [PATCH 27/45] generate translation trait if needed --- src/generators/model/Generator.php | 17 +++- src/generators/model/default/model.php | 86 ++++++------------- .../model/default/translation-trait.php | 41 +++++++++ 3 files changed, 84 insertions(+), 60 deletions(-) create mode 100644 src/generators/model/default/translation-trait.php diff --git a/src/generators/model/Generator.php b/src/generators/model/Generator.php index 2f3abf3..6d48cd2 100644 --- a/src/generators/model/Generator.php +++ b/src/generators/model/Generator.php @@ -316,6 +316,8 @@ public function generate() $db = $this->getDbConnection(); + $generateTranslationTrait = false; + foreach ($this->getTableNames() as $tableName) { list($relations, $translations) = array_values($this->extractTranslations($tableName, $relations)); $className = $this->modelClass === '' || php_sapi_name() === 'cli' @@ -333,13 +335,16 @@ public function generate() 'labels' => $this->generateLabels($tableSchema), 'hints' => $this->generateHints($tableSchema), 'rules' => $this->generateRules($tableSchema), - 'relations' => isset($relations[$tableName]) ? $relations[$tableName] : [], + 'relations' => $relations[$tableName] ?? [], 'ns' => $this->ns, 'enum' => $this->getEnum($tableSchema->columns), + 'traits' => (array)$this->baseTraits ]; if (!empty($translations)) { $params['translation'] = $translations; + $params['traits'][] = '\\' . $this->ns . '\traits\TranslationAttributeRules'; + $generateTranslationTrait = true; } $params['blameable'] = $this->generateBlameable($tableSchema); @@ -392,6 +397,16 @@ public function generate() $files[] = new CodeFile($formDataFile, $formData); } + if ($generateTranslationTrait) { + $files[] = new CodeFile( + Yii::getAlias('@' . str_replace('\\', '/', $this->ns)) . '/traits/TranslationAttributeRules.php', + $this->render('translation-trait.php', [ + 'ns' => $this->ns . '\traits' + ]) + ); + } + + return $files; } diff --git a/src/generators/model/default/model.php b/src/generators/model/default/model.php index fcb5962..4dd5ce9 100644 --- a/src/generators/model/default/model.php +++ b/src/generators/model/default/model.php @@ -17,6 +17,8 @@ * @var string[] $labels list of attribute labels (name => label) * @var string[] $rules list of validation rules * @var array $relations list of relations (name => relation declaration) + * @var array $translation + * @var array $traits */ $activeRecordClass = '\\' . ltrim($generator->baseClass, '\\'); @@ -60,11 +62,11 @@ abstract class extends { baseTraits; - if ($traits) { - echo "use {$traits};"; + if (!empty($traits)) { + echo "\tuse " . implode(', ', $traits) . ';' . PHP_EOL; } ?> + @@ -104,21 +106,21 @@ public static function getDb() */ public function behaviors() { - $behaviors = parent::behaviors(); + $behaviors = parent::behaviors(); - $behaviors['blameable'] = [ - 'class' => BlameableBehavior::class, - - 'createdByAttribute' => , - - - 'updatedByAttribute' => , - - ]; + $behaviors['blameable'] = [ + 'class' => BlameableBehavior::class, + + 'createdByAttribute' => , + + + 'updatedByAttribute' => , + +]; - $behaviors['timestamp'] = [ - 'class' => TimestampBehavior::class, +$behaviors['timestamp'] = [ + 'class' => TimestampBehavior::class, 'value' => , @@ -128,14 +130,13 @@ public function behaviors() 'updatedAtAttribute' => , - ]; +]; $behaviors['translation'] = [ 'class' => TranslateableBehavior::class, - // in case you renamed your relation, you can setup its name // 'relation' => 'translations', languageCodeColumn !== 'language'): ?> 'languageField' => 'languageCodeColumn ?>', @@ -152,7 +153,6 @@ public function behaviors() $values): ?> - $behaviors['translation_'] = [ 'class' => TranslateableBehavior::class, 'relation' => 'translations', @@ -188,9 +188,9 @@ public function rules() { $parentRules = parent::rules(); - $parentRules += $this->importTranslationAttributeRules(); + $parentRules += $this->importTranslationAttributeRules(); - return ArrayHelper::merge($parentRules, []); + return ArrayHelper::merge($parentRules, []); } /** @@ -241,49 +241,17 @@ public function getTranslations() $values): ?> - /** - * @return \yii\db\ActiveQuery - */ - public function getTranslations() - { - - } + /** + * @return \yii\db\ActiveQuery + */ + public function getTranslations() + { + + } - - /** - * get validation rules from translation* relationModels - * @return array - */ - protected function importTranslationAttributeRules() { - - $rules = []; - - foreach ($this->getBehaviors() as $key => $behavoir) { - - if ($behavoir instanceof TranslateableBehavior) { - - $translationModelClass = $this->getRelation($behavoir->relation)->modelClass; - $importRules = (new $translationModelClass)->rules(); - foreach ($importRules as $rule) { - foreach ((array)$rule[0] as $rule_key => $attribute) { - if (!in_array($attribute, $behavoir->translationAttributes, true)) { - unset ($rule[0][$rule_key]); - } - } - if (!empty($rule[0])) { - $rules[] = $rule; - } - } - } - } - - return $rules; - } - - /** diff --git a/src/generators/model/default/translation-trait.php b/src/generators/model/default/translation-trait.php new file mode 100644 index 0000000..12e7168 --- /dev/null +++ b/src/generators/model/default/translation-trait.php @@ -0,0 +1,41 @@ + + +namespace ; + +use dosamigos\translateable\TranslateableBehavior; + +trait TranslationAttributeRules +{ + /** + * Import rules from translation model for translation attributes + * + * @return array + */ + public function importTranslationAttributeRules(): array + { + $rules = []; + foreach ($this->getBehaviors() as $behavior) { + if ($behavior instanceof TranslateableBehavior) { + $translationModelClass = $this->getRelation($behavior->relation)->modelClass; + $importRules = (new $translationModelClass)->rules(); + foreach ($importRules as $rule) { + foreach ((array)$rule[0] as $rule_key => $attribute) { + if (!in_array($attribute, $behavior->translationAttributes, true)) { + unset($rule[0][$rule_key]); + } + } + if (!empty($rule[0])) { + $rules[] = $rule; + } + } + } + } + return $rules; + } +} From 4cd779fd22c214b3524460bac4208d37d845f6fd Mon Sep 17 00:00:00 2001 From: Elias Luhr Date: Mon, 27 Mar 2023 12:56:32 +0200 Subject: [PATCH 28/45] fixed relation column name --- src/generators/crud/default/search.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/generators/crud/default/search.php b/src/generators/crud/default/search.php index bcbfce3..735c944 100644 --- a/src/generators/crud/default/search.php +++ b/src/generators/crud/default/search.php @@ -2,6 +2,8 @@ /** * This is the template for generating CRUD search class of the specified model. */ + +use yii\helpers\Inflector; use yii\helpers\StringHelper; /* @var $this yii\web\View */ @@ -64,7 +66,7 @@ public function search($params) $query = ::find(); hasTranslationRelation): ?> - $query->leftJoin(translationModelClass?>::tableName(),::tableName() . '.id = ' . translationModelClass?>::tableName() . '._id'); + $query->leftJoin(translationModelClass?>::tableName(),::tableName() . '.id = ' . translationModelClass?>::tableName() . '._id'); From f33a31c10cbb709d06c4c407e877288e179fbe63 Mon Sep 17 00:00:00 2001 From: Elias Luhr Date: Mon, 27 Mar 2023 13:54:06 +0200 Subject: [PATCH 29/45] simplify form view(s) --- .../crud/default/views/_form-fields.php | 3 +- src/generators/crud/default/views/_form.php | 30 +++++-------------- 2 files changed, 8 insertions(+), 25 deletions(-) diff --git a/src/generators/crud/default/views/_form-fields.php b/src/generators/crud/default/views/_form-fields.php index 11fcf69..7792721 100644 --- a/src/generators/crud/default/views/_form-fields.php +++ b/src/generators/crud/default/views/_form-fields.php @@ -15,11 +15,10 @@ * @var modelClass, '\\') ?> $model * @var yii\widgets\ActiveForm $form */ - ?> \n"; + echo "\n\n\n"; $prepend = $generator->prependActiveField($attribute, $model); $field = $generator->activeField($attribute, $model); $append = $generator->appendActiveField($attribute, $model); diff --git a/src/generators/crud/default/views/_form.php b/src/generators/crud/default/views/_form.php index 300a667..8fb8102 100644 --- a/src/generators/crud/default/views/_form.php +++ b/src/generators/crud/default/views/_form.php @@ -49,32 +49,18 @@ ); ?> -
- beginBlock('main'); ?>\n"; ?> -
- render('_form-fields', ['form' => \$form, 'model' => \$model])?>\n"?> -
- endBlock(); ?>'; ?> - Yii::t('$generator->modelMessageCategory', '$label'), - 'content' => \$this->blocks['main'], - 'active' => true, -], -EOS; - ?> - - generateString(substr(strrchr($model::class, '\\'), 1)); + echo " false, 'items' => [ - $items + [ + 'label' => $label, + 'content' => \$this->render('_form-fields', ['form' => \$form, 'model' => \$model]), + 'active' => true, + ] ] ] ); @@ -97,7 +83,5 @@ ActiveForm::end(); ?> -
-
From 86aeff66d469231d70b7b2d4c35ee09bc06dddbb Mon Sep 17 00:00:00 2001 From: Elias Luhr Date: Thu, 4 Jan 2024 12:12:06 +0100 Subject: [PATCH 30/45] Fix controller syntax and structure + remove deprecations and not needed code --- .../crud/default/controller-extended.php | 8 +- .../crud/default/controller-rest.php | 53 +-- src/generators/crud/default/controller.php | 329 +++++++++--------- 3 files changed, 194 insertions(+), 196 deletions(-) diff --git a/src/generators/crud/default/controller-extended.php b/src/generators/crud/default/controller-extended.php index 7c9ec5f..7c565c5 100644 --- a/src/generators/crud/default/controller-extended.php +++ b/src/generators/crud/default/controller-extended.php @@ -7,10 +7,12 @@ namespace controllerClass, '\\')) ?>; +use controllerNs) ? '\\'.$generator->controllerNs.'\\' : '', '\\') .'base\\'.$controllerClassName?> as Base; + /** -* This is the class for controller "". -*/ -class extends controllerNs) ? '\\'.$generator->controllerNs.'\\' : '') .'base\\'.$controllerClassName."\n" ?> + * This is the class for controller "". + */ +class extends Base { } diff --git a/src/generators/crud/default/controller-rest.php b/src/generators/crud/default/controller-rest.php index 4fe1940..24fecce 100644 --- a/src/generators/crud/default/controller-rest.php +++ b/src/generators/crud/default/controller-rest.php @@ -2,41 +2,54 @@ /** * Customizable controller class. */ + +use yii\helpers\StringHelper; + +$modelClass = StringHelper::basename($generator->modelClass); echo " namespace controllerNs ?>\api; /** -* This is the class for REST controller "". -*/ + * This is the class for REST controller "". + */ +use modelClass ?>; +accessFilter): ?> use yii\filters\AccessControl; use yii\helpers\ArrayHelper; + +use yii\rest\ActiveController; +accessFilter): ?> +use Yii; + -class extends \yii\rest\ActiveController +class extends ActiveController { -public $modelClass = 'modelClass ?>'; + public $modelClass = ::class; accessFilter): ?> + /** - * @inheritdoc - */ + * @inheritdoc + */ public function behaviors() { - return ArrayHelper::merge( - parent::behaviors(), - [ - 'access' => [ - 'class' => AccessControl::className(), - 'rules' => [ - [ - 'allow' => true, - 'matchCallback' => function ($rule, $action) {return \Yii::$app->user->can($this->module->id . '_' . $this->id . '_' . $action->id, ['route' => true]);}, - ] - ] - ] - ] - ); + return ArrayHelper::merge(parent::behaviors(), + [ + 'access' => [ + 'class' => AccessControl::class, + 'rules' => [ + [ + 'allow' => true, + 'matchCallback' => function ($rule, $action) { + return Yii::$app->user->can($this->module->id . '_' . $this->id . '_' . $action->id, ['route' => true]); + } + ] + ] + ] + ] + ); } } diff --git a/src/generators/crud/default/controller.php b/src/generators/crud/default/controller.php index d8c965e..00c3060 100644 --- a/src/generators/crud/default/controller.php +++ b/src/generators/crud/default/controller.php @@ -2,7 +2,7 @@ use yii\helpers\StringHelper; -/* +/** * This is the template for generating a CRUD controller class file. * * @var yii\web\View $this @@ -35,210 +35,193 @@ namespace controllerClass, '\\')) ?>\base; +use dmstr\bootstrap\Tabs; use modelClass, '\\') ?>; - use searchModelClass, '\\' ) ?> as ; +accessFilter): ?> +use yii\filters\AccessControl; +use yii\helpers\ArrayHelper; + +use yii\helpers\Url; use baseControllerClass, '\\') ?>; use yii\web\HttpException; -use yii\helpers\Url; -use yii\filters\AccessControl; -use dmstr\bootstrap\Tabs; +use yii\web\Request; +use yii\web\Response; +use Yii; /** -* implements the CRUD actions for model. -*/ + * implements the CRUD actions for model. + * + * @property Request $request + */ class extends baseControllerClass)."\n" ?> { - baseTraits; if ($traits) { echo "use {$traits};"; } ?> - -/** -* @var boolean whether to enable CSRF validation for the actions in this controller. -* CSRF validation is enabled only when both this property and [[Request::enableCsrfValidation]] are true. -*/ -public $enableCsrfValidation = false; - accessFilter): ?> /** - * @inheritdoc - */ + * @inheritdoc + */ public function behaviors() { - return [ - 'access' => [ - 'class' => AccessControl::className(), - 'rules' => [ - $actions){ -?> - [ - 'allow' => true, - 'actions' => [''], - 'roles' => [''], - ], - - ], - ], - ]; + return ArrayHelper::merge(parent::behaviors(), + [ + 'access' => [ + 'class' => AccessControl::class, + 'rules' => [ + $actions): ?> + [ + 'allow' => true, + 'actions' => [''], + 'roles' => [''] + ], + + ] + ] + ]); } -/** -* Lists all models. -* @return mixed -*/ -public function actionIndex() -{ - - $searchModel = new ; - $dataProvider = $searchModel->search($_GET); - - $dataProvider = new \yii\data\ActiveDataProvider([ - 'query' => ::find(), - ]); - - -Tabs::clearLocalStorage(); - -Url::remember(); -\Yii::$app->session['__crudReturnUrl'] = null; - -return $this->render('index', [ -'dataProvider' => $dataProvider, - + /** + * Lists all models. + * + * @return string + */ + public function actionIndex() + { + + $searchModel = new (); + $dataProvider = $searchModel->search($this->request->get()); + + $dataProvider = new ActiveDataProvider([ + 'query' => ::find(), + ]); + + + return $this->render('index', [ + 'dataProvider' => $dataProvider, + 'searchModel' => $searchModel, - -]); -} - -/** -* Displays a single model. -* -* -* @return mixed -*/ -public function actionView() -{ -\Yii::$app->session['__crudReturnUrl'] = Url::previous(); -Url::remember(); -Tabs::rememberActiveState(); - -return $this->render('view', [ -'model' => $this->findModel(), + ]); -} - -/** -* Creates a new model. -* If creation is successful, the browser will be redirected to the 'view' page. -* @return mixed -*/ -public function actionCreate() -{ -$model = new ; - -try { -if ($model->load($_POST) && $model->save()) { -return $this->redirect(['view', ]); -} elseif (!\Yii::$app->request->isPost) { -$model->load($_GET); -} -} catch (\Exception $e) { -$msg = (isset($e->errorInfo[2]))?$e->errorInfo[2]:$e->getMessage(); -$model->addError('_exception', $msg); -} -return $this->render('create', ['model' => $model]); -} + } -/** -* Updates an existing model. -* If update is successful, the browser will be redirected to the 'view' page. -* -* @return mixed -*/ -public function actionUpdate() -{ -$model = $this->findModel(); + /** + * Displays a single model. + * + * + * + * @throws HttpException + * @return string + */ + public function actionView() + { + Tabs::rememberActiveState(); -if ($model->load($_POST) && $model->save()) { -return $this->redirect(Url::previous()); -} else { -return $this->render('update', [ -'model' => $model, -]); -} -} + return $this->render('view', [ + 'model' => $this->findModel() + ]); + } -/** -* Deletes an existing model. -* If deletion is successful, the browser will be redirected to the 'index' page. -* -* @return mixed -*/ -public function actionDelete() -{ -try { -$this->findModel()->delete(); -} catch (\Exception $e) { -$msg = (isset($e->errorInfo[2]))?$e->errorInfo[2]:$e->getMessage(); -\Yii::$app->getSession()->addFlash('error', $msg); -return $this->redirect(Url::previous()); -} + /** + * Creates a new model. + * If creation is successful, the browser will be redirected to the 'view' page. + * + * @return string|Response + */ + public function actionCreate() + { + $model = new (); + + try { + if ($model->load($this->request->post()) && $model->save()) { + return $this->redirect(['view', ]); + } elseif (!$this->request->getIsPost()) { + $model->load($_GET); + } + } catch (\Exception $e) { + $model->addError('_exception', $e->errorInfo[2] ?? $e->getMessage()); + } + return $this->render('create', ['model' => $model]); + } -// TODO: improve detection -$isPivot = strstr('',','); -if ($isPivot == true) { -return $this->redirect(Url::previous()); -} elseif (isset(\Yii::$app->session['__crudReturnUrl']) && \Yii::$app->session['__crudReturnUrl'] != '/') { -Url::remember(null); -$url = \Yii::$app->session['__crudReturnUrl']; -\Yii::$app->session['__crudReturnUrl'] = null; + /** + * Updates an existing model. + * If update is successful, the browser will be redirected to the 'view' page. + * + * + * + * @throws HttpException + * @return string|Response + */ + public function actionUpdate() + { + $model = $this->findModel(); + + if ($model->load($_POST) && $model->save()) { + return $this->redirect(Url::previous()); + } else { + return $this->render('update', [ + 'model' => $model, + ]); + } + } -return $this->redirect($url); -} else { -return $this->redirect(['index']); -} -} + /** + * Deletes an existing model. + * If deletion is successful, the browser will be redirected to the 'index' page. + * + * + * + * @throws \Throwable + * @return Response + */ + public function actionDelete() + { + try { + $this->findModel()->delete(); + } catch (\Exception $e) { + Yii::$app->getSession()->addFlash('error', $e->errorInfo[2] ?? $e->getMessage()); + return $this->goBack(); + } + return $this->redirect(['index']); + } -/** -* Finds the model based on its primary key value. -* If the model is not found, a 404 HTTP exception will be thrown. -* -* @return the loaded model -* @throws HttpException if the model cannot be found -*/ -protected function findModel() -{ - \$$pk"; + /** + * Finds the model based on its primary key value. + * If the model is not found, a 404 HTTP exception will be thrown. + * + * + * + * @throws HttpException if the model cannot be found + * @return the loaded model + */ + protected function findModel() + { + \$$pk"; + } + $condition = '['.implode(', ', $condition).']'; + } + ?> + if (($model = ::findOne()) !== null) { + return $model; + } else { + throw new HttpException(404, generateString('The requested page does not exist.') ?>); + } } - $condition = '['.implode(', ', $condition).']'; -} -?> -if (($model = ::findOne()) !== null) { -return $model; -} else { -throw new HttpException(404, 'The requested page does not exist.'); -} -} } From a20f236b0d4a50dd75fbd1608f358a6de5d013d8 Mon Sep 17 00:00:00 2001 From: Elias Luhr Date: Thu, 4 Jan 2024 16:22:07 +0100 Subject: [PATCH 31/45] small cleanups --- src/generators/crud/editable/controller.php | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/generators/crud/editable/controller.php b/src/generators/crud/editable/controller.php index 9395a85..b93eceb 100644 --- a/src/generators/crud/editable/controller.php +++ b/src/generators/crud/editable/controller.php @@ -100,7 +100,7 @@ public function actionIndex() $searchModel = new ; - $dataProvider = $searchModel->search($_GET); + $dataProvider = $searchModel->search($this->request->get()); @@ -146,7 +146,7 @@ public function actionView() public function actionCreate() { $model = new ; - $model->load($_GET); + $model->load($this->request->get()); $relAttributes = $model->attributes; try { @@ -156,7 +156,7 @@ public function actionCreate() } return $this->redirect(['view', ]); } elseif (!\Yii::$app->request->isPost) { - $model->load($_GET); + $model->load($this->request->get()); } } catch (\Exception $e) { $msg = (isset($e->errorInfo[2]))?$e->errorInfo[2]:$e->getMessage(); @@ -176,7 +176,7 @@ public function actionCreate() public function actionCreateForRel() { $model = new ; - $model->load($_GET); + $model->load($this->request->get()); $relAttributes = $model->attributes; $model->save(); return $this->goBack(); @@ -191,7 +191,7 @@ public function actionCreateForRel() public function actionUpdate() { $model = new ; - $model->load($_GET); + $model->load($this->request->get()); $relAttributes = $model->attributes; $model = $this->findModel(); @@ -223,7 +223,7 @@ public function actionDelete() } $model = new ; - $model->load($_GET); + $model->load($this->request->get()); $relAttributes = $model->attributes; if($relAttributes){ return $this->redirect(Url::previous()); From 16dae88d92ae1a22178abd36ebf87cde4a44a2fe Mon Sep 17 00:00:00 2001 From: Elias Luhr Date: Thu, 4 Jan 2024 16:22:26 +0100 Subject: [PATCH 32/45] php 8 deprecation string in trim fix --- src/generators/crud/default/views/index.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/generators/crud/default/views/index.php b/src/generators/crud/default/views/index.php index 0153057..659640c 100644 --- a/src/generators/crud/default/views/index.php +++ b/src/generators/crud/default/views/index.php @@ -231,8 +231,8 @@ foreach ($safeAttributes as $attribute) { - $format = trim($generator->columnFormat($attribute, $model)); - if ($format == false) { + $format = trim((string)$generator->columnFormat($attribute, $model)); + if (empty($format)) { continue; } if (++$count <= $generator->gridMaxColumns) { From 633c6e9877b632d88427f4c7809b07beace4cf02 Mon Sep 17 00:00:00 2001 From: Elias Luhr Date: Thu, 4 Jan 2024 16:22:39 +0100 Subject: [PATCH 33/45] use getters --- src/generators/crud/default/search.php | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/generators/crud/default/search.php b/src/generators/crud/default/search.php index 735c944..25aa1f0 100644 --- a/src/generators/crud/default/search.php +++ b/src/generators/crud/default/search.php @@ -6,8 +6,9 @@ use yii\helpers\Inflector; use yii\helpers\StringHelper; -/* @var $this yii\web\View */ -/* @var $generator yii\gii\generators\crud\Generator */ +/* @var $this yii\web\View + * @var $generator schmunk42\giiant\generators\crud\Generator + */ $modelClass = StringHelper::basename($generator->modelClass); $searchModelClass = StringHelper::basename($generator->searchModelClass); @@ -65,7 +66,7 @@ public function search($params) { $query = ::find(); -hasTranslationRelation): ?> +getHasTranslationRelation()): ?> $query->leftJoin(translationModelClass?>::tableName(),::tableName() . '.id = ' . translationModelClass?>::tableName() . '._id'); @@ -81,7 +82,7 @@ public function search($params) // $query->where('0=1'); return $dataProvider; } -hasTranslationRelation): ?> +getHasTranslationRelation()): ?> $query->groupBy(::tableName() . '.id'); From 56cb77f0063bf9c69e22a40f3bb5b5f0b38c5505 Mon Sep 17 00:00:00 2001 From: Elias Luhr Date: Thu, 4 Jan 2024 16:22:53 +0100 Subject: [PATCH 34/45] remove overhead --- src/generators/model/default/model-extended.php | 16 ---------------- src/generators/model/default/model.php | 10 +++++----- src/generators/model/default/query.php | 5 +---- 3 files changed, 6 insertions(+), 25 deletions(-) diff --git a/src/generators/model/default/model-extended.php b/src/generators/model/default/model-extended.php index cb2334c..a289054 100644 --- a/src/generators/model/default/model-extended.php +++ b/src/generators/model/default/model-extended.php @@ -24,21 +24,5 @@ */ class extends Base { - /** - * @inheritdoc - */ - public function behaviors() - { - $behaviors = parent::behaviors(); - return $behaviors; - } - /** - * @inheritdoc - */ - public function rules() - { - $rules = parent::rules(); - return $rules; - } } diff --git a/src/generators/model/default/model.php b/src/generators/model/default/model.php index 4dd5ce9..955f902 100644 --- a/src/generators/model/default/model.php +++ b/src/generators/model/default/model.php @@ -122,7 +122,7 @@ public function behaviors() $behaviors['timestamp'] = [ 'class' => TimestampBehavior::class, - 'value' => , + 'value' => , 'createdAtAttribute' => , @@ -133,9 +133,9 @@ public function behaviors() ]; - - - $behaviors['translation'] = [ + + +$behaviors['translation'] = [ 'class' => TranslateableBehavior::class, // 'relation' => 'translations', languageCodeColumn !== 'language'): ?> @@ -147,7 +147,7 @@ public function behaviors() ], 'deleteEvent' => ::EVENT_BEFORE_DELETE, 'restrictDeletion' => TranslateableBehavior::DELETE_LAST - ]; + ]; diff --git a/src/generators/model/default/query.php b/src/generators/model/default/query.php index 69a2839..1722dd4 100644 --- a/src/generators/model/default/query.php +++ b/src/generators/model/default/query.php @@ -30,8 +30,5 @@ */ class extends queryBaseClass, '\\') . "\n" ?> { - /* public function active() - { - return $this->andWhere(['status' => 1]); - } */ + } From 8850223c820f20048acbd8a98638d9e823f701ca Mon Sep 17 00:00:00 2001 From: Elias Luhr Date: Thu, 4 Jan 2024 16:23:23 +0100 Subject: [PATCH 35/45] use datetime imutable instead of db expression --- src/generators/model/Generator.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/generators/model/Generator.php b/src/generators/model/Generator.php index 7433564..5e91133 100644 --- a/src/generators/model/Generator.php +++ b/src/generators/model/Generator.php @@ -826,7 +826,7 @@ protected function generateTimestamp($table) // check column type, if datetime set NOW() as Value if ($table->getColumn($this->createdAtColumn)->type === 'datetime') { return [ - 'value' => 'new \yii\db\Expression(\'NOW()\')', + 'value' => '(new \DateTime())->format(\'Y-m-d H:i:s\')', 'createdAtAttribute' => $createdAt, 'updatedAtAttribute' => $updatedAt, 'timestampBehaviorClass' => $this->timestampBehaviorClass, From 3eff8bdd10af52a41a6fea6bf48676f1ad3fdcf1 Mon Sep 17 00:00:00 2001 From: Elias Luhr Date: Thu, 4 Jan 2024 16:23:57 +0100 Subject: [PATCH 36/45] unique validator with targetClass so in works for translations --- src/generators/model/Generator.php | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/src/generators/model/Generator.php b/src/generators/model/Generator.php index 5e91133..8daec01 100644 --- a/src/generators/model/Generator.php +++ b/src/generators/model/Generator.php @@ -632,8 +632,22 @@ public function generateRules($table) $ns = "\\{$this->ns}\\"; $match = "'targetClass' => "; $replace = $match . $ns; + + + $replaceMap = [ + [ + 'search' => "'targetClass' => ", + 'replace' => "'targetClass' => " . $ns, + ], + [ + 'search' => "'unique', ", + 'replace' => "'unique', 'targetClass' => " . $ns . $this->modelClass . '::class, ', + ] + ]; foreach ($parentRules as $k => $parentRule) { - $parentRules[$k] = str_replace($match, $replace, $parentRule); + foreach ($replaceMap as $replaceItem) { + $parentRules[$k] = str_replace($replaceItem['search'], $replaceItem['replace'], $parentRule); + } } $rules = array_merge($parentRules, $rules); From c69b99459c458cc70425d7b9c5eb7135e20a0dc7 Mon Sep 17 00:00:00 2001 From: Elias Luhr Date: Mon, 29 Jan 2024 15:01:14 +0100 Subject: [PATCH 37/45] break out of loop to prevent overloading --- src/generators/model/Generator.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/generators/model/Generator.php b/src/generators/model/Generator.php index 8daec01..c7c4933 100644 --- a/src/generators/model/Generator.php +++ b/src/generators/model/Generator.php @@ -633,7 +633,7 @@ public function generateRules($table) $match = "'targetClass' => "; $replace = $match . $ns; - + $replaceMap = [ [ 'search' => "'targetClass' => ", @@ -647,6 +647,7 @@ public function generateRules($table) foreach ($parentRules as $k => $parentRule) { foreach ($replaceMap as $replaceItem) { $parentRules[$k] = str_replace($replaceItem['search'], $replaceItem['replace'], $parentRule); + break; } } From 3b4b63a6478820aeb0309bfd7595c3b5d97b2d24 Mon Sep 17 00:00:00 2001 From: Elias Luhr Date: Mon, 29 Jan 2024 19:20:52 +0100 Subject: [PATCH 38/45] Fixed access definitions --- src/generators/crud/Generator.php | 3 +- .../crud/default/access_definition.php | 8 ++-- src/generators/crud/default/controller.php | 5 +-- .../crud/default/migration_access.php | 20 ++++----- src/generators/crud/default/views/index.php | 10 ++--- src/generators/crud/default/views/view.php | 42 +++++++++++++++++++ .../crud/editable/access_definition.php | 8 ++-- .../crud/editable/migration_access.php | 20 ++++----- src/generators/crud/editable/views/index.php | 8 ++-- 9 files changed, 82 insertions(+), 42 deletions(-) diff --git a/src/generators/crud/Generator.php b/src/generators/crud/Generator.php index 45ba427..3166489 100644 --- a/src/generators/crud/Generator.php +++ b/src/generators/crud/Generator.php @@ -395,7 +395,8 @@ public function generate() if (is_file($templatePath.'/'.$file) && pathinfo($file, PATHINFO_EXTENSION) === 'php') { $files[] = new CodeFile("$viewPath/$file", $this->render("views/$file", [ 'model' => $model, - 'safeAttributes' => $safeAttributes + 'safeAttributes' => $safeAttributes, + 'accessDefinitions' => $accessDefinitions ])); } } diff --git a/src/generators/crud/default/access_definition.php b/src/generators/crud/default/access_definition.php index e7b10ba..2b1dcaa 100644 --- a/src/generators/crud/default/access_definition.php +++ b/src/generators/crud/default/access_definition.php @@ -13,7 +13,7 @@ /** * permissions - create name and descriptions */ -$permisions = []; +$permissions = []; foreach ($actions as $k => $action){ $name = $this->getModuleId() . '_' . $this->getControllerID() @@ -21,7 +21,7 @@ $description = $this->getModuleId() . '/' . $this->getControllerID() . '/' . $action; - $permisions[$action] = [ + $permissions[$action] = [ 'name' => $name, 'description' => $description, ]; @@ -48,6 +48,6 @@ } return [ - 'permisions' => $permisions, + 'permissions' => $permissions, 'roles' => $roles, -]; \ No newline at end of file +]; diff --git a/src/generators/crud/default/controller.php b/src/generators/crud/default/controller.php index 5b8f296..3334f9f 100644 --- a/src/generators/crud/default/controller.php +++ b/src/generators/crud/default/controller.php @@ -50,9 +50,6 @@ use yii\base\InvalidConfigException; use yii\helpers\Url; use baseControllerClass, '\\') ?>; -accessFilter): ?> -use yii\filters\AccessControl; - use yii\web\NotFoundHttpException; use yii\web\Request; use yii\web\Response; @@ -175,7 +172,7 @@ public function actionUpdate() { $model = $this->findModel(); if ($model->load($this->request->post()) && $model->save()) { - return $this->redirect(Url::previous()); + return $this->redirect(['view', ]); } return $this->render('update', ['model' => $model]); } diff --git a/src/generators/crud/default/migration_access.php b/src/generators/crud/default/migration_access.php index 3e708e8..0a841ee 100644 --- a/src/generators/crud/default/migration_access.php +++ b/src/generators/crud/default/migration_access.php @@ -13,26 +13,26 @@ class migrationClass?> extends Migration /** * @var array controller all actions */ - public $permisions = var_export54($accessDefinitions['permisions'],' ')?>; + public $permissions = var_export54($accessDefinitions['permissions'],' ')?>; /** - * @var array roles and maping to actions/permisions + * @var array roles and maping to actions/permissions */ public $roles = var_export54($accessDefinitions['roles'],' ')?>; public function up() { - $permisions = []; + $permissions = []; $auth = \Yii::$app->authManager; /** - * create permisions for each controller action + * create permissions for each controller action */ - foreach ($this->permisions as $action => $permission) { - $permisions[$action] = $auth->createPermission($permission['name']); - $permisions[$action]->description = $permission['description']; - $auth->add($permisions[$action]); + foreach ($this->permissions as $action => $permission) { + $permissions[$action] = $auth->createPermission($permission['name']); + $permissions[$action]->description = $permission['description']; + $auth->add($permissions[$action]); } /** @@ -46,7 +46,7 @@ public function up() * to role assign permissions */ foreach ($actions as $action) { - $auth->addChild($role, $permisions[$action]); + $auth->addChild($role, $permissions[$action]); } } } @@ -59,7 +59,7 @@ public function down() { $auth->remove($role); } - foreach ($this->permisions as $permission) { + foreach ($this->permissions as $permission) { $authItem = $auth->createPermission($permission['name']); $auth->remove($authItem); } diff --git a/src/generators/crud/default/views/index.php b/src/generators/crud/default/views/index.php index 659640c..de3a305 100644 --- a/src/generators/crud/default/views/index.php +++ b/src/generators/crud/default/views/index.php @@ -6,11 +6,11 @@ /** * @var yii\web\View $this * @var schmunk42\giiant\generators\crud\Generator $generator - * @var array $permisions */ $urlParams = $generator->generateUrlParams(); $nameAttribute = $generator->getNameAttribute(); +$permissions = $accessDefinitions['permissions']; /** @var \yii\db\ActiveRecord $model */ $model = new $generator->modelClass(); @@ -60,15 +60,15 @@ */ $actionColumnTemplates = []; -if (\Yii::$app->user->can('', ['route' => true])) { +if (\Yii::$app->user->can('', ['route' => true])) { $actionColumnTemplates[] = '{view}'; } -if (\Yii::$app->user->can('', ['route' => true])) { +if (\Yii::$app->user->can('', ['route' => true])) { $actionColumnTemplates[] = '{update}'; } -if (\Yii::$app->user->can('', ['route' => true])) { +if (\Yii::$app->user->can('', ['route' => true])) { $actionColumnTemplates[] = '{delete}'; } accessFilter){ echo " -if(\Yii::$app->user->can('', ['route' => true])){ +if(\Yii::$app->user->can('', ['route' => true])){ \n" ?> diff --git a/src/generators/crud/default/views/view.php b/src/generators/crud/default/views/view.php index 7601110..efde802 100644 --- a/src/generators/crud/default/views/view.php +++ b/src/generators/crud/default/views/view.php @@ -27,6 +27,7 @@ $className = $model::class; $modelName = Inflector::camel2words(StringHelper::basename($className)); $urlParams = $generator->generateUrlParams(); +$permissions = $accessDefinitions['permissions']; echo " @@ -60,23 +61,54 @@
+ + accessFilter) { + echo 'getUser()->can(\'' . $permissions['update']['name'] . '\')): ?>'; + } + ?> Html::a( ' ' . generateString('Edit ' . $modelName) ?>, [ 'update', ], ['class' => 'btn btn-info']) ?> + accessFilter) { + echo ''; + } + ?> + accessFilter) { + echo 'getUser()->can(\'' . $permissions['update']['name'] . '\')): ?>'; + } + ?> Html::a( ' ' . generateString('Copy ' . $modelName) ?>, ['create', , 'modelClass) ?>'=>$copyParams], ['class' => 'btn btn-success']) ?> + accessFilter) { + echo ''; + } + ?> + accessFilter) { + echo 'getUser()->can(\'' . $permissions['create']['name'] . '\')): ?>'; + } + ?> Html::a( ' ' . generateString('New ' . $modelName) ?>, ['create'], ['class' => 'btn btn-success']) ?> + accessFilter) { + echo ''; + } + ?>
@@ -115,6 +147,11 @@
+ accessFilter) { + echo 'getUser()->can(\'' . $permissions['delete']['name'] . '\')): ?>'; + } + ?> Html::a(' ' . generateString( 'Delete ' . $modelName @@ -125,6 +162,11 @@ 'data-method' => 'post', ]); ?> + accessFilter) { + echo ''; + } + ?> endBlock(); ?>\n\n"; ?> $action){ $name = $this->getModuleId() . '_' . $this->getControllerID() @@ -30,7 +30,7 @@ $description = $this->getModuleId() . '/' . $this->getControllerID() . '/' . $action; - $permisions[$action] = [ + $permissions[$action] = [ 'name' => $name, 'description' => $description, ]; @@ -76,6 +76,6 @@ } return [ - 'permisions' => $permisions, + 'permissions' => $permissions, 'roles' => $roles, -]; \ No newline at end of file +]; diff --git a/src/generators/crud/editable/migration_access.php b/src/generators/crud/editable/migration_access.php index 3e708e8..0a841ee 100644 --- a/src/generators/crud/editable/migration_access.php +++ b/src/generators/crud/editable/migration_access.php @@ -13,26 +13,26 @@ class migrationClass?> extends Migration /** * @var array controller all actions */ - public $permisions = var_export54($accessDefinitions['permisions'],' ')?>; + public $permissions = var_export54($accessDefinitions['permissions'],' ')?>; /** - * @var array roles and maping to actions/permisions + * @var array roles and maping to actions/permissions */ public $roles = var_export54($accessDefinitions['roles'],' ')?>; public function up() { - $permisions = []; + $permissions = []; $auth = \Yii::$app->authManager; /** - * create permisions for each controller action + * create permissions for each controller action */ - foreach ($this->permisions as $action => $permission) { - $permisions[$action] = $auth->createPermission($permission['name']); - $permisions[$action]->description = $permission['description']; - $auth->add($permisions[$action]); + foreach ($this->permissions as $action => $permission) { + $permissions[$action] = $auth->createPermission($permission['name']); + $permissions[$action]->description = $permission['description']; + $auth->add($permissions[$action]); } /** @@ -46,7 +46,7 @@ public function up() * to role assign permissions */ foreach ($actions as $action) { - $auth->addChild($role, $permisions[$action]); + $auth->addChild($role, $permissions[$action]); } } } @@ -59,7 +59,7 @@ public function down() { $auth->remove($role); } - foreach ($this->permisions as $permission) { + foreach ($this->permissions as $permission) { $authItem = $auth->createPermission($permission['name']); $auth->remove($authItem); } diff --git a/src/generators/crud/editable/views/index.php b/src/generators/crud/editable/views/index.php index 1911289..3426416 100644 --- a/src/generators/crud/editable/views/index.php +++ b/src/generators/crud/editable/views/index.php @@ -56,15 +56,15 @@ */ $actionColumnTemplates = []; -if (\Yii::$app->user->can('')) { +if (\Yii::$app->user->can('')) { $actionColumnTemplates[] = '{view}'; } -if (\Yii::$app->user->can('')) { +if (\Yii::$app->user->can('')) { $actionColumnTemplates[] = '{update}'; } -if (\Yii::$app->user->can('')) { +if (\Yii::$app->user->can('')) { $actionColumnTemplates[] = '{delete}'; } accessFilter){ echo " -if(\Yii::$app->user->can('')){ +if(\Yii::$app->user->can('')){ \n" ?> From 5d9faae1b3064644be52205fe8e9a84d21ee925f Mon Sep 17 00:00:00 2001 From: Elias Luhr Date: Tue, 30 Jan 2024 10:07:42 +0100 Subject: [PATCH 39/45] remove go back to avoid void targets -> redirect to home screen --- src/generators/crud/default/controller.php | 1 - 1 file changed, 1 deletion(-) diff --git a/src/generators/crud/default/controller.php b/src/generators/crud/default/controller.php index 3334f9f..455af08 100644 --- a/src/generators/crud/default/controller.php +++ b/src/generators/crud/default/controller.php @@ -192,7 +192,6 @@ public function actionDelete() $this->findModel()->delete(); } catch (\Exception $e) { Yii::$app->getSession()->addFlash('error', $e->errorInfo[2] ?? $e->getMessage()); - return $this->goBack(); } return $this->redirect(['index']); From 98f479436aef999889c6a6bdec36985e943c74f7 Mon Sep 17 00:00:00 2001 From: Elias Luhr Date: Wed, 31 Jan 2024 10:35:17 +0100 Subject: [PATCH 40/45] Allow clear for relations which are nullable --- src/generators/crud/providers/core/RelationProvider.php | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/generators/crud/providers/core/RelationProvider.php b/src/generators/crud/providers/core/RelationProvider.php index d3e5bb0..158b9f0 100644 --- a/src/generators/crud/providers/core/RelationProvider.php +++ b/src/generators/crud/providers/core/RelationProvider.php @@ -62,7 +62,8 @@ public function activeField($attribute) case !$relation->multiple: $pk = key($relation->link); $name = $this->generator->getModelNameAttribute($relation->modelClass); - $method = __METHOD__; + $isRequired = $relation->primaryModel->isAttributeRequired($column->name) ? 'false' : 'true'; + $method = __METHOD__; switch ($this->inputWidget) { case 'select2': $code = << {$this->generator->generateString('Type to autocomplete')}, 'multiple' => false, 'disabled' => (isset(\$relAttributes) && isset(\$relAttributes['{$column->name}'])), + ], + 'pluginOptions' => [ + 'allowClear' => {$isRequired} ] ]); EOS; From c8a1f1e0479576665db96c89269844fd54df4d61 Mon Sep 17 00:00:00 2001 From: Elias Luhr Date: Tue, 6 Feb 2024 09:36:34 +0100 Subject: [PATCH 41/45] allow list crud --- src/generators/crud/ModelTrait.php | 2 +- src/generators/crud/default/views/index.php | 18 +++++++++--------- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/generators/crud/ModelTrait.php b/src/generators/crud/ModelTrait.php index 99cac59..b265e28 100644 --- a/src/generators/crud/ModelTrait.php +++ b/src/generators/crud/ModelTrait.php @@ -92,7 +92,7 @@ public function getModelRelations($modelClass, $types = []) 'getAttribute', 'getAttributeLabel', 'getAttributeHint', - 'getOldAttribute', + 'getOldAttribute', 'getErrorSummary', ]; if (in_array($method->name, $skipMethods)) { diff --git a/src/generators/crud/default/views/index.php b/src/generators/crud/default/views/index.php index de3a305..1c019bc 100644 --- a/src/generators/crud/default/views/index.php +++ b/src/generators/crud/default/views/index.php @@ -20,18 +20,18 @@ $model->setScenario('crud'); } + $baseName = StringHelper::basename($model::class); $modelName = Inflector::camel2words($baseName); -//$safeAttributes = $model->safeAttributes(); -//if (empty($safeAttributes)) { -// /** @var \yii\db\ActiveRecord $model */ -// $model = new $generator->modelClass(); -// $safeAttributes = $model->safeAttributes(); -// if (empty($safeAttributes)) { -// $safeAttributes = $model::getTableSchema()->columnNames; -// } -//} +$safeAttributes = $model->safeAttributes(); +if (empty($safeAttributes)) { + $model->setScenario('default'); + $safeAttributes = $model->safeAttributes(); +} +if (empty($safeAttributes)) { + $safeAttributes = $model::getTableSchema()->columnNames; +} echo " From 2e2eb45b9588251446b635447a5d7767b3c95e46 Mon Sep 17 00:00:00 2001 From: Elias Luhr Date: Mon, 12 Feb 2024 16:53:18 +0100 Subject: [PATCH 42/45] to remove potential out of memory error --- src/generators/crud/default/views/view.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/generators/crud/default/views/view.php b/src/generators/crud/default/views/view.php index efde802..ce07f6e 100644 --- a/src/generators/crud/default/views/view.php +++ b/src/generators/crud/default/views/view.php @@ -43,7 +43,7 @@ * @var yii\web\View $this * @var modelClass, '\\') ?> $model */ -$copyParams = $model->attributes; +$copyParams = $model->hasMethod('getCopyParams') ? $model->getCopyParams() : $model->attributes; $this->title = Yii::t('modelMessageCategory ?>', ''); $this->params['breadcrumbs'][] = ['label' => Yii::t('modelMessageCategory ?>.plural', ''), 'url' => ['index']]; From 53c7802e08105865eb43bdeb1c75a2f9980b0cc8 Mon Sep 17 00:00:00 2001 From: Elias Luhr Date: Mon, 25 Mar 2024 16:18:56 +0100 Subject: [PATCH 43/45] fix label in forms --- src/generators/crud/default/views/_form.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/generators/crud/default/views/_form.php b/src/generators/crud/default/views/_form.php index 8fb8102..92116fd 100644 --- a/src/generators/crud/default/views/_form.php +++ b/src/generators/crud/default/views/_form.php @@ -1,5 +1,6 @@ generateString(substr(strrchr($model::class, '\\'), 1)); + $label = $generator->generateString(Inflector::camel2words(StringHelper::basename($model::class))); echo " Date: Tue, 26 Mar 2024 13:13:37 +0100 Subject: [PATCH 44/45] introduce enable or disable copy function --- src/commands/BatchController.php | 11 +++++++++-- src/generators/crud/Generator.php | 4 ++++ src/generators/crud/default/controller.php | 1 + src/generators/crud/default/views/view.php | 5 +++-- 4 files changed, 17 insertions(+), 4 deletions(-) diff --git a/src/commands/BatchController.php b/src/commands/BatchController.php index 305b299..cfc4d89 100644 --- a/src/commands/BatchController.php +++ b/src/commands/BatchController.php @@ -317,6 +317,11 @@ class BatchController extends Controller public $modelTranslationTableAdditions = ['name' => 'meta', 'fallbackLanguage' => false]; + /** + * Whether the copy functionality for a crud should be created or not + */ + public $crudEnableCopy = true; + /** * @var array application configuration for creating temporary applications */ @@ -388,7 +393,8 @@ public function options($id) 'crudOverwriteRestControllerClass', 'crudOverwriteControllerClass', 'generateAccessFilterMigrations', - 'disablePluralization' + 'disablePluralization', + 'crudEnableCopy' ] ); } @@ -566,7 +572,8 @@ public function actionCruds() 'generateAccessFilterMigrations' => $this->generateAccessFilterMigrations, 'actionButtonColumnPosition' => $this->crudActionButtonColumnPosition, 'disablePluralization' => $this->disablePluralization, - 'gridMaxColumns' => $this->crudGridMaxColumns + 'gridMaxColumns' => $this->crudGridMaxColumns, + 'enableCopy' => $this->crudEnableCopy ]; $route = 'gii/giiant-crud'; $app = \Yii::$app; diff --git a/src/generators/crud/Generator.php b/src/generators/crud/Generator.php index 3166489..d11e22e 100644 --- a/src/generators/crud/Generator.php +++ b/src/generators/crud/Generator.php @@ -164,6 +164,8 @@ class Generator extends \yii\gii\generators\crud\Generator private $_p = []; public $translateRelations = ['translation', 'translation_meta']; + + public $enableCopy = true; /** * {@inheritdoc} @@ -237,6 +239,7 @@ public function rules() 'generateAccessFilterMigrations', 'singularEntities', 'modelMessageCategory', + 'enableCopy' ], 'safe', ], @@ -277,6 +280,7 @@ public function formAttributes() 'accessFilter', 'singularEntities', 'modelMessageCategory', + 'enableCopy' ]; } diff --git a/src/generators/crud/default/controller.php b/src/generators/crud/default/controller.php index 455af08..9b6a25a 100644 --- a/src/generators/crud/default/controller.php +++ b/src/generators/crud/default/controller.php @@ -67,6 +67,7 @@ class extends bas if ($traits) { echo "use {$traits};"; } + ?> accessFilter): ?> diff --git a/src/generators/crud/default/views/view.php b/src/generators/crud/default/views/view.php index ce07f6e..45737a0 100644 --- a/src/generators/crud/default/views/view.php +++ b/src/generators/crud/default/views/view.php @@ -43,7 +43,6 @@ * @var yii\web\View $this * @var modelClass, '\\') ?> $model */ -$copyParams = $model->hasMethod('getCopyParams') ? $model->getCopyParams() : $model->attributes; $this->title = Yii::t('modelMessageCategory ?>', ''); $this->params['breadcrumbs'][] = ['label' => Yii::t('modelMessageCategory ?>.plural', ''), 'url' => ['index']]; @@ -78,6 +77,7 @@ } ?> + enableCopy): ?> accessFilter) { echo 'getUser()->can(\'' . $permissions['update']['name'] . '\')): ?>'; @@ -85,7 +85,7 @@ ?> Html::a( ' ' . generateString('Copy ' . $modelName) ?>, - ['create', , 'modelClass) ?>'=>$copyParams], + ['create', , 'modelClass) ?>'=> $model->hasMethod('getCopyParams') ? $model->getCopyParams() : $model->attributes], ['class' => 'btn btn-success']) ?> '; } ?> + accessFilter) { From 38b96a82841bd09cce4ed9f09d26405b37c06e53 Mon Sep 17 00:00:00 2001 From: Tobias Munk Date: Tue, 26 Mar 2024 14:09:55 +0100 Subject: [PATCH 45/45] added artifacts --- .github/workflows/docker-image.yml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.github/workflows/docker-image.yml b/.github/workflows/docker-image.yml index 15add40..e6680db 100644 --- a/.github/workflows/docker-image.yml +++ b/.github/workflows/docker-image.yml @@ -19,3 +19,9 @@ jobs: cd tests make all make test + + - name: 'Upload Test Report' + uses: actions/upload-artifact@v4 + with: + path: tests/_output + retention-days: 7