Tell me more ×
Drupal Answers is a question and answer site for Drupal developers and administrators. It's 100% free, no registration required.

I have a piece of code that I want to have the default value be a variable, but I need to know how to set a default value if the variable is not set:

  $form['background_audio_height'] = array(
'#type' => 'textfield',
'#title' => t('Subject'),
'#default_value' => variable_get('background_audio_upload_path'),
'#size' => 5,
'#maxlength' => 3,
'#required' => TRUE,
);

How can I set a default value if background_audio_upload_path is not set?

share|improve this question

3 Answers

up vote 6 down vote accepted

You can pass a second variable to the variable_get() function, which is a default value.

example:

variable_get('background_audio_upload_path', 'path/to/foo.bar');
share|improve this answer

If you're doing many operations with variables, consider using Variable module.

Once setup, it will save your time a lot. One of the problem that it will fix for you is the default value of the variable which you will need to change only in one place, instead of going through all the code. It will also provide you a configuration form for your variables for free.

share|improve this answer
<?php

function my_module_menu() {
  $menu['my_form_page/%'] = array
  (
    'title' => 'My Form',
    'page callback' => 'my_form_page',
    'page arguments' => array(1),
    'access callback' => TRUE,
  );
  return $menu;
}

function my_module_load_data($item_id) {
  return db_query('SELECT value1 FROM {some_table} WHERE item_id = :item_id', array(':item_id' => $item_id))->fetchObject();
}

function my_form_page($item_id) {
  $my_object = my_module_load_data($item_id);
  return drupal_get_form('my_form', $my_object);
}

function my_form($form, &$form_state, $my_object) {
  $form['element1'] = array(
    '#type' => 'textfield',
    '#title' => t('Item 1'),
    '#default_value' => $my_object->value1,
  );
  return $form;
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.