Reputation: 1105
I am trying to use JQuery's datepicker with CakePHP. I can't seem to figure out how to do this while also using CakePHP's built in date validation and allowing for any date format. Any answers I've come across involve complicated solutions. I get the feeling that there must be a simple way to do this, seems how a JQuery datepicker is a common enough thing.
Currently, I am attempting this by converting the date into the CakePHP date array format
array( 'day' => '21', 'month' => '3', 'year' => '1993' )
This is causing issues when invalid data is entered. It puts two spaces in any empty date fields, and strtotime counts spaces as 'now'. So if invalid data is entered, and the user resends the data, it causes any empty date fields (that are not required) to be saved as today's date.
Any ideas?
Upvotes: 3
Views: 2852
Reputation: 3772
Try something like this:
In Model:
/*...*/
$validate = array(
'your_date' => array(
'date' => array(
//Add 'ymd' to the rule.
'rule' => array('date', 'ymd'),
'message' => 'Please select a valid birth date.',
),
),
);
/*...*/
In Controller:
//Put into a function so you can reuse the same code.
function convertDates( &$data ){
if (!empty($data['date_of_birth']) && strtotime($data['date_of_birth']) ){
$data['date_of_birth'] = date('Y-m-d', strtotime($data['date_of_birth']));
}
}
Function where you call the above function:
public function add() {
/*...*/
//Convert the dates to YYYY-MM-DD format before attempting to save.
$this->convertDates( $this->request->data['ModelName'] );
/*...*/
}
In View:
/*...*/
//Make input form a text field, and give it a class of datepicker (or whatever).
echo $this->Form->input('date_of_birth', array(
'class'=>'datepicker', 'type'=>'text','label'=>'Date of Birth'
)
);
/*...*/
And then add your initialization script at the bottom:
<script>
//Initialize your datepicker at the bottom.
$(document).ready(function() {
$( "input.datepicker" ).datepicker({
yearRange: "-100:+50",
changeMonth: true,
changeYear: true,
constrainInput: false,
showOn: 'both',
buttonImage: "/img/calendar.png",
buttonImageOnly: true
});
});
</script>
Upvotes: 1