datedrupaldrupal-7drupal-webformdrupal-hooks

Webform form alter date hide day


I'm relatively new to Drupal 7 and I'm trying to create a custom webform. My goal is to add a date (provided by the date module) field with out the day option. So it displays on month and year hiding the day option.

I have managed to achieve this but only by recreating the wholedate field as a custom field but I wanted to know if it was possible to customize the date field provided by the date module.

Below is a screen shot of my form: enter image description here

How I create my custom date field:

function my_webform_form_alter(&$form, &$form_state) {

      if (isset($form['#node']->webform) && $form['#node']->uuid == '00b20537-d5ce-45c2-af37-150c9e73b96d') {

           //$form['submitted']['date']['#type'] = 'hidden';

           $form['ggg'] = array(
            '#type' => 'date_select',
            '#title' => 'Date',
            '#date_format' => 'm/Y',
            '#default_value' => date('Y-m-d')
          );


      }
    }

I have tried other methods on hiding the field components but nothing seem to work so far. I was wondering if I needed to implement a hook different from the alter hook (the one being used).

Any suggestions on how to achieve this?


Solution

  • A possible solution would be to transform the day field of the date component to a hidden field instead of the select field type. That can be achieved by adding a #process callback for that field and altering the data.

    function YOURMODULE_form_alter(&$form, &$form_state, $form_id)
    {
        // Your logic here depending which form to alter
        // ...
    
        // Add #process for the component with key name 'date'
        $form['submitted']['date']['#process'][] = 'YOURMODULE_process_date';
    }
    
    function YOURMODULE_process_date(&$element)
    {
        // change type to hidden
        $element['day']['#type'] = 'hidden';
    
        // set value to first day of the month
        $element['day']['#value'] = '1';
    
        return $element;
    }