Warning: Cannot modify header information - headers already sent by (output started at /www/wwwroot/sbboke.com/wp-content/plugins/wordpress-seo/src/integrations/front-end-integration.php:409) in /www/wwwroot/sbboke.com/wp-content/themes/pacify/content-single.php on line 5

Magento 2:以自定义形式显示日历/ DatePicker和日期范围字段

本文介绍了如何在Magento 2中以任何自定义形式添加日历或日期选择器字段。

我将展示在Magento 2的模板文件(.phtml)中添加日期选择器的三种不同方式。

1)使用日历小部件
2)使用datepicker小部件
3)使用datetimepicker小部件

我还将展示如何在自定义表单中添加日期范围

显示日期选择器字段

首先,让我们看看我们的输入域代码。日期字段命名为my-date

<input type="text" 
    class="input-text required-entry hasDatepicker" 
    id="my-date" 
    name="my-date"
    aria-required="true" />

现在,我们只需在表单结束标记之后添加Javascript代码即可。

1)使用日历小部件

<script>
require([
    'jquery',
    'mage/mage',
    'mage/calendar'
], function($){
    $('#my-date').calendar({
        // show date
        changeYear: true,
        changeMonth: true,
        yearRange: '1970:2050',
        buttonText: 'Select Date',
        
        // show time as well
        timeInput: true,
        timeFormat: 'HH:mm:ss',
        showsTime: true
    });
});
</script>

2)使用日期选择器小部件

<script>
require([
    'jquery',
    'mage/mage',
    'mage/calendar'
], function($){
    $('#my-date').datepicker({
        dateFormat: 'd/m/yy',
        changeMonth: true,
        changeYear: true
    });
});
</script>

3)使用datetimepicker小部件

<script>
require([
    'jquery',
    'mage/mage',
    'mage/calendar'
], function($){
    $('#my-date').datetimepicker({
        dateFormat: 'd/m/yy',
        timeFormat: 'HH:mm:ss',
        changeMonth: true,
        changeYear: true,
        showsTime: true
    });
});
</script>

显示日期范围字段

为了显示日期范围字段,首先,我们需要为日期范围添加两个字段,即from-date和to-date输入文本字段。

<div class="field overview required" id="date-range">
    <label for="from" class="label">
        <span>From date</span>
    </label>
    <div class="control">
        <input class="input-text required-entry"
            type="text"
            id="date-from"
            name="from" />
    </div>
 
    <label for="to" class="label">
        <span>To date</span>
    </label>
    <div class="control">
        <input class="input-text required-entry"
            type="text"
            id="date-to"
            name="to" />
    </div>
</div>

在表单中定义了from和to date字段之后,我们可以在文件末尾(即form标记结束后)编写以下javascript代码。

<script>
require([
    'jquery',
    'mage/mage',
    'mage/calendar'
], function($){
    $('#date-range').dateRange({
        buttonText: 'Select Date',
        from: {
            id: 'date-from'
        },
        to: {
            id: 'date-to'
        }
    });
});
</script>

Calendar / date-picker JS文件存在于Magento文件夹中的文件lib / web / mage / calendar.js中。您可以查看该文件以查找可以添加到日历/日期选择器的更多选项。

希望这可以帮助。谢谢。

相关文章

0 0 投票数
文章评分
订阅评论
提醒
0 评论
内联反馈
查看所有评论