Skip to content

Commit a08609d

Browse files
authored
Merge pull request #8050 from cakephp/fix-8049
Expand the enum docs
2 parents 55c353d + b10465d commit a08609d

File tree

1 file changed

+32
-2
lines changed

1 file changed

+32
-2
lines changed

en/orm/database-basics.rst

Lines changed: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -493,7 +493,7 @@ To use this type you need to specify which column is associated to which BackedE
493493
$this->getSchema()->setColumnType('status', EnumType::from(ArticleStatus::class));
494494
}
495495

496-
Where ``ArticleStatus`` contains something like::
496+
A simple ``ArticleStatus`` could look like::
497497

498498
namespace App\Model\Enum;
499499

@@ -503,6 +503,36 @@ Where ``ArticleStatus`` contains something like::
503503
case Unpublished = 'N';
504504
}
505505

506+
CakePHP also provides the ``EnumLabelInterface`` which can be implemented by
507+
Enums that want to provide a map of human-readable labels::
508+
509+
namespace App\Model\Enum;
510+
511+
use Cake\Database\Type\EnumLabelInterface;
512+
513+
enum ArticleStatus: string implements EnumLabelInterface
514+
{
515+
case Published = 'Y';
516+
case Unpublished = 'N';
517+
518+
public static function label(): string
519+
{
520+
return match ($this) {
521+
self::Published->value => __('Published'),
522+
self::Unpublished->value => __('Unpublished'),
523+
};
524+
}
525+
}
526+
527+
This can be useful if you want to use your enums in ``FormHelper`` select
528+
inputs. You can use `bake </bake>`_ to generate an enum class::
529+
530+
# generate an enum class with two cases and stored as an integer
531+
bin/cake bake enum UserStatus inactive:0,active:1 -i
532+
533+
# generate an enum class with two cases as a string
534+
bin/cake bake enum UserStatus published:Y,unpublished:N
535+
506536
CakePHP recommends a few conventions for enums:
507537

508538
- Enum classnames should follow ``{Entity}{ColumnName}`` style to enable
@@ -1100,7 +1130,7 @@ databases. For example to create a database::
11001130
.. note::
11011131

11021132
When creating a database it is a good idea to set the character set and
1103-
collation parameters (e.g. ``DEFAULT CHARACTER SET utf8mb4 DEFAULT COLLATE utf8mb4_unicode_ci``).
1133+
collation parameters (e.g. ``DEFAULT CHARACTER SET utf8mb4 DEFAULT COLLATE utf8mb4_unicode_ci``).
11041134
If these values are missing, the database will set whatever system default values it uses.
11051135

11061136
.. meta::

0 commit comments

Comments
 (0)