diff --git a/CHANGELOG.md b/CHANGELOG.md index 509fa8d70..7b9c76af4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ Yii Framework 2 gii extension Change Log ----------------------- - Bug #532: Return `ExitCode::USAGE` on command input validation error (egmsystems) +- Enh #537: Generating rules for the fields with default values (manky) 2.2.6 May 22, 2023 diff --git a/src/generators/model/Generator.php b/src/generators/model/Generator.php index 20eec2d63..4121cab79 100644 --- a/src/generators/model/Generator.php +++ b/src/generators/model/Generator.php @@ -438,12 +438,21 @@ public function generateRules($table) { $types = []; $lengths = []; + $nullable = []; + $defaultValues = []; foreach ($table->columns as $column) { if ($column->autoIncrement) { continue; } if (!$column->allowNull && $column->defaultValue === null) { $types['required'][] = $column->name; + } elseif ($column->allowNull && $column->defaultValue === null) { + $nullable[] = $column->name; + } elseif (is_scalar($column->defaultValue)) { + if (array_key_exists($column->defaultValue, $defaultValues)) { + $defaultValues[$column->defaultValue] = []; + } + $defaultValues[$column->defaultValue][] = $column->name; } switch ($column->type) { case Schema::TYPE_SMALLINT: @@ -477,6 +486,15 @@ public function generateRules($table) } } $rules = []; + if (!empty($nullable)) { + $rules[] = "[['" . implode("', '", $nullable) . "'], 'default', 'value' => null]"; + } + if (!empty($defaultValues)) { + foreach ($defaultValues as $defaultValue => $defaultValueColumns) { + $defaultValue = is_numeric($defaultValue) ? $defaultValue : "'$defaultValue'"; + $rules[] = "[['" . implode("', '", $defaultValueColumns) . "'], 'default', 'value' => $defaultValue]"; + } + } $driverName = $this->getDbDriverName(); foreach ($types as $type => $columns) { if ($driverName === 'pgsql' && $type === 'integer') {