0
votes

i am working on simple custom module for Drupal 7, which take two numeric values and on submit display sum of two values on same page.

I have form ready, NOT completed but struggling as I am want to call calculateFunction() function when user submit form, takes parameter and sum values...

info

name = form_test
description = Small module which demo how to create input form in custom module.
core = 7.x

Module php

<?php
function form_test_menu()
{
    $items['formtest'] = array(
        'title' => 'Form Test',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('form_test_form'),
        'access callback' => TRUE, 
    );
    return $items;
}

function form_test_form($form,&$form_submit) {
    $form['firstname'] = array(
        '#title' => t('First Number'),
        '#type' => 'textfield',
        '#required' => TRUE,
    );
    $form['lastname'] = array(
        '#title' => t('Second Number'),
        '#type' => 'textfield',
    );   
    $form['submit'] = array(
        '#type' => 'submit', 
        '#value' => t('Run Function'));

    calculateFunction($form);

    return $form;
}

function calculateFunction()
{
    echo "sum of two numbers.....";
}
?>
1

1 Answers

0
votes

Instead of calling calculateFuction() directly you need to set $form['#submit'] to an array containing the name of the functions you want to call when the form is submitted.

$form['submit'] just creates the submit form element. #submit sets which callback function to submit to.

You may also optionally set $form['#validate'] to validate the submitted data.

See the Form API tutorial at Drupal.org

The submit callback could look something like the following:

/**
 * FAPI Callback for form_test_form().
 */
function calculateFunction($form, &$form_state) {
  $values = $form_state['values'];
  $sum = $values['first_name'] + $values['last_name'];
  drupal_set_message('The sum is ' . $sum);
}