Kai*_*las 8 yii2 yii2-advanced-app
我正在使用Kartik DateTimePicker扩展
<?= $form->field($model, 'Created')->widget(DateTimePicker::classname(),[
'model' => $model,
'attribute' => 'Created',
'name' => 'Created',
'options' => ['placeholder' => 'Select Created'],
'pluginOptions' => [
'format' => 'dd-mm-yyyy hh:ii:ss',
'todayHighlight' => true
]
])
?>
Run Code Online (Sandbox Code Playgroud)
用户填写格式为的创建日期
dmY H:我:s(如24-09-2015 11:21:10)
但是当记录保存到数据库然后创建日期格式更改为
Ymd H:我:s(比如2015-09-24 11:21:10)
如何在保存/更新记录时更改日期格式
最后我使用AttributeBehavior找到了答案。
在我的模型类中,我编写了行为代码:
public function behaviors()
{
return [
[
'class' => AttributeBehavior::className(),
'attributes' => [
// update 1 attribute 'created' OR multiple attribute ['created','updated']
ActiveRecord::EVENT_BEFORE_INSERT => ['created','updated'],
ActiveRecord::EVENT_BEFORE_UPDATE => 'updated',
],
'value' => function ($event) {
return date('Y-m-d H:i:s', strtotime($this->Created));
},
],
];
}
Run Code Online (Sandbox Code Playgroud)
我的模特班
namespace frontend\models;
use Yii;
use yii\db\ActiveRecord;
use yii\behaviors\AttributeBehavior;
/**
* This is the model class for table "product".
*
* @property integer $id
* @property integer $product_id
* @property string $product_name
* @property string $created
* @property string $updated
*/
class Product extends ActiveRecord
{
public $csv_file;
/**
* @inheritdoc
*/
public static function tableName()
{
return 'product';
}
public function behaviors()
{
return [
[
'class' => AttributeBehavior::className(),
'attributes' => [
ActiveRecord::EVENT_BEFORE_INSERT => ['created','updated'], // update 1 attribute 'created' OR multiple attribute ['created','updated']
ActiveRecord::EVENT_BEFORE_UPDATE => 'updated', // update 1 attribute 'created' OR multiple attribute ['created','updated']
],
'value' => function ($event) {
return date('Y-m-d H:i:s', strtotime($this->LastUpdated));
},
],
];
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['id', 'product_id', 'product_name', created, updated], 'required'],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'product_id' => 'Product ID',
'product_name' => 'Product Name',
'created' => 'Created',
'updated' => 'Updated',
];
}
}
Run Code Online (Sandbox Code Playgroud)
如果输入格式为d/m/Y则需要将“/”替换为“-”
例如:输入日期(创建):10/09/2015
date('Y-m-d H:i:s', strtotime(str_replace("/","-",$this->created)));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14795 次 |
| 最近记录: |