Pages

Thursday, February 24, 2011

Drupal Module - Data View In Block

<?php

/**
 * This module showing on how to show the data on table
 * It querying data in the database and then viewing it as 
 * table to user at module front end
 *
 * @author  : irfanudin ridho
 * @email   : irfan.ub@gmail.com
 * @version : 1.0
 * @date    : February 24, 2011
 * @type    : drupal module - block data view
 */

/**
 * This defines general setting for the module
 */
function ipad_block_info(){
    $block['ipad_apple'] = array(
        'info' => t('iPad Module'),        // this viewed in admin page
        'cache' => DRUPAL_CACHE_PER_ROLE,
        'region' => 'header',
        'visibility' => 1,
        'pages' => '*',
        'status' => TRUE,
    );
   
    return $block;
}

/**
 * This act as roles like an interface, then implemented in
 * the ipad_content
 */
function ipad_block_view($delta=''){
    switch($delta){
        case 'ipad_apple':
            $block['subject'] = t('Hello World');        // viewed in front top module block
            $block['content'] = ipad_content($delta);
            break;
    }
   
    return $block;
}

/**
 * This is what displayed in the content of block
 */
function ipad_content($switch_delta){
    $render = get_name_city();
   
    switch($switch_delta){
        case 'ipad_apple':
            return $render;
    }   
}

/**
 * This functin has task for accessing the data in the table
 * and then present it as table.
 * the structure of the table is like this one:
 * name of table: data
 * id int not null auto_increment key,
 * name char(20),
 * city char(20)
 */
function get_name_city(){
    $query = db_select('data')->fields('data')->execute()->fetchAll();
    $output = '<table><tr><th>Name</th><th>City</th></tr>';
   
    foreach($query as $key){
        $output .= '<tr>';
        $output .= '<td>'.$key->name.'</td>';
        $output .= '<td>'.$key->city.'</td>';
        $output .= '</tr>';
    }
   
    $output .= '</table>';
   
    return $output;
}

No comments:

Post a Comment