What is the best way to handle complex data types in CakePHP?

My goal: replace default date cake mark

I don't like CakePHP FormHelper's default selection elements, and I would like to use the jQuery UI Datepicker widget. To degrade competently, I want to have a date field (enabled with a widget) and a timer selection field limited to 15-minute increments.

In case I explain it badly, here is what it looks like:

date-picker sample

My perfect solution

To minimize repetition, I want to put HTML in an Element element and process it using the Behavior function. That way I could do something like the following:

view.ctp

echo $this->element( 'datepicker', array( 'data' => $data ) ); 

model.php

 $actsAs = array( 'Datepicker' ); function beforeSave( $options ){ $this->parseDatepickers(); //behavior function would alter $this->data return true; } 

Problem

Unfortunately, by the time the beforeSave (or beforeValidate ) callback was received, the datepicker and timepicker fields were destroyed by the deconstruct function. deconstruct seems to be looking for dates and times to tell how FormHelper creates them.

In short, he is looking for:

 [date_field] => Array ( [year] => 2011 [month] => 11 [day] => 11 [hour] => 8 [min] => 00 [meridian] => pm ) 

but instead he finds:

 [date_field] => Array ( [datepicker] => 11/11/2011 [timepicker] => 8:00 pm ) 

And since it does not find the structure that it expects, I get the following:

 [date_field] => 

I know that I can have hidden jQuery attachments with corresponding fields, but that would not get worse.

Current workaround

What I am doing currently erases the data through my behavior function before saving - but this does not seem to be the correct way to do this:

 $this->request->data = $this->Event->fixDates( $this->data ); $this->Event->save( $this->data ); 

So...............

What is the best way to do this? Putting it in beforeSave or beforeValidate seems like an "empty way", but deconstruct kills me. Do I need to extend AppModel and override deconstruct ? That also seems ugly.

+8
date cakephp
source share
1 answer

I usually make my date fields as text fields in the view to override the default Form Helper output, and then use jQuery date picker (or any other alternative selector) to set the date:

 echo $this->Form->input('date', array('type' => 'text', 'class' => 'datepicker')); 

This will result in a typical tag, and not all drop-down lists.

Then, in my beforeSave function of the model, I change the format to the MySQL formatting date:

 $this->data['Model']['date'] = date('Ymd G:i:s', strtotime($this->data['Model']['date'])); 

(don't forget to return true in beforeSave)

This works with the correct datetime data type in the database, and it looks like what you are trying to do.

+2
source share

All Articles