Admin page to configure your module - boilerplate

Here is a boilerplate for Drupal 7, for the admin configuration feature of 'mymodule', accessible by the user having the 'administer mymodule' rights,  and shows the use of functions variable_get() and system_settings_form()

First, add the admin page entry in the HOOK_menu in your module.php file. This will create a menu item to the administration page we set to "admin/config/system/mymodule". The actual code for the admin page will be in a separated file called mymodule.admin.php. That way, the php for the admin page is only loaded when actually accessing the page, saving ressources on the webserver.

function mymodule_menu() {
	$items['admin/config/system/mymodule'] = array(
		'title' => 'Mymodule configuration',
		'page callback' => 'drupal_get_form',
		'page arguments' => array('mymodule_admin'),
		'file'  => 'mymodule.admin.inc',
		'description' => 'Configuration for mymodule',
		'access arguments' => array('administer mymodule'),
		'type' => MENU_NORMAL_ITEM,
	  );
	return $items;
}
	

Then add the path of the admin page to the .info file of your module so that a nice "Configure" button shows for your module on the admin module management page.

configure = admin/config/system/mymodule

 Back in the mymodule file, we need to declare the access key 'administer mymodule' with the HOOK_permission

function mymodule_permission() {
  return array(
    'administer mymodule' => array(
      'title' => t('Mymodule administration page'),
    ),
  );
}

Now we need to create the "mymodule.admin.inc" file, in the same directory as "mymodule.php" and start building our form

function mymodule_admin($form, &$form_state){

  $form['mymodule_something'] = array(
    '#type' => 'textfield',
    '#title' => t('A very important string'),
    '#default_value' => variable_get('mymodule_something', 'default value'),
    '#size' => 32,
    '#maxlength' => 64,
    '#required' => TRUE,
  );

  return system_settings_form($form);
}

We system_settings_form function takes care or the submit, and the action button, meaning we are done here. We can now use "variable_get('mymodule_something','default value')" in our mymodule module and get what evere value the user set.

On last thing is to delete our variable when uninstalling mymodule with the HOOK_uninstall() in your mymodule.install file

function mymodule_uninstall() {
  variable_del('mymodule_something');
}

 

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.