knackforge
June 14, 2017
Drupal has a rich set of APIs to aid us in implementing custom functionalities with minimal optimized code. One such utility is system_settings_form($form).
Recently in my project, I created a new admin configuration form, in which I had to set all the field values as system variables. If I had not used system_settings_form(), then the code would have been like this.
function premium_admin_form() {
$form = array();
$form['premium_validity_period'] = array(
'#type' => 'textfield',
'#title' => t('Premium service validity period (days)'),
'#default_value' => variable_get('premium_validity_period', 365),
);
$form['premium_node'] = array(
'#type' => 'textfield',
'#title' => t('Product nid'),
'#default_value' => variable_get('premium_node', ''),
);
$form['premium_version'] = array(
'#type' => 'textfield',
'#title' => t('Version'),
'#default_value' => variable_get('premium_version', 1),
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit'),
);
return $form;
}
function premium_admin_form_submit($form, $form_state) {
variable_set('premium_validity_period', $form_state['values']['premium_validity_period']);
variable_set('premium_node', $form_state['values']['premium_node']);
variable_set('premium_version', $form_state['values']['premium_version']);
drupal_set_message("Premium Service configuration saved");
}
This is the customized code after I used system_settings_form(),
function premium_admin_form() {
$form = array();
$form['premium_validity_period'] = array(
'#type' => 'textfield',
'#title' => t('Premium service validity period (days)'),
'#default_value' => variable_get('premium_validity_period', 365),
);
$form['premium_node'] = array(
'#type' => 'textfield',
'#title' => t('Product nid'),
'#default_value' => variable_get('premium_node', ''),
);
$form['premium_version'] = array(
'#type' => 'textfield',
'#title' => t('Version'),
'#default_value' => variable_get('premium_version', 1),
);
return system_settings_form($form);
}
Let us see a brief explanation of system_settings_form().
Syntax :
system_settings_form($form)
$form: An associative array containing the structure of the form.
What will it do?
Like other forms, we can write our validation function to this form. If you want to remove the reset button, you can do using the below snippet.
$form = system_settings_form($form);
unset ($form['buttons']['reset']);
return $form;
We can retrieve the system variables using
$var_name = variable_get($variable_name, $default_value);
All system variables are available in the Drupal database under table name 'variable'.
Just like how your fellow techies do.
We'd love to talk about how we can work together
Take control of your AWS cloud costs that enables you to grow!