I am trying to do a variable_set() when clicking ‘Reset default values’ on my module’s admin page form. This runs through system_settings_form_submit(). The #default_value inside my form is reset, but my module relies on this stored variable to display some data. Clicking reset fills in the form with the default, but does not ‘Save’ it to recreate the variable in the database, so my module’s function breaks. It appears that nothing happens after clicking Reset, other than it deleting the variable from the database. Thanks in advance.
My submit function looks like this:
function faculty_submit(&$form, &$form_state){
if($form_state['values']['op'] == 'Reset to defaults') {
global $faculty_detail_template_default;
variable_set('faculty_detail_template', $faculty_detail_template_default);
}
elseif ($form_state['values']['op'] == 'Save configuration') {
// Clear caches for list and detail pages.
cache_clear_all('faculty_list', 'cache', TRUE);
cache_clear_all('faculty_detail_load', 'cache', TRUE);
}
}
First of all that’s what
system_settings_form_submitdoes when you press the Reset to defaults button. It callsvariable_delwhich will delete all your defined variables in the form from thevariablestable.Now your form’s
#defaultvalue is probably filled because you do something like this:I don’t see why you insist of adding a default value in the
variablestable. This entire approach is flawed. Just usevariable_get($name, $default)wherever your code depends onfaculty_detail_template. That’s precisely what the second parameter of this function is used for:$default The default value to use if this variable has never been set.So for Drupal, the absence of a variable from thevariabletable means it’s up to the coder how to handle this case (provide a default for example). Default value which is specified usingvariable_get.Second, if you used
system_settings_formthen you already have a submit function, the one mentioned above (system_settings_form_submit) so yourfaculty_submitwon’t be called unless you add it specifically to the array of submit callbacks to be executed. Something like this:BTW, using global variables is a bad idea (in general) and you should try to avoid using them. That’s what variables are used for 🙂 Pieces of information which can be retrieved in different parts of the code. So instead add a
.installfile to your module and in that file you define these global variables usingvariable_set. This is a lot cleaner than just magically popping some global variables in the middle of the code.