variable_set

5 bootstrap.inc variable_set($name, $value)
6 bootstrap.inc variable_set($name, $value)
7 bootstrap.inc variable_set($name, $value)
8 bootstrap.inc variable_set($name, $value)

Sets a persistent variable.

Case-sensitivity of the variable_* functions depends on the database collation used. To avoid problems, always use lower case for persistent variable names.

Parameters

$name: The name of the variable to set.

$value: The value to set. This can be any PHP data type; these functions take care of serialization as necessary.

See also

variable_del()

variable_get()

348 functions call variable_set()

File

includes/bootstrap.inc, line 996
Functions that need to be loaded on every Drupal request.

Code

<?php
function variable_set($name, $value) {
  global $conf;

  db_merge('variable')->key(array('name' => $name))->fields(array('value' => serialize($value)))->execute();

  cache_clear_all('variables', 'cache_bootstrap');

  $conf[$name] = $value;
}
?>

Comments

Code to set a variable in admin panel using form field

<?php
/*
* Implements hook_menu().
*/
function mymodule_menu() {
 
$items = array();

 
$items['admin/mymodule/config-set-time'] = array(
   
'page callback' => 'drupal_get_form',
   
'page arguments' => array('_mymodule_set_time_form'),
   
'access arguments' => array('administer node'),
   
'type' => MENU_CALLBACK,
   
'file' => 'mymodule.admin.inc',
  );

  return
$items;
}
?>

in mymodule.admin.inc:

<?php
function _mymodule_set_time_form(&$form_state) {
 
 
$form = array();
 
 
$form['time'] = array(
   
'#type' => 'textfield',
   
'#title' => t('Time in second'),
   
'#default_value' => variable_get('mymodule_seconds_to_wait', 24 * 3600),    
   
'#required' => TRUE,
  );
 
 
$form['submit'] = array(
   
'#type' => 'submit',
   
'#value' => t('Submit'),
  );
 
}

function
_mymodule_set_time_form_submit(&$form_state) {
 
  if (
intval($form_state['values']['time'])) {
   
variable_set('mymodule_seconds_to_wait', intval($form_state['values']['time']));
   
   
drupal_set_message(t('Your configuration has been saved.'));
  }
 
}
?>

Thanks. Very useful.

Thanks. Very useful.

It would also be good to look at system_settings_form() for these types of forms.

Login or register to post comments