</> Code The Pixel

CakePHP 4 jQuery Date Time Picker

Asyraf Wahi Anuar - October 01, 2018

Estimated reading time: 1 minute, 56 seconds

Date Picker is one of the most important features in web-based applications to enhance the user experience, especially when inputting date and time. Technically, CakePHP supports a native HTML5 date picker that can be called using 'type' => 'Date' but the picker needs to be clicked at caret symbol then the calendar will pop up. To enhance the user friendly and experience, I recommended using the jQuery date picker. 

1. Download the jQuery Plugin Date and Time Picker

2. The date-time CSS and JS should be properly placed at respective folder at webroot-CSS & webroot-js

3. Insert the following code to call the CSS and JS to the page that you want to use date time picker. Those codes should be loaded at the top of the coding page.

<?php
	echo $this->Html->css('jquery.datetimepicker');
	echo $this->Html->script('jquery.datetimepicker.full.js');
?>


4. Next, identify your input name for the date time picker and the location of the date-time picker should appear. EG: your input name is 'publish_on', so the code should be as shown below:

<?php echo $this->Form->control('publish_on',[
	'class' => 'form-control datepicker-here', 
	'label' => 'Publish On',
	'id' => 'publish_on',
	'type' => 'Text',
	'data-language' => 'en',
	'data-date-format' => 'Y-m-d',
	'value' => date('Y-m-d'),
	'empty'=>'empty',
	'required' => false,
	'autocomplete' => 'off'
]); ?>

<script type="text/javascript">
$('#publish_on').datetimepicker({
	lang:'en',
	timepicker:false,
	format:'Y-m-d',
	formatDate:'Y/m/d',
	//minDate:'-1970/01/01', // yesterday is minimum date
	//maxDate:'+1970/01/02' // and tommorow is maximum date calendar
});

</script>


5. Now, check your input name to ensure that you've correctly configured the date picker. At line number 2, 5 and 14 must use the same variable (input name) to ensure that the script is able to identify and call the JS function for the date picker. Refresh your page and the output of the date picker will be shown as below:


6. If in the edit page, use 'value' attributes to read existing date/time:

<?php echo $this->Form->control('publish_on',[
	'class' => 'form-control datepicker-here', 
	'label' => 'Publish On',
	'id' => 'publish_on',
	'type' => 'Text',
	'value' => date('Y-m-d', strtotime($article->publish_on)),
	'data-language' => 'en',
	'data-date-format' => 'Y-m-d',
	'empty'=>'empty',
	'required' => false,
	'autocomplete' => 'off'
]); ?>

 


Cite this article (APA 6th Edition)

Popular
CakePHP 4 Print PDF Using CakePDF
May, 17 2020
CakePHP 4 Authentication Using Auth...
May, 14 2020
CakePHP 4 jQuery Date Time Picker
October, 01 2018
CakePHP 4 Export To CSV
May, 29 2020
CakePHP 4 Authentication Using...
May, 11 2020
CakePHP 4 File Upload Using Proffer Plugin
May, 15 2020
CakePHP 4 Find, Sort & Count
June, 02 2020
Share
Sharing Link
Click the icon to share