2

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?

7

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');
0

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.

0
<?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;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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