How to auto set a value from URL in form alter hook

Submitted by Daniel Henry on 06/07/2013 - 12:09:pm
I’ve had several recent projects where I wanted the user to be able to create a node but with one of the fields set by default based on a URL parameter. So here is the snippet for that.
 
First, use a form alter hook to pull the value from the URL. Then validate it as URL input is not safe by default. Set the fields new default value, and hide the field from the user. Since this is a standard fields API field the default submit handler will take care of the rest.
 
  1. /**
  2.  * Implements hook_form_FORM_ID_alter().
  3.  */
  4. function my_module_form_question_node_form_alter(&$form, $form_state) {
  5.   $question_type = $_GET['question_type'];
  6.   $question_types = array('advice', 'support');
  7.  
  8.   if (in_array($question_type, $question_types)) {
  9.     $form['field_type'][LANGUAGE_NONE]['#default_value'][0] = $question_type;
  10.   }
  11.   $form['field_type'][LANGUAGE_NONE]['#type'] = 'value';
  12. }

Second, create a link to the node create page. 

The following snippet can be passed into theme_links:

  1. links['level-2 question create'] = array(
  2.   'title' => t('Ask the helpdesk for technical support'),
  3.   'href' => 'node/add/question',
  4.   'query' => array('question_type' => 'helpdesk'),
  5.   'attributes' => array(
  6.     'class' => array('question', 'helpdesk', 'create'),
  7.   ),
  8. );
 
Happy Coding!