How to Add Date Picker in Magento 2 Custom Form
Featured In - Magento 2,
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.
Add Date Picker in Magento 2 Custom Form by implementing the below code:
1 2 3 4 5 6 7 8 | <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> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <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> |
That’s all! You have added date picker in Magento 2 custom form without using jQuery. Feel free to ask any doubts regarding the topic in the comments section.
Rate the post with 5 stars 🙂
Happy Coding!
6 Comments
How to add datepicker in admin form that is php file above code is for phtml file please suggest
Hello,
Please subscribe to our daily blog posts to get notified when we post your required solution.
Thank you.
Perfect, thanks!
[FYI Small typo, missing quote mark in $(‘#datepicker)]
Hey,
Thanks for drawing my attention.
I’ve updated the post 🙂
How to add the datepicker field in checkout?
Hello Siva,
You’ll have to follow the method at https://meetanshi.com/blog/add-custom-field-in-address-form-in-magento-2/ to add the datepicker field in checkout.