Pages

Thursday, February 24, 2011

Drupal Module - Ajax Sample

<?php

/**
 * This module provide example for ajax moduling
 *
 * @name    : ajax db access
 * @author  : irfanudin ridho
 * @email   : irfan.ub@gmail.com
 * @version : 1.0
 * @date    : February 25, 2011
 * @type    : drupal module - ajax database
 */

/**
 * Implements hook_menu()
 */
function mac_menu(){
    $items['mac'] = array(
        'title' => 'Mac Ajax',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('get_ajax'),
        'access callback' => TRUE,
    );
   
    return $items;
}

/**
 * ajax form and function handling
 */
function get_ajax($form, &$form_state){
    $form['nama'] = array(
        '#type' => 'select',
        '#title' => t('Select a name'),
        '#options' => get_names(),            // get all the names in database
        '#ajax' => array(
            'callback' => 'get_ajax_callback',
            'wrapper' => 'replace_text',
        ),
    );
   
    $form['item'] = array(
        '#type' => 'item',
        '#title' => t('The data you querying'),
        '#prefix' => '<div id="replace_text">',
        '#suffix' => '</div>',
    );
   
    if(!empty($form_state['values']['nama'])) {
        $render = render_table($form_state['values']['nama']);
        $form['item']['#description'] = $render;
    }
   
    return $form;
}

/**
 * Helper function for the select
 */
function get_ajax_callback($form, &$form_state){
    return $form['item'];
}

/**
 * Rendering table of data for viewing
 */
function render_table($name){
    $query = db_select('data')->fields('data')->condition('name',$name)->execute()->fetchAll();
    $output = '<table><tr><th>Name</th><th>Age</th><th>City</th></tr>';
    foreach($query as $key){
        $output .= '<tr>';
        $output .= '<td>'.$key->name.'</td>';
        $output .= '<td>'.$key->age.'</td>';
        $output .= '<td>'.$key->city.'</td>';
        $output .= '</tr>';
    }
   
    $output .= '</table>';
    return $output;
}

/**
 * Helper function.
 * Get all the names available on the database
 */
function get_names(){
    $query = db_select('data')->fields('data')->execute()->fetchAll();
    $names = array();
    foreach($query as $key){       
        $names[$key->name] = $key->name;
    }
   
    return $names;
}

No comments:

Post a Comment