What’s the standard way to get rid of the three <select> elements and allow users to just type dates in a regular <input type="text"> control?
Requirements include:
- Date format must be D/M/Y
- Existing dates must be printed correctly
- Cannot break date validation
I cannot find any reasonable documentation on this, just hacks in forum threads written by users as clueless as me xD
Clarification: Please note the CakePHP tag. I already know how to handle dates in regular PHP. I need help about the precise CakePHP mechanism I can use to adjust the framework’s default functionality (and I really mean adjust rather than override).
So far, I’ve added this to the model:
public $validate = array(
'fecha' => array(
array(
'rule' => 'notEmpty',
'required' => true,
),
array(
'rule' => array('date', 'dmy'),
),
)
);
… and I’ve composed the field like this inside the view:
echo $this->Form->input(
'Foo.fecha',
array(
'type' => 'text',
)
);
… but all I can do with this is reading and validating user input: it won’t print previous date properly and it won’t store new date properly.
Here’s a summary of my findings. It seems that the appropriate mechanism is using Model Callback Methods to switch between two date formats:
2012-08-2828/08/2012Steps:
AppModelto convert between my custom format (aka “display format”) and MySQL’s default format (aka “DB format”).afterFind()filter to my model that converts to display format when read from DB.'type' => 'text'.'rule' => array('date', 'dmy')validation rule to the field inside the model.beforeSave()filter to my model that converts to DB format right before saving.These steps can be encapsulated with a behaviour that implements the
afterFind()andbeforeSave()callbacks and possibly some others likebeforeFind(). The behaviour can be applied directly toAppModeland will take care of traversing data arrays to convert dates between both formats (if the model has an attached table). The code is not trivial but can be done and it makes it all transparent.Drawbacks:
It would be more rock-solid to be able to use three formats:
2012-08-2828/08/2012DateTimeobjectsSadly, the CakePHP core is not designed for that and it all starts getting too complicate if you attemp to implement it this way.