简体   繁体   English

CakePHP表单帮助器和日期时间

[英]CakePHP Form Helper and Datetime

I have used the form helper to create a date time selection and when I access the $this->data . 我使用表单助手创建日期时间选择以及访问$this->data

It looks like the following. 看起来如下。

[Timetable] => Array
    (
        [event_id] => 133
        [location_id] => 39
        [start] => Array
            (
                [hour] => 09
                [min] => 06
                [day] => 11
                [month] => 03
                [year] => 2011
            )

    )

But I want this to look more like this... 但我希望它看起来更像这样...

[Timetable] => Array
    (
        [event_id] => 133
        [location_id] => 39
        [start] => 2011-03-11 09:06:00

    )

Is there a way to transform it to this? 有没有办法将其转换成这种形式?

You can just rebuild the $this->data['Timetable']['start'] var in your controller like so: 您可以在控制器中重建$this->data['Timetable']['start'] var,如下所示:

$this->data['Timetable']['start'] = $this->data['Timetable']['start']['year']
    .'-'.$this->data['Timetable']['start']['month']
    .'-'.$this->data['Timetable']['start']['day']
    .' '.$this->data['Timetable']['start']['hour']
    .':'.$this->data['Timetable']['start']['min'];

Should work fine. 应该工作正常。

This is undocumented in the Cookbook, but the function the model uses to convert that array into a database-friendly format is Model::deconstruct($field, $data) . 这在Cookbook中没有记载,但是模型用来将该数组转换为数据库友好格式的函数是Model::deconstruct($field, $data) You can use it as follows: 您可以按以下方式使用它:

$startAsString = $this->Timetable->deconstruct(
    'start', $this->data['Timetable']['start']
);

This solution has the benefit of not breaking the MVC abstraction by having your controller know anything about the structure of data submitted by a form or how the database stores it. 此解决方案的好处是,不让控制器知道有关表单提交的数据的结构或数据库如何存储它的信息,而不会破坏MVC抽象。

Since you're using the form helper to generate your code, you can't get it into a single index unless you change your form helper. 由于您使用的是表单帮助程序来生成代码,因此除非更改表单帮助程序,否则无法将其放入单个索引中。

You're probably using 您可能正在使用

$this->Form->input('start')

Changing it to the below will make it come out the way you want. 将其更改为以下内容将使其以您想要的方式显示。

$this->Form->input('start', array('type'=>'text'));

However, if you do this, you'll lose out on all the dropdowns that cake auto generates for you. 但是,如果执行此操作,您将失去Cake自动为您生成的所有下拉菜单。 Not a problem if you use a datepicker. 如果您使用日期选择器,这不是问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM