开发者

CakePHP Form Helper and Datetime

I have used the form helper to create a date time selection and when I access the $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'] = $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). 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.


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. Not a problem if you use a datepicker.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜