[英]Laravel dates on form model binding
我正在使用Laravel 5.1
我有一个模型:
class ExampleModel extends Model {
// ....
protected $dateFormat = 'Y.m.d';
protected $dates = ['first_date', 'second_date'];
// ...
}
因此,当我索引ExampleModel元素时,日期格式是正确的(ex 2015.07.31)
但在编辑表单中,它使用默认格式:2015-07-31 00:00:00
我正在使用Form::model()
绑定。
我知道我可以使用getFirstDateAttribute()
但它不是我正在寻找的解决方案。 因为它根本不优雅,一旦我定义了$dates
数组,它应该在每种情况下自动工作。
这可能是个错误吗? 或者我做错了什么?
我通过覆盖Carbon的默认日期格式解决了我的问题:
Carbon\Carbon::setToStringFormat('Y.m.d');
但凯利的回答更好,更优雅,我也发布了这个,也许有人会发现这个有用一次。
我以前从未这样做过,但它似乎与我放在一起的一个基本例子有关。 请注意,我只是在表单开始标记中调用模型上的toArray
方法。
{!! Form::model($exampleModel->toArray(), ['route' => ['example-models.update', $exampleModel->id]]) !!}
{!! Form::label('first_date', 'First Date') !!}
{!! Form::text('first_date') !!}
{!! Form::close() !!}
文档说dateFormat
属性确定将对象dateFormat
转换为json或数组时的日期格式。
我没有完全建议将其作为修复,因为当您更新核心时,您将失去此修复程序,但也许这应该作为拉动请求发布到Laravel的下一个版本。
在\\ Illuminate \\ Database \\ Eloquent \\ Concerns \\ HasAttributes中更新asDate函数,如下所示。 从注释中可以看出,asDate函数仍然返回时间戳,即使它是00:00:00。
/**
* Return a timestamp as DateTime object with time set to 00:00:00.
*
* @param mixed $value
* @return \Illuminate\Support\Carbon
*/
protected function asDate($value)
{
$date = $this->asDateTime($value)->startOfDay();
$date->setToStringFormat($this->getDateFormat());
return $date;
}
这允许您从模型中控制日期的格式(注意我区分日期和日期时间)。 然后使用casts变量将变量转换为日期格式。
protected $casts = [
'start_date' => 'date',
'end_date' => 'date'
];
protected $dateFormat = 'Y-m-d';
$ dates变量无法区分日期和日期时间。
更新真正的问题是表单模型绑定跳过了FormBuilder类的辅助函数。 如您所见,检查\\ Collective \\ Html \\ FormBuilder :: date
/**
* Create a date input field.
*
* @param string $name
* @param string $value
* @param array $options
*
* @return \Illuminate\Support\HtmlString
*/
public function date($name, $value = null, $options = [])
{
if ($value instanceof DateTime) {
$value = $value->format('Y-m-d');
}
return $this->input('date', $name, $value, $options);
}
正确地将日期格式化为HTML格式中指定的'Ymd'。 但是在这一点上,$ value实际上是null。 所以你必须更新通用输入功能。
/**
* Create a form input field.
*
* @param string $type
* @param string $name
* @param string $value
* @param array $options
*
* @return \Illuminate\Support\HtmlString
*/
public function input($type, $name, $value = null, $options = [])
{
...
//$value is null here
if (! in_array($type, $this->skipValueTypes)) {
//$value is fetched based on hierarchy set by
$value = $this->getValueAttribute($name, $value);
//necessary duplicate code to format date value
if ($type == 'date' && $value instanceof DateTime) {
$value = $value->format('Y-m-d');
}
}
...
}
更新无需更新供应商代码。 查看FormModelAccessors
https://laravelcollective.com/docs/5.2/html#form-model-binding
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.