omnilight / yii2-datetime
Yii2扩展,为处理日期和时间添加辅助工具和行为
Requires
- php: >=5.4.0
- yiisoft/yii2: *
This package is auto-updated.
Last update: 2024-09-16 04:31:32 UTC
README
本扩展帮助您处理Yii框架2.0中模型的日期和时间属性
安装
安装此扩展的首选方式是通过composer。
运行以下命令之一:
php composer.phar require --prefer-dist omnilight/yii2-datetime "*"
或者
"omnilight/yii2-datetime": "*"
将以下内容添加到您的composer.json文件的require部分。
为什么?
在与模型和表单一起工作时,通常需要为用户提供一种编辑包含日期和/或时间的属性的方法。在这种情况下,典型的问题包括
- 数据库和显示表单中的日期/时间格式可能不同(例如,由于本地设置)
- 您应该验证用户输入的值
因此,您必须为数据库和表单设置正确的格式,将它们从一种格式转换为另一种格式,并且如果您可以在应用级别上设置一次正确的格式,那么以后就不用担心这些问题了。本扩展在这个领域提供帮助。
理念
理念是对于模型中每个可编辑的日期/时间属性,都有一个单独的属性,该属性将用于表单。此属性不会存储在数据库中,但它将用于向用户提供正确格式的值。当您为此属性分配值时,它将自动转换并分配给模型的数据库属性。
本扩展提供特殊的行为,以自动处理这些属性
如何使用
在您的模型中
/** * @property string posted_at This is your property that you have in the database table, it has DATETIME format */ class Post extends ActiveRecord { // ... Some code here public function behaviors() { return [ 'datetime' => [ 'class' => DateTimeBehavior::className(), // Our behavior 'attributes' => [ 'posted_at', // List all editable date/time attributes ], ] ]; } }
现在在您的视图中使用表单
// $model has instance of Post <?= $form->field($model, 'posted_at_local')->widget(\yii\jui\DatePicker::className(), \omnilight\datetime\DatePickerConfig::get($model, 'posted_at_local')) ?> // DatePickerConfig is used to properly configure widget. Currently it only supports DatePicker from the Jui extension
这就完成了!用户将以本地格式输入日期,并将其自动转换为数据库格式。
它是如何工作的
行为为在'attributes'部分中定义的每个属性创建一个名为attribute_name_local的"虚拟"属性。当您读取$yourModel->attribute_name_local时,行为将返回一个类型为DateTimeAttribute的对象。如果此对象在字符串上下文中使用,它将通过魔法__toString方法转换为字符串。并且在这个过程中,原始的attribute_name值将转换为本地表示。
当您将值分配给$yourModel->attribute_name_local时,它将内部分配给DateTimeAttribute类的value属性,并转换为数据库存储的属性。
您还可以为每个属性定义单独的配置,并定义它的本地名称、格式等。