d3yii2/yii2-datetime

该包最新版本(1.1.1)没有可用的许可证信息。

为 Yii 2.0 框架添加日期和时间辅助函数和行为的 Yii2 扩展

安装: 174

依赖者: 1

建议者: 0

安全性: 0

星标: 0

关注者: 2

分支: 5

类型:yii2-extension

1.1.1 2016-09-04 11:56 UTC

This package is auto-updated.

Last update: 2024-09-20 03:04:27 UTC


README

此扩展可以帮助您处理 Yii 框架 2.0 模型的日期和时间属性

安装

安装此扩展的首选方式是通过 composer

运行

php composer.phar require --prefer-dist omnilight/yii2-datetime "*"

或者

"omnilight/yii2-datetime": "*"

将此添加到您的 composer.json 的 require 部分。

为什么?

当与模型和表单一起工作时,通常需要为用户提供一种编辑包含日期和/或时间的属性的方法。在这种情况下,典型的问题包括

  1. 数据库和显示表单中的日期/时间格式可能不同(例如,由于本地设置)
  2. 您应该验证用户输入的值

因此,您需要为数据库、表单设置正确的格式,某种方式将这些格式相互转换,并且最好能够一次性(在应用程序级别)设置正确的格式,以后不必担心。此扩展在此领域提供帮助。

想法

想法是对于模型中每个可编辑的日期/时间属性都有一个单独的属性,该属性将在表单中使用。此属性不会存储在数据库中,但将用于向用户提供正确格式的值。当您为该属性分配值时,它将自动转换并分配给模型的数据库属性。

此扩展提供特殊行为,自动处理这些属性

如何使用

在您的模型中

/**
 * @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 属性,并将其转换为数据库存储的属性。

您还可以为每个属性定义单独的配置,并定义其本地名称、格式等。