欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

Add a pop-up calendar on a date textfield in a custom Drupal 7 Form

shiping1 的头像

I found out you can add a pop-up calendar easily enough with the Date Pop-up submodule of the Date module, but I have used the (wonderful!) Date module enough times to know it adds a lot of overhead.  Since I did not need the date module for anything else on the site preferred to stay lightweight.

Handy enough, Drupal comes packaged with the jQuery UI Datepicker control which is exactly what I need (tip-of-the-hat goes to the Better Exposed Filters module which I vaguely recalled having a pop-up calendar sans-Date module dependency and that allowed me to track down how they did it).

Once I was on the ui.datepicker trail, finding help was not so hard.  I used the directions there and some trial and error to put this together:

function MODULE_example_form($form, &$form_state) {
  $form['finished_between'] = array(
    '#type' => 'item',
    '#title' => 'Finished between',
    'finished_after' => array(
      '#type' => 'textfield',
      '#attributes' => array('class' => array('datepicker')),
    ),
    'finished_before' => array(
      '#type' => 'textfield',
      '#title' => 'and',
      '#attributes' => array('class' => array('datepicker')),
    ),
  );
  
  $form['#after_build'] = array('MODULE_example_form_uidatepicker');
  
  $form['submit'] = array(
    '#type' => 'submit', 
    '#value' => t('Filter'),
  );
  ...
  
  return $form;
}

function MODULE_example_form_uidatepicker($form, $form_state) {
  drupal_add_library('system', 'ui.datepicker');
  drupal_add_js("(function ($) { $('.datepicker').datepicker(); })(jQuery);", array('type' => 'inline', 'scope' => 'footer', 'weight' => 5));
  return $form;
}

 

The #after_build function is super handy - just be sure to return the $form variable or your form will not display (or if you attach it to an element, returning the $element seems to be the right option (though not a lot of documentation here!)



来自  http://www.covenantdesign.com/blog/add-pop-calendar-date-textfield-custom-drupal-7-form

普通分类: