Drupal – 7 : Make a Module with a Form and Menu Link

Created a simple form which will add to your website that is accessed through its own custom URL.

Hooks are functions with special names that will be called by Drupal when actions occur.

For example – “form_example_menu()” is called when menu information is gathered.

Function t() will output text and is a Drupal function that plays nice with translation.

This demo will help you to create a new module with menu hook function.

After completing all the steps, go to the /admin/modules section and enable this module.

Clear all caches from the /admin/config/development/performance section.

Your page url will be “form_example”

Demo – Creating Module Structure


Step – 1

I. Create a folder for the module 
II. Put this folder in "sites/all/modules/{name of your module}" 
III. For example - "sites/all/modules/form_example"

Step – 2

I. Create two empty text files
II. {name of your module}.module 
For example - form_example.module
III. {name of your module}.info
For example - form_example.info

form_example.info (The .info file contains information about what your module does)

core = "7.x"
description = "An example module used to learn module development and forms creation."
name = "Form Example Module"

form_example.module (The .module file contains the actual code including hooks)

<?php
function form_example_menu() {
  $items = array();
  $items['form_example'] = array( //this creates a URL that will call this form at "form_example"
    'title' => 'Example Form', //page title
    'description' => 'A form to mess around with.',
    'page callback' => 'drupal_get_form', //this is the function that will be called when the page is accessed.
    'page arguments' => array('form_example_form'), //put the name of the form here
    'access callback' => TRUE,
  );
  return $items;
}
function form_example_form($form, &$form_state) {
 $form['price'] = array(
    '#type' => 'textfield', //you can find a list of available types in the form api
    '#title' => 'What is Your Price?',
    '#size' => 10,
    '#maxlength' => 10,
    '#required' => TRUE, //make this field required
  );
  $form['submit_button'] = array(
    '#type' => 'submit',
    '#value' => t('Click Here!'),   
  );
  return $form;
}
function form_example_form_validate($form, &$form_state) {
  if (!($form_state['values']['price'] > 0)){
    form_set_error('price', t('Price must be a positive number.'));
  }
}
function form_example_form_submit($form, &$form_state) {
 	//you can add your query here
 	drupal_set_message(t('Form Submitted.'));
}
SHARE:

Leave a Reply

Your email address will not be published. Required fields are marked *

*