Date pickers are mainly needed when it is required to pick a not-yet-known date in context for a specific event or schedule some plan. It doesn’t only reduce typing errors but also standardize the format. It also helps to improve the user experience by allowing users to simply selection rather than inputting using the keyboard.
Today, I have come up with the simple custom code to add date picker in Magento 2 custom form.
There may be a requirement of date picker in the frontend or the backend form. Usually jQuery is used for the same. But here, we have used Magento 2 library to add date picker both in admin and frontend custom form.
Code to Add Date Picker in Magento 2 Custom Form
<div class="field "> <label class="field-label"> <span><?php echo __(' Date Picker')?></span> </label> <div class="field-control "> <input class="control-text" name="datepicker" id="datepicker" type="text"> </div> </div>
Now run the following code:
<script type="text/javascript"> require(["jquery", "mage/calendar"], function ($) { $('#datepicker').datepicker({ prevText: '<zurück', prevStatus: '', prevJumpText: '<<', prevJumpStatus: '', nextText: 'Vor>', nextStatus: '', nextJumpText: '>>', nextJumpStatus: '', monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], dayNames: ['Sunday ', 'Monday', 'Tuesday ', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], dayNamesMin: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], showMonthAfterYear: false, dateFormat: 'd/m/yy' } ); }); </script>
Happy Coding!