我是drupal的新手..我在Drupal7中有一个表单,它必须移动到drupal8。该表单包括两个日期字段-一个开始日期和一个结束日期。日期类型为'date_popup‘。
我想让to_date自动更改为from_date。我已经附上了js脚本和表单模块。日期没有显示在屏幕上。我是不是漏掉了什么?
PHP
public function buildForm(array $form, FormStateInterface $form_state) {
$form['suggested_date'] =
array(
'#type' => 'date_popup',
'#title' => t('F Date:'),
);
$default_from = date('Y-m-d 00:00:00', strtotime(date('Y-m-d')." +1 month"));
$form['from_date'] = array(
'#title' => t('from'),
'#type' => 'date_popup',
'#date_format' => 'd/m/Y',
'#default_value' => $default_from,
'#datepicker_options' => array('minDate' => 'today'),
'#required' => TRUE,
);
$form['to_date'] = array(
'#title' => t('today'),
'#type' => 'date_popup',
'#date_format' => 'd/m/Y',
'#default_value' => date('Y-m-d 00:00:00', strtotime($default_from." +1 day")),
'#datepicker_options' => array('minDate' => date('d/m/Y', strtotime($default_from." +1 day"))),
'#required' => TRUE,
);
return $form;
}JS script
(function($) {
Drupal.behaviors.testdate = {
attach: function(context, settings) {
$('#edit-from-date', context).change(function() {
$('#edit-to-date', context).val($(this).val());
var field_date1 =$('#edit-to-date', context).val($(this).val());
console.log(field_date1);
});
}
}
})(jQuery);Module
function testdate_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
$form['#attached']['library'][] = drupal_get_path('module', 'testdate') . 'date_picker.js';
}发布于 2021-03-15 00:48:45
您必须定义一个包含js文件的库,并将其附加到表单:
testdate.libraries.yml
date_picker:
version: VERSION
js:
date_picker.js: {}YourForm.php
public function buildForm(array $form, FormStateInterface $form_state) {
// Your current logic
$form['#attached']['library'][] = 'testdate/date_picker'; // 'module_name/library_name'
return $form;
}而且您不应该在未选中form_id的情况下使用hook_form_alter,因为您会将库附加到所有表单。相反,您可以像上面那样直接在function buildForm()中附加库。
更新:
表单元素类型date_popup在Drupal8中不存在。请改用date。您可以查看受支持的类型here
https://stackoverflow.com/questions/66619646
复制相似问题