I'm creating a module that is basically a form but needs to use information from a table in the database to react the some of the button presses. Rather than executing the database query each time the button is pressed in the callback
function, is there a way to retrieve all of the information from the database when the module loads and store it in a variable so that other functions in the module can use/access it?
Thanks in advance
Code: An example module that is similar to my current one. I need to use results from the database query in the copy_text
function, and as I build the form up the same results in the callbacks for the other functions, so I don't see a point in putting the same db_query
in each callback - surely that's just unnecessary querying of the database:
<?php
function playground_menu() {
$items['playground/form'] = array(
'title' => 'Form',
'description' => '',
'page callback' => 'drupal_get_form',
'page arguments' => array('playground_demo_form'),
'access arguments' => array('access content'),
);
return $items;
}
function playground_demo_form($form, $form_state) {
$form['input'] = array(
'#type' => 'textarea',
'#title' => t('Input text'),
'#prefix' => '<div id="in-text">',
'#attributes' => array(
'placeholder' => t('Enter some text here... '),
),
'#suffix' => '</div>',
);
$form['buttons'] = array(
'#type' => 'fieldset',
'#title_display' => 'invisible',
'#attributes' => array(
'style' => 'border: 0px; text-align: right',
'class' => array('container-inline'),
),
);
$form['buttons']['copy'] = array(
'#type' => 'button',
'#value' => 'Copy text',
'#ajax' => array(
'callback' => 'copy_text',
'wrapper' => 'out-text',
// 'method' => 'replace',
// 'effect' => 'fade',
),
);
$form['buttons']['reverse'] = array(
'#type' => 'button',
'#value' => t('Reverse text'),
);
$form['buttons']['clear'] = array(
'#type' => 'button',
'#value' => t('Clear text'),
);
$form['output'] = array(
'#type' => 'textarea',
'#title' => t('Output text:'),
'#prefix' => '<div id="out-text">',
'#value' => '',
'#attributes' => array(
'placeholder' => t('Your text will appear here...'),
),
'#suffix' => '</div>',
);
return $form;
}
function copy_text($form, $form_state){
$form['output']['#value'] = $form_state['values']['input'];
return $form['output'];
}