Wednesday, March 23, 2011

Access database in php

<?php
error_reporting(-1);

$man_db = db_query("SELECT DISTINCT manufacture_name FROM {drup_deductible} WHERE drup_deductible.carrier_name LIKE '%Verizon%' ORDER BY manufacture_name");
$model_db = db_query("SELECT DISTINCT model_name FROM {drup_deductible} WHERE manufacture_name LIKE '%".$_REQUEST['manufacturer']."%' ORDER BY model_name");
$deduct_db = db_query("SELECT drup_deductible.tier_name, drup_tier.tier_name, drup_tier.tier_amount, drup_tier.tier_premium FROM {drup_tier},{drup_deductible} WHERE drup_tier.tier_name = drup_deductible.tier_name AND drup_deductible.carrier_name = 'Verizon' LIMIT 1");

$today = date('m/d/Y');
if($today >= "06/01/2011"){
    $effectiveDate = "05/17/2009";
} else {
    $effectiveDate = "02/01/11";
}

function dropdownfunc($name, $rowname, $source){
    foreach($source as $row) {
        if ($row->$rowname == $_REQUEST[$name])
        {
            $s = " SELECTED";
        } else {
            $s = "";
        }
        echo '<option value="'.$row->$rowname.'"'. $s.'>'.$row->$rowname.'</option>';
    }
}
?>
<div id="newwrapper">
    <div style="margin-top: -23px; margin-left: -22px; /margin-left: -15px; width: 975px; position: relative;">
        <div style="float:left; width:648px; margin-right: 5px;">
            <div id="vz-redesign-top"></div>
            <div style="padding-left: 25px; margin-top: 20px; /margin-top: 0px; position: relative; min-height: 200px;">
                <p style="font-size: 16px;">Select your manufacturer and model</p>
                <form method="POST" action="lookup">
                    <div style="float:left;width:160px;padding-right:15px; margin-top: 0px;">
                        <span style="font-size: 16px !important;">Manufacturer</span><br/>
                        <select name="manufacturer" onchange="this.form.submit();">
                            <option value="">Select a manufacturer</option>
                            <?php dropdownfunc('manufacturer', 'manufacture_name', $man_db); ?>
                        </select>
                    </div>
                    <input type="hidden" name="_submit" value="1">
                    <div style="float:left;width:150px;">
                        <span style="font-size:16px !important; margin-bottom: 10px;">Model</span><br/>
                        <select name="model" onchange="this.form.submit();"><br/>
                            <option value="">Select a model</option>
                            <?php dropdownfunc('model', 'model_name', $model_db); ?>
                        </select>
                    </div>
               </form>

               </form>
               </div>
               </div>
               </div>
               </div>

Sunday, March 20, 2011

JQuery Dialog Box capture input

JQuery Dialog Box capture input

<html lang="en">
<head>
  <title></title>
  <link type="text/css" href="js/themes/base/ui.all.css" rel="stylesheet" />
  <script type="text/javascript" src="js/jquery-1.4.4.min.js"></script>
  <script type="text/javascript" src="js/jquery-ui-1.8.7.custom.min.js"></script>
   <link type="text/css" href="js/demos.css" rel="stylesheet" />
  <script type="text/javascript">
    $(function() {
        var cancel = function() {
            $("#myDialog").dialog("close");
        }
        var getResponse = function(){
          var answer;
          $("input").each(function(){
            (this.checked == true) ? answer = $(this).val() : null;
          });
          $("<p>").text(answer).insertAfter($("#poll"));
          $("#myDialog").dialog("close");
        }
        var dialogOpts = {
          modal: true,
          buttons: {
            "Done": getResponse,
            "Cancel": cancel
          },
          autoOpen: false
        };
        $("#myDialog").dialog(dialogOpts);
        $("#poll").click(function() {
          $("#myDialog").dialog("open");
        }); 
    });
  </script>
</head>
<body>
    <button id="poll">Poll</button>
    <div id="myDialog" class="flora" title="This is the title">
      <p>Question?</p>
      <label for="yes">Yes!</label><input type="radio" id="yes" value="yes" name="question"><br>
      <label for="no">No!</label><input type="radio" id="no" value="no" name="question">
    </div>
</body>
</html>

Friday, March 18, 2011

Gmail Ubuntu Desktop Simple Mail

Send a simple mail from Ubuntu Desktop using ssmtp

1. Install ssmpt from System- >Administration->Synaptic
2. Go to /etc/ssmtp and edit ssmtp.conf

Debug=YES
#
# Config file for sSMTP sendmail
#
# The person who gets all mail for userids < 1000
# Make this empty to disable rewriting.
root=yourgmailusername@gmail.com

# The place where the mail goes. The actual machine name is required no
# MX records are consulted. Commonly mailhosts are named mail.domain.com
mailhub=smtp.gmail.com:587

# Where will the mail seem to come from?
#rewriteDomain=

# The full hostname
hostname=yourgmailusername@gmail.com

# Are users allowed to set their own From: address?
# YES - Allow the user to specify their own From: address
# NO - Use the system generated From: address
UseSTARTTLS=YES
FromLineOverride=YES

AuthUser=yourgmailusername@gmail.com
AuthPass=yourgmailpassword
AuthMethod=Login
AuthMethod=PLAIN


Now from terminal

localadmin@localadmin:~$ ssmtp destinationemailaddress@yahoo.com
To : destinationemailaddress@yahoo.com
From : youremailaddress@gmail.com
Subject : hi

Hi
Now press Cntrl D. If any difficulty instead of yahoo try any other gmail address.

If you get this - it means your username or password is in correct
Authorization failed (535 5.7.1 http://mail.google.com/support/bin/answer.py?answer=14257 27sm2207505yhl.25)


Thursday, March 17, 2011

Drupal 7 theme_table pagination sort

Drupal 7 theme_table  pagination sort

function deductible_menu_page($content = NULL, $arg1 = NULL, $arg2 = NULL){
  /*$tablesort = tablesort_sql($header);
    $result = pager_query($sql . $tablesort, $limit);
    $rows = array();
     // Then you can pass the data to the theme functions
    $output .= theme('table', $header, $rows);
    $output .= theme('pager', NULL, $limit, 0);
    */
   
    $headervariable =  array(
    array('data' => t('Carrier'), 'field' => 'carrier_name', 'sort' => 'asc'),
    array('data' => t('Manufacture'), 'field' => 'manufacture_name', 'sort' => 'asc'),
    array('data' => t('Model'), 'field' => 'model_name', 'sort' => 'asc'),
    array('data' => t('Tier'), 'field' => 'tier_name', 'sort' => 'asc'),
    t('Delete'),t('Update'));
    //$result = db_query("SELECT deductible_id,carrier_name,manufacture_name,model_name,tier_name FROM {drup_deductible}");
    $entries_per_page=3;
    $select = db_select('drup_deductible', 'pv')->extend('PagerDefault')->extend('TableSort');
    $result = $select
    ->fields('pv', array('deductible_id','carrier_name', 'manufacture_name', 'model_name', 'tier_name'))
    ->limit($entries_per_page)
    ->orderByHeader($headervariable)
    ->execute();
   
    $listitems=array();
    $bigitems = array();
    foreach ($result as $item) {
        watchdog('Deductibe', 'hi', array(), WATCHDOG_DEBUG);
        $listitems=array($item->carrier_name,
        $item->manufacture_name,
        $item->model_name,
        $item->tier_name,
        l('Delete','deductible/deductible/delete/'.$item->deductible_id),
        l('Update','deductible/deductible/update/'.$item->deductible_id)
        );
        $bigitems[]=$listitems;
    }

    //   return print_r($bigitems);
    if (count($listitems) == 0)
    $make[] = array("No Models Entered Yet");
    else{
        watchdog('Deductibe', 'a', array(), WATCHDOG_DEBUG);
    }

    $link_to_add_form = l('Add More Deductible','deductible/add_deductible');
    $variable=array(
             'header' =>  $headervariable,
             'rows'  =>  $bigitems,
             'attributes' => array(),
             'caption' => NULL,
             'colgroups' => NULL,
             'sticky' => NULL,
             'empty' => NULL,
    );
    // return print_r($items);
    $output= '<div id="car">'.theme_table($variable).'<br/>'.$link_to_add_form.'</div>';
    $output .= theme('pager');
    $output .= theme('sort');
    return $output;
   
}



Drupal 7 Ajax Pagination Update Delete Insert Form theme_table

Drupal 7 Ajax Pagination Update Delete Insert Form  theme_table  - Implemented below

deductible.module

<?php
//;$Id$

/**
 * @file
 * Enables a single blog for an individual or multiple users.
 */
// After you learn Form API in Chapter 5, you'll be able to
// make these settings configurable.

function deductible_help($section) {
    switch ($section) {
        case 'admin/help#deductible':
            return t('This module stores deductible for given make an Model');
    }
}

function deductible_menu(){
  
  
  $items['deductible/add_deductible'] = array(
    'title' => '',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('adddeductible'),
    'access callback' => TRUE,
     'file'=>'deductible.inc',
    'weight' => 0,
  );
  

    //watchdog('Deductibe', '1', array(), WATCHDOG_DEBUG);
    $items['deductible/display_deductibles'] = array(
    //    'title'=>'Calculate Deductible',
        'access arguments' => array('administer user'),
        'page callback' => 'deductible_menu_page',
        'page arguments' => array(t('Display Deductible')),
        'access callback' => TRUE,
        'file'=> 'deductible.inc',
    //'type' => MENU_CALLBACK,
    );
  
    $items['deductible/deductible/delete/%'] = array(
    //    'title'=>'Calculate Deductible',
        'access arguments' => array('administer user'),
        'page callback' => 'delete_deductible',
        'access callback' => TRUE,
        'page arguments' => array(0,1,2,3),
        'file'=> 'deductible.inc',
    //'type' => MENU_LOCAL_TASK,
    );
  
    //watchdog('Deductibe', '2', array(), WATCHDOG_DEBUG);
    return $items;
}



/**
 * Implementation of hook_perm().
 */
function deductible_perm() {
  return array('administer user');
}



function theme_deductible($form) {
    watchdog('Deductibe', 'abf', array(), WATCHDOG_DEBUG);
    $output = drupal_render($form['Title']);
    return $output;
}

function deductible_theme($existing, $type, $theme, $path) {
    return array(
    'deductible' => array(
      'arguments' => array('form' => NULL),
        'template' => 'deductible',  
        'render element' => 'form',  
    //  'file'=> 'deductibleadd.inc',  
    ),
    'list' => array(
      'arguments' => array('form' => NULL),
        'template' => 'list',  
        'render element' => 'form',      
          ),
      'carrier' => array(
      'arguments' => array('form' => NULL),
        'template' => 'carrier',  
        'render element' => 'form',      
          ),  
    );
}

function deductible_block_info() {
    $blocks = array();
    // The array key defines the $delta parameter used in all
    // other block hooks.
    $blocks['list'] = array(
       // The name of the block on the blocks administration page.
       'info' => t('List'),
       'file'=>'list.inc',
       'access arguments' => array('administer user'),
    );
    return $blocks;
}

function deductible_block_view($delta = '') {
 $block = array();
 switch ($delta) {
 case "list":
 $form = drupal_get_form('display_list');
 $block["content"] = $form;
 break;
 }
 return $block;
 }

deductible.inc

 <?php

function adddeductible($form, &$form_state) {
      $form = array();
    $path = drupal_get_path('module', 'Deductible');
    //$form_state['redirect'] = 'deductilbe/display_results';
    $result = db_query("SELECT carrier_name FROM {drup_carrier}");
    $form['#prefix']='<div id="ooo" class="dedwrapper">';
    $form['#suffix']='</div>';
    $carrier_names[] = array();
    $carrier_names[0]='--Select--';
   // $manufacture_names[]='Select';
          foreach ($result as $carrier) {
              $carrier_names[$carrier->carrier_name] = $carrier->carrier_name;
          }
  $selectedcarrier = isset($form_state['values']['carrier_select']) ? $form_state['values']['carrier_select'] : NULL;        
  $selectedmanufacture = isset($form_state['values']['manufacture_select']) ? $form_state['values']['manufacture_select'] : NULL;
  $selectedmodel = isset($form_state['values']['model_select']) ? $form_state['values']['model_select'] : NULL;
 
    $form['carrier_select'] = array(
    '#type' => 'select',
    '#title' => t('Carrier'),
    '#options' => $carrier_names,
      '#default_value' => $carrier_names[0],
    '#ajax' => array(
     'callback' => 'deductible_callback_formanufacture',
      'wrapper' => 'manufacturediv',
    ),
  );
 
  $form['manufacture_select'] = array(
    '#type' => 'select',
    '#title' => t('Manufacture'),
    '#options' => getManufactureList($selectedcarrier),
      //'#default_value' => $manufacture_names[0],
       '#prefix' => '<div id="manufacturediv">',
    '#suffix' => '</div>',
    '#ajax' => array(
     'callback' => 'deductible_callback_formodel',
      'wrapper' => 'modeldiv',
    ),
  );
 
  $form['model_select'] = array(
    '#type' => 'select',
    '#title' => t('Model'),
    '#prefix' => '<div id="modeldiv">',
    '#suffix' => '</div>',
   // '#default_value' => isset($form_state['values']['model_select']) ? $form_state['values']['model_select'] : 'Select',
    '#options' => getModelList($selectedmanufacture),
  '#ajax' => array(
     'callback' => 'deductible_callback_fortier',
      'wrapper' => 'tierdiv',
    ),
   );
 
   $form['tier_select'] = array(
    '#type' => 'select',
    '#title' => t('Tier'),
    '#prefix' => '<div id="tierdiv">',
    '#suffix' => '</div>',
  //  '#default_value' => isset($form_state['values']['tier_select']) ? $form_state['values']['tier_select'] : NULL,
    '#options' => getTierList($selectedmodel),
   );
 
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Save'),
        '#submit' => array('deductible_submit'),
    );
 //$form['#theme'] = 'deductible';
  return $form;
}

function deductible_callback_formanufacture($form, $form_state) {
     watchdog('Deductibe', 'In ajax', array(), WATCHDOG_DEBUG);
  return $form['manufacture_select'];
}

function deductible_callback_formodel($form, $form_state) {
     watchdog('Deductibe', 'In ajax', array(), WATCHDOG_DEBUG);
  return $form['model_select'];
}

function deductible_callback_fortier($form, $form_state) {
     watchdog('Deductibe', 'In ajax', array(), WATCHDOG_DEBUG);
  return $form['tier_select'];
}


function getManufactureList($selectedCarrier = NULL){
    $manufacture_names = array();
        if(isset($selectedCarrier)){
             $manufacture_names[0]='--Select--';
    watchdog('Deductibe', 'In select'.$selectedCarrier, array(), WATCHDOG_DEBUG);  
        $result = db_query("SELECT manufacture_name FROM {drup_manufacture}");
          foreach ($result as $manufacture_name) {
              $manufacture_names[$manufacture_name->manufacture_name] = $manufacture_name->manufacture_name;
          }
        }
          return $manufacture_names;
}

function getTierList($selectedModel = NULL){
    $tiers = array();
  
        if(isset($selectedModel)){
             $tiers[0]='--Select--';
    watchdog('Deductibe', 'In select'.$selectedModel, array(), WATCHDOG_DEBUG);  
        $result = db_query("SELECT tier_amount FROM {drup_tier} ");
  
  
          foreach ($result as $tier) {
              $tiers[$tier->tier_amount] = $tier->tier_amount;
          }
        }
          return $tiers;
}

function getModelList($selectedManufacture = NULL){
//    watchdog('Deductibe', 'FUNNY CATCH -JACK'.$selectedManufacture, array(), WATCHDOG_DEBUG);  
  
    $model_names = array();
        if(isset($selectedManufacture)){
    watchdog('Deductibe', 'In select'.$selectedManufacture, array(), WATCHDOG_DEBUG);  
        $result = db_query("SELECT model_name FROM {drup_model} WHERE model_manufacture  = :contents", array(':contents' => trim($selectedManufacture)));
  
    $model_names = array();
 
          foreach ($result as $model) {
               $model_names[0]='--Select--';
              $model_names[$model->model_name] = $model->model_name;
          }
        }
          return $model_names;
}

function deductible_submit($form, &$form_state){

  $carselect = isset($form_state['values']['carrier_select'])?$form_state['values']['carrier_select']:NULL;
  $manselect=isset($form_state['values']['manufacture_select'])?$form_state['values']['manufacture_select']:NULL;
  $modselect = isset($form_state['values']['model_select'])?$form_state['values']['model_select']:NULL;
  $tierselect = isset($form_state['values']['tier_select'])?$form_state['values']['tier_select']:NULL;
 // watchdog('Deductibe', 'Some Jacky'.$manselect, array(), WATCHDOG_DEBUG);  
 
  if(isset($carselect)&&isset($manselect)&&isset($modselect)&&isset($tierselect)){
      if(strlen($carselect)>0&&strlen($manselect)>0&&strlen($modselect)>0&&strlen($tierselect)>0){
         watchdog('Deductibe', 'Some Jacky'.strlen($carselect), array(), WATCHDOG_DEBUG);  
        $insertquery = db_insert('drup_deductible')->fields(array(
      'carrier_name'=>$carselect,
       'manufacture_name'=>$manselect,
       'model_name'=>$modselect,
         'tier_name'=>$tierselect
      ))->execute();
      if($insertquery!==false){
           $message = 'Deductible Added';
         drupal_set_message(t($message));
         $form_state['redirect'] = 'deductible/display_deductibles';
      }else{
          drupal_set_message(t('Error-Contact Administrator- Database issue'));
      }
      }else{
          watchdog('Deductibe', 'Some Jacky'.$carselect.$manselect.$modselect.$tierselect, array(), WATCHDOG_DEBUG);  
          drupal_set_message(t('Please select all entries'));
      }
  }else{
      drupal_set_message(t('Error-Contact Administrator'));
  }
}

function deductible_menu_page($content = NULL, $arg1 = NULL, $arg2 = NULL){
  /*$tablesort = tablesort_sql($header);
    $result = pager_query($sql . $tablesort, $limit);
    $rows = array();
     // Then you can pass the data to the theme functions
    $output .= theme('table', $header, $rows);
    $output .= theme('pager', NULL, $limit, 0);
    */
  
    $headervariable =  array(t('Carrier Name'),t('Manufacture Name'),t('Model Name'),t('Tier Name'),t('Delete'),t('Update'));
    //$result = db_query("SELECT deductible_id,carrier_name,manufacture_name,model_name,tier_name FROM {drup_deductible}");
    $entries_per_page=3;
    $select = db_select('drup_deductible', 'pv')->extend('PagerDefault')->extend('TableSort');
    $result = $select
    ->fields('pv', array('deductible_id','carrier_name', 'manufacture_name', 'model_name', 'tier_name'))
    ->limit($entries_per_page)
    ->orderByHeader($headervariable)
    ->execute();
  
    $listitems=array();
    $bigitems = array();
    foreach ($result as $item) {
        watchdog('Deductibe', 'hi', array(), WATCHDOG_DEBUG);
        $listitems=array($item->carrier_name,
        $item->manufacture_name,
        $item->model_name,
        $item->tier_name,
        l('Delete','deductible/deductible/delete/'.$item->deductible_id),
        l('Update','deductible/deductible/update/'.$item->deductible_id)
        );
        $bigitems[]=$listitems;
    }

    //   return print_r($bigitems);
    if (count($listitems) == 0)
    $make[] = array("No Models Entered Yet");
    else{
        watchdog('Deductibe', 'a', array(), WATCHDOG_DEBUG);
    }

    $link_to_add_form = l('Add More Deductible','deductible/add_deductible');
    $variable=array(
             'header' =>  $headervariable,
             'rows'  =>  $bigitems,
             'attributes' => array(),
             'caption' => NULL,
             'colgroups' => NULL,
             'sticky' => NULL,
             'empty' => NULL,
    );
    // return print_r($items);
    $output= '<div id="car">'.theme_table($variable).'<br/>'.$link_to_add_form.'</div>';
    $output .= theme('pager');
    $output .= theme('sort');
    return $output;
  
}

function delete_deductible($content = NULL, $arg1 = NULL, $arg2 = NULL,$arg3=NULL)
{

    global $base_root;
    $url=$base_root . request_uri();
    $output =  '<div>' . $url . '</div>';
    watchdog('Deductibe', 'In delete'.$arg3, array(), WATCHDOG_DEBUG);
    if(isset($arg3)){
        delete_entry($arg3);
    }
    drupal_goto($path = 'deductible/display_deductibles',  array(), $http_response_code = 302);
    //return $output.$arg2;
}

function delete_entry($arg){

    try{
        $num_deleted = db_delete('drup_deductible')
        ->condition('deductible_id', $arg)
        ->execute();
    }catch(Exception $e){
    }
    if($num_deleted!==false){
        drupal_set_message('<div id="msg">'.t('The deductible has been deleted').'</div>');
    //    $form_state['redirect'] = 'deductible/display_deductibles';
    }else{
        drupal_set_message(t('Some issue- Unable to delete'));
    //    $form_state['redirect'] = 'deductible/display_results';
    }
}


/*function adddeductible_form($form, &$form_state){
    $form = array();
    $path = drupal_get_path('module', 'Deductible');
    //$form_state['redirect'] = 'deductilbe/display_results';
    $result = db_query("SELECT manufacture_name FROM {drup_manufacture}");
  
    $manufacture_names = array();
          foreach ($result as $manufacture) {
              $manufacture_names[] = $manufacture->manufacture_name;
          }
  $selected = isset($form_state['values']['manufacture_select']) ? $form_state['values']['manufacture_select'] : key($manufacture_names);
 
  $form['manufacture_select'] = array(
    '#type' => 'select',
    '#title' => t('Manufacture'),
    '#options' => $manufacture_names,
      '#default_value' => $selected,
    '#ajax' => array(
     'callback' => 'deductible_dependent_dropdown_callback',
      'wrapper' => 'dropdown-second-replace',
    ),
  );

  $form['model_select'] = array(
    '#type' => 'select',
    '#title' => t('Model'),
    '#prefix' => '<div id="dropdown-second-replace">',
    '#suffix' => '</div>',
    '#default_value' => isset($form_state['values']['model_select']) ? $form_state['values']['model_select'] : 'Select',
    '#options' => getModelList($selected),
      '#ajax' => array(
     'callback' => 'deductible_dependent_dropdown_callback2',
      'wrapper' => 'dropdown-third-replace',
    ),
   );
 


  
$form['#attached'] = array
    (
    'css' => array
    (
        'type' => 'file',
        'data' => $path . '/root.css',
    ),
    'js' => array
    (
        'type' => 'file',
        'data' => $path . '/root.js',
    ),
    );
  
    $form['#theme'] = 'deductible';
    return $form;
}
*/
/*function deductible_dependent_dropdown_callback($form, $form_state) {
     watchdog('Deductibe', 'In ajax', array(), WATCHDOG_DEBUG);
  return $form['manufacture_select'];
}


*/

/*function deductible_submit($form, &$form_state){
  watchdog('Deductibe', 'In add', array(), WATCHDOG_DEBUG);
  global $user;
  $username = $user->name;
  watchdog('Deductibe', $form_state['values']['manufacture_select'], array(), WATCHDOG_DEBUG);
   $form_state['redirect'] = 'deductible/add_manufacture';
  /*$Make = $form_state['values']['Make'];
  $Model = $form_state['values']['Model'];
  $Deductible = $form_state['values']['Deductible'];
      $insertquery = db_insert('Deductible')->fields(array(
      'username' => $username,
      'Make'=>$form_state['values']['Make'],
       'model'=>$form_state['values']['Model'],
       'deductible'=>$form_state['values']['Deductible']
      ))->execute();
      if($insertquery!==false){
           $message = 'You have submitted the '  . ' form which contains the following data:<pre>' . print_r($form_state['values']['Make'],true) . '</pre>';
         drupal_set_message(t($message));
         $form_state['redirect'] = 'deductible/display_results';
      }else{
          drupal_set_message(t('Error-Contact Administrator'));
      }*/
//}


/*function deductible_menu_page($content = NULL, $arg1 = NULL, $arg2 = NULL,$arg3=NULL)
{
    $result = db_query("SELECT itemid,make,model,deductible FROM {Deductible}");
    $listitems=array();
    $bigitems = array();
    foreach ($result as $item) {
        watchdog('Deductibe', 'hi', array(), WATCHDOG_DEBUG);
        $listitems=array($item->make,
        $item->model,
        $item->deductible,
        l('Delete','deductible/delete/'.$item->itemid),
        l('Update','deductible/update/'.$item->itemid)
        );
        $bigitems[]=$listitems;
    }

    //   return print_r($bigitems);
    if (count($listitems) == 0)
    $make[] = array("No Models Entered Yet");
    else{
        watchdog('Deductibe', 'a', array(), WATCHDOG_DEBUG);
    }

    $link_to_add_form = l('Add More Models','deductible/calculate');
    $variable=array(
             'header' =>  array(t('Make'), t('Model'),t('Deductible'),t('Delete'),t('Update')),
             'rows'  =>  $bigitems,
             'attributes' => array(),
             'caption' => NULL,
             'colgroups' => NULL,
             'sticky' => NULL,
             'empty' => NULL,
    );
    // return print_r($items);
    return theme_table($variable).'<br/>'.$link_to_add_form;
}*/
/*  $form['justtext'] = array(
    '#type' => 'textfield',
    '#title' => t("Who"),
    '#prefix' => '<div id="replace_textfield_div1">',
    '#suffix' => '</div>',
  );*/
/*  if (!empty($form_state['values']['manufacture_select'])) {
    $form['justtext']['#description'] = t("Say why you chose") .  " '{$form_state['values']['manufacture_select']}'";
   /* $selected=$form_state['values']['manufacture_select'];
     $form['model_select']['#options'] = getModelList($selected);*/
 // }

 /*     $form['fs'] = array(
      '#type'=>'fieldset',
      '#attributes'=>array('style'=>'width:50%;'),
      '#weight'=>$weight,
    );
  */


function display_list(){
    $form = array();
    $path = drupal_get_path('module', 'Deductible');
    $form['#attached'] = array
    (
    'css' => array
    (
        'type' => 'file',
        'data' => $path . '/root.css',
    ),
    'js' => array
    (
        'type' => 'file',
        'data' => $path . '/root.js',
    ),
    );
    $form['#theme'] = 'list';
    return $form;
}



Sunday, March 13, 2011

Display 2 blocks besides each other in the main content in Drupal 7

Display 2 blocks besides each other in the main content


First Set the 2 blocks to display on the main content. Go to Structure->Blocks
Set the blocks to main content.

Now when you close the overlay. You will see 2 blocks on the main page.

Right click and view source. If your module has css file set you can change over there or you can change the css file in style.css of your theme.

Basically you now have to modify the css file to display to blocks besides each other rather than vertical position.

Right click and view source now find the id for your block and set the css as below.

#listtable, #td {
    border:1px solid black; width:200px
}
#tr.invisible td{border:0px;width:40px}

#breadcrumb {display: none;}

#deductible-custom-form{
float: right;
margin-top:75px;
display:block;
width: 200px;
position: relative;
}
#display-list{
/*border:0.5px solid black;
background-color:lightgrey;*/
height: auto;
position: 10;
width: 200px;
float: left;
}

#block-deductible-list{
/*border:0.5px solid black;
background-color:lightgrey;*/
display: block;
height: auto;
position: relative;
width: 200px;
float: left;
}

.region-content{
max-width:500px;
min-width:500px;
}

now you will also have to modify the region content to set the maximum and minimum region so that blocks dont fall over in vertical position.

In above I have set one block to float left and one to float right this sets my two blocks in same line.
float: right;


Simple Help Module in Drupal / Drupal 7

Simple Block Module in Drupal / Drupal 7

Create a simple module using the example on this link

http://harshal-techapps.blogspot.com/2011/03/simple-form-example-drupal-7-with.html

Then replace the deductible.module in that example with below.

This is the deductible.module
<?php
//;$Id$

/**
 * @file
 * Enables a single blog for an individual or multiple users.
 */
// After you learn Form API in Chapter 5, you'll be able to
// make these settings configurable.

function deductible_help($section) {
    switch ($section) {
        case 'admin/help#deductible':
            return t('This module stores deductible for given make an Model');
    }
}

function deductible_menu(){
   
    $items['deductible/list']=array(
    //    'title'=>'Calculate Deductible',
        'page callback'=>'drupal_get_form',
        'page arguments'=>array('display_list'),
        'file'=> 'list.inc',
        'access arguments' => array('administer user'),
    );
   
    $items['deductible/add_carrier']=array(
    //    'title'=>'Calculate Deductible',
        'page callback'=>'drupal_get_form',
        'page arguments'=>array('addcarrier_form'),
        'access arguments' => array('administer user'),
        'file'=> 'carrier.inc',
    //'type' => MENU_CALLBACK,
    );
   
    $items['deductible/calculate']=array(
    //    'title'=>'Calculate Deductible',
        'page callback'=>'drupal_get_form',
        'page arguments'=>array('deductible_custom_form'),
        'access arguments' => array('administer user'),
        'file'=> 'deductibleadd.inc',
//        'type' => MENU_CALLBACK,
    );



    //watchdog('Deductibe', '1', array(), WATCHDOG_DEBUG);
    $items['deductible/display_results'] = array(
    //    'title'=>'Calculate Deductible',
        'access arguments' => array('administer user'),
        'page callback' => 'display_results',
        'access callback' => TRUE,
    //'type' => MENU_CALLBACK,
    );
    $items['deductible/delete/%'] = array(
    //    'title'=>'Calculate Deductible',
        'access arguments' => array('administer user'),
        'page callback' => 'delete_item',
        'access callback' => TRUE,
        'page arguments' => array(0,1,2),
        'file'=> 'deductibledelete.inc',
    //'type' => MENU_LOCAL_TASK,
    );
    //watchdog('Deductibe', '2', array(), WATCHDOG_DEBUG);
    return $items;
}



/**
 * Implementation of hook_perm().
 */
function deductible_permission() {
  return array('administer user');
}

function display_results()
{
    $result = db_query("SELECT itemid,make,model,deductible FROM {Deductible}");
    $listitems=array();
    $bigitems = array();
    foreach ($result as $item) {
        watchdog('Deductibe', 'hi', array(), WATCHDOG_DEBUG);
        $listitems=array($item->make,
        $item->model,
        $item->deductible,
        l('Delete','deductible/delete/'.$item->itemid),
        l('Update','deductible/update/'.$item->itemid)
        );
        $bigitems[]=$listitems;
    }

    //   return print_r($bigitems);
    if (count($listitems) == 0)
    $make[] = array("No Models Entered Yet");
    else{
        watchdog('Deductibe', 'a', array(), WATCHDOG_DEBUG);
    }

    $link_to_add_form = l('Add More Models','deductible/calculate');
    $variable=array(
             'header' =>  array(t('Make'), t('Model'),t('Deductible'),t('Delete'),t('Update')),
             'rows'  =>  $bigitems,
             'attributes' => array(),
             'caption' => NULL,
             'colgroups' => NULL,
             'sticky' => NULL,
             'empty' => NULL,
    );
    // return print_r($items);
    return theme_table($variable).'<br/>'.$link_to_add_form;
}

function theme_deductible($form) {
    watchdog('Deductibe', 'abf', array(), WATCHDOG_DEBUG);
    $output = drupal_render($form['Title']);
    return $output;
}

function deductible_theme($existing, $type, $theme, $path) {
    return array(
    'deductible' => array(
      'arguments' => array('form' => NULL),
        'template' => 'deductible',   
        'render element' => 'form',   
      'file'=> 'deductibleadd.inc',   
    ),
    'list' => array(
      'arguments' => array('form' => NULL),
        'template' => 'list',   
        'render element' => 'form',       
          ),
      'carrier' => array(
      'arguments' => array('form' => NULL),
        'template' => 'carrier',   
        'render element' => 'form',       
          ),   
    );
}

function deductible_block_info() {
    $blocks = array();
    // The array key defines the $delta parameter used in all
    // other block hooks.
    $blocks['list'] = array(
       // The name of the block on the blocks administration page.
       'info' => t('List'),
        'file'=>'list.inc',
    );
    return $blocks;
}

function deductible_block_view($delta = '') {
 $block = array();
 switch ($delta) {
 case "list":
 $form = drupal_get_form('display_list');
 $block["content"] = $form;
 break;
 }
 return $block;
 }

function display_list(){
    $form = array();
    $path = drupal_get_path('module', 'Deductible');
    $form['#attached'] = array
    (
    'css' => array
    (
        'type' => 'file',
        'data' => $path . '/root.css',
    ),
    'js' => array
    (
        'type' => 'file',
        'data' => $path . '/root.js',
    ),
    );
    $form['#theme'] = 'list';
    return $form;
}






You can access the help module when you enable the Module from Modules menu on the top you See help link besides the module. Also on the top you will see Help Menu Once you click on the help menu you will see Calculate Deductible Module

Simple Block Module in Drupal 7

Simple Block Module in Drupal 7

Create a simple module using the example on this link

http://harshal-techapps.blogspot.com/2011/03/simple-form-example-drupal-7-with.html

Then replace the deductible.module in that example with below.

This is the deductible.module
<?php
//;$Id$

/**
 * @file
 * Enables a single blog for an individual or multiple users.
 */
// After you learn Form API in Chapter 5, you'll be able to
// make these settings configurable.

function deductible_help($section) {
    switch ($section) {
        case 'admin/help#deductible':
            return t('This module stores deductible for given make an Model');
    }
}

function deductible_menu(){
   
    $items['deductible/list']=array(
    //    'title'=>'Calculate Deductible',
        'page callback'=>'drupal_get_form',
        'page arguments'=>array('display_list'),
        'file'=> 'list.inc',
        'access arguments' => array('administer user'),
    );
   
    $items['deductible/add_carrier']=array(
    //    'title'=>'Calculate Deductible',
        'page callback'=>'drupal_get_form',
        'page arguments'=>array('addcarrier_form'),
        'access arguments' => array('administer user'),
        'file'=> 'carrier.inc',
    //'type' => MENU_CALLBACK,
    );
   
    $items['deductible/calculate']=array(
    //    'title'=>'Calculate Deductible',
        'page callback'=>'drupal_get_form',
        'page arguments'=>array('deductible_custom_form'),
        'access arguments' => array('administer user'),
        'file'=> 'deductibleadd.inc',
//        'type' => MENU_CALLBACK,
    );



    //watchdog('Deductibe', '1', array(), WATCHDOG_DEBUG);
    $items['deductible/display_results'] = array(
    //    'title'=>'Calculate Deductible',
        'access arguments' => array('administer user'),
        'page callback' => 'display_results',
        'access callback' => TRUE,
    //'type' => MENU_CALLBACK,
    );
    $items['deductible/delete/%'] = array(
    //    'title'=>'Calculate Deductible',
        'access arguments' => array('administer user'),
        'page callback' => 'delete_item',
        'access callback' => TRUE,
        'page arguments' => array(0,1,2),
        'file'=> 'deductibledelete.inc',
    //'type' => MENU_LOCAL_TASK,
    );
    //watchdog('Deductibe', '2', array(), WATCHDOG_DEBUG);
    return $items;
}



/**
 * Implementation of hook_perm().
 */
function deductible_permission() {
  return array('administer user');
}

function display_results()
{
    $result = db_query("SELECT itemid,make,model,deductible FROM {Deductible}");
    $listitems=array();
    $bigitems = array();
    foreach ($result as $item) {
        watchdog('Deductibe', 'hi', array(), WATCHDOG_DEBUG);
        $listitems=array($item->make,
        $item->model,
        $item->deductible,
        l('Delete','deductible/delete/'.$item->itemid),
        l('Update','deductible/update/'.$item->itemid)
        );
        $bigitems[]=$listitems;
    }

    //   return print_r($bigitems);
    if (count($listitems) == 0)
    $make[] = array("No Models Entered Yet");
    else{
        watchdog('Deductibe', 'a', array(), WATCHDOG_DEBUG);
    }

    $link_to_add_form = l('Add More Models','deductible/calculate');
    $variable=array(
             'header' =>  array(t('Make'), t('Model'),t('Deductible'),t('Delete'),t('Update')),
             'rows'  =>  $bigitems,
             'attributes' => array(),
             'caption' => NULL,
             'colgroups' => NULL,
             'sticky' => NULL,
             'empty' => NULL,
    );
    // return print_r($items);
    return theme_table($variable).'<br/>'.$link_to_add_form;
}

function theme_deductible($form) {
    watchdog('Deductibe', 'abf', array(), WATCHDOG_DEBUG);
    $output = drupal_render($form['Title']);
    return $output;
}

function deductible_theme($existing, $type, $theme, $path) {
    return array(
    'deductible' => array(
      'arguments' => array('form' => NULL),
        'template' => 'deductible',   
        'render element' => 'form',   
      'file'=> 'deductibleadd.inc',   
    ),
    'list' => array(
      'arguments' => array('form' => NULL),
        'template' => 'list',   
        'render element' => 'form',       
          ),
      'carrier' => array(
      'arguments' => array('form' => NULL),
        'template' => 'carrier',   
        'render element' => 'form',       
          ),   
    );
}

function deductible_block_info() {
    $blocks = array();
    // The array key defines the $delta parameter used in all
    // other block hooks.
    $blocks['list'] = array(
       // The name of the block on the blocks administration page.
       'info' => t('List'),
        'file'=>'list.inc',
    );
    return $blocks;
}

function deductible_block_view($delta = '') {
 $block = array();
 switch ($delta) {
 case "list":
 $form = drupal_get_form('display_list');
 $block["content"] = $form;
 break;
 }
 return $block;
 }

function display_list(){
    $form = array();
    $path = drupal_get_path('module', 'Deductible');
    $form['#attached'] = array
    (
    'css' => array
    (
        'type' => 'file',
        'data' => $path . '/root.css',
    ),
    'js' => array
    (
        'type' => 'file',
        'data' => $path . '/root.js',
    ),
    );
    $form['#theme'] = 'list';
    return $form;
}







Friday, March 11, 2011

Drupal 7 Getting access denied page on logout

If you menu_example module installed you may face this issue.

Access denied on logout on drupal 7.


Try disabling the menu_example module

Thursday, March 10, 2011

Drupal 7 hook_theme not using the template

Do check out this if you want to use the template .tpl.php


http://harshal-techapps.blogspot.com/2011/03/drupal-7-hooktheme-template-form.html

<?php

function deductible_menu()
{
    $items['deductible/calculate'] = array
    (
        'title' => 'Theming Forms',
        'description' => 'Practicing theming forms in Drupal 7',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('deductible_form'),
        'access callback' => TRUE,
    );
    return $items;
}

function deductible_form(){
$form['first_name'] = array
(
    '#type' => 'textfield',
);
$form['last_name'] = array
(
    '#type' => 'textfield',
);
$form['age'] = array
(
    '#type' => 'textfield',
    '#maxlength' => 3,
);

// Get the path to the module
$path = drupal_get_path('module', 'Deductible');
// Attach the CSS and JS to the form
/*$form['#attached'] = array
(
    'css' => array
    (
        'type' => 'file',
        'data' => $path . '/form_theme.css',
    ),
    'js' => array
    (
        'type' => 'file',
        'data' => $path . '/form_theme.js',
    ),
);*/
return $form;
}


function deductible_theme()
{
    return array
    (
        'deductible_form' => array
        (
            'render element' => 'form'
        ),
    );
}


function theme_deductible_form($variables)
{
    // Isolate the form definition form the $variables array
    $form = $variables['form'];
    $output = '<h2>' . t('Please enter your information below') . '</h2>';
    // Put the entire structure into a div that can be used for
    // CSS purposes
    $output .= '<div id="personal_details">';
    // Each of the pieces of text is wrapped in a <span>
    // tag to allow it to be floated left
    $output .= '<span>' . t('My name is') . '</span>';
    // Form elements are rendered with drupal_render()
    $output .= drupal_render($form['first_name']);
    $output .= drupal_render($form['last_name']);
    $output .= '<span>' . t('and I am') . '</span>';
    $output .= drupal_render($form['age']);
    $output .= '<span>' . t('years old.') . '</span>';
    $output .= '</div>';
    // Pass the remaining form elements through drupal_render_children()
    $output .= drupal_render_children($form);
    // return the output
    return $output;
}

Drupal 7 hook_theme template form

Drupal 7 hook_theme template form

First create a module using the link http://harshal-techapps.blogspot.com/2011/03/database-drupal-7-themetable-example.html

deductible.module

<?php

function deductible_menu()
{
    $items['deductible/calculate'] = array
    (
        'title' => 'Theming Forms',
        'description' => 'Practicing theming forms in Drupal 7',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('deductible_form'),
        'access callback' => TRUE,
    );
    return $items;
}


function deductible_form(){
$form['first_name'] = array
(
'#title' => 'FirstName',   
'#type' => 'textfield',
);
$form['last_name'] = array
(
    '#type' => 'textfield',
);
$form['age'] = array
(
    '#type' => 'textfield',
    '#maxlength' => 3,
);

// Get the path to the module
$path = drupal_get_path('module', 'Deductible');
// Attach the CSS and JS to the form
/*$form['#attached'] = array
(
    'css' => array
    (
        'type' => 'file',
        'data' => $path . '/form_theme.css',
    ),
    'js' => array
    (
        'type' => 'file',
        'data' => $path . '/form_theme.js',
    ),
);*/
$form['#theme'] = 'deductible_form';
return $form;
}


function deductible_theme($existing, $type, $theme, $path)
{
    return array
    (
        'deductible_form' => array(
         'arguments' => array('form' => NULL),
           'template' => 'deductible_form',   
         'render element' => 'form',   
    ),
    );
}
Template file
deductible_form.tpl.php

<div id="registration_form">
    <div class="field">
      <?php
        print 'hi'.drupal_render($form['first_name']);
      ?>
    </div>
</div>

Wednesday, March 9, 2011

Drupal 7 database


Quick guide to the new Drupal 7 database layer


Settings.php

We should start by taking a look at the renewed database definition in the settings.php. In most cases you will be using a drupal site with only one database. For this you should use the following structure.

<?php
$databases['default']['default'] = array(
‘driver’ => ‘mysql’,
‘database’ => ‘drupaldb’,
‘username’ => ‘username’,
‘password’ => ’secret’,
‘host’ => ‘localhost’,
);
?>

The first thing you should notice are the values “default” in the $database array. The first one is the CONNECTION KEY, the second one is the TARGET.
The connection key is a unique identifier for a database connection, there must ALWAYS be a ‘default’ connection key available.
The target is used to define master/slave database structures. If the master (default) isn’t available, the system will search for the slave database. It is also possible to flag a query to run on the slave database. To make this a bit clearer I’ll give you a more complicated database structure.
<?php
$databases['default']['default'] = array(
‘driver’ => ‘mysql’,
‘database’ => ‘drupaldb1′,
‘username’ => ‘username’,
‘password’ => ’secret’,
‘host’ => ‘dbserver1′,
);
$databases['default']['slave'][] = array(
‘driver’ => ‘mysql’,
‘database’ => ‘drupaldb2′,
‘username’ => ‘username’,
‘password’ => ’secret’,
‘host’ => ‘dbserver2‘,
);
?>
In this case, the first database is the default database, the second is the slave databases.
It is also possible to define separate database structures.
<?php
$databases['default']['default'] = array(
‘driver’ => ‘mysql’,
‘database’ => ‘drupaldb1′,
‘username’ => ‘username’,
‘password’ => ’secret’,
‘host’ => ‘dbserver1′,
);
$databases['extra']['default'][] = array(
‘driver’ => ‘mysql’,
‘database’ => ‘drupaldb2′,
‘username’ => ‘username’,
‘password’ => ’secret’,
‘host’ => ‘dbserver2‘,
);
?>
Note that no matter how many connections are defined in the settings file, These connections will not be used by Drupal until they are actually opened.

Select Query

So far for the database connections, now lets take a look at the actual use of query’s in this new database layer. For the regular select query’s not much changes. Here is an example of a select query with a short explanation.
$result = db_query(“SELECT nid, title FROM {node} WHERE type = :type”, array(
‘:type’ => ‘page’,
));
The db_query function uses three arguments, first one is the query string, the second one are the values used to fill up the placeholders. The third one will be explained at the next example.
Note that the placeholder (:type) doesn’t use quotes. Another thing you should take in to account is to put your database names between {}. This is needed for the database system to attache a prefix string if this is defined in your settings.
Now for the third argument of the db_query we will take a look at the following code:
<?php
$result = db_query(“SELECT nid, title FROM {node}”, array(), array(
‘target’ => ’slave’,
));
?>
The third argument is an array of configuration directives to detect the way the query should run. In this case the query runs on the slave database. I won’t go into the details here, because (as I said before) in this blog post I will only pick up the basics of the new database system.
The following is just a handy guide about the way you can use the database query’s results. (Not 100% relevant to this post, but this might come in handy for some of you. The others should just scroll through the code, as if it doesn’t exist).
$result = db_query(“SELECT nid, title FROM {node}”);
foreach ($result as $record) {
// Do something with each $record
}
$record = $result->fetch(); // Use the default fetch mode.
$record = $result->fetchObject(); // Fetch as a stdClass object
$record = $result->fetchField($column_index); // Fetch only one field.
$number_of_rows = $result->rowCount(); //Count the results.

Insert Query

Now we’ve arrived to he fun part. The INSERT, DELETE and UPDATE query’s require that you use the query builder object in order to behave consistently across all different databases. This is where the new object-oriented query API comes in.
The compact INSERT form is the following:
<?php
$nid = db_insert(‘node’)
->fields(array(
‘title’ => ‘Example’,
‘uid’ => 1,
‘created’ => REQUEST_TIME,
))
->execute();
?>
This will result in the following query:
INSERT INTO {node} (title, uid, created) VALUES (’Example’, 1, 1221717405);
Note: If you don’t call the execute() method, the query will not run!
The insert query object can also be used with multiple values. To insert multiple rows you shouldn’t only use fields() but also values(). In this case fields() only defines the fields, but doesn’t put any content into the selected fields. The values() may be called multiple times in order to add more than one line to your database.
<?php
$query = db_insert(’node’)
->fields(array(‘title’, ‘uid’, ‘created’))
->values(array(
array(
‘title’ => ‘Example’,
‘uid’ => 1,
‘created’ => REQUEST_TIME,
),
array(
‘title’ => ‘Example 2′,
‘uid’ => 1,
‘created’ => REQUEST_TIME,
)))
->execute();
?>
Using a ‘foreach’ the code will look like this:
<?php
$values = array(
array(
‘title’ => ‘Example’,
‘uid’ => 1,
‘created’ => REQUEST_TIME,
),
array(
‘title’ => ‘Example 2′,
‘uid’ => 1,
‘created’ => REQUEST_TIME,
),
);
$query = db_insert(‘node’)->fields(array(‘title’, ‘uid’, ‘created’));
foreach ($values as $record) {
$query->values($record);
}
$query->execute();
?>

Update Query

Next stop is the UPDATE query. The update query is pretty straight forward, if you understand how the insert query’s work, it shouldn’t be a problem to understand the update query. Here it goes:
<?php
$num_updated = db_update(‘node’)
->fields(array(
‘uid’ => 5,
’status’ => 1,
))
->condition(‘created’, REQUEST_TIME - 3600, ‘>=’)
->execute();
?>
This will result in the following query:
UPDATE {node} SET uid=5, status=1 WHERE created >= 1221717405;
Not much to explain here, so let’s go to the DELETE query’s.

Delete Query

Again the same story here. The DELETE query is probabily the easiest form of the query object:
<?php
$num_deleted = db_delete(‘node’)
->condition(‘nid’, 5)
->execute();
?>
This will result in the following query:
DELETE FROM {node} WHERE nid=5;

Merge Query

Finally we’ve got to the last one. The MERGE query. This one is a bit more complicated. If you would strip this one down to it’s original form, you will finde that a merge query is actually just the combination of an insert and an update query. In php it would be something like this:
<?php
if (db_query(”SELECT COUNT(*) FROM {example} WHERE id=:id”, array(’:id’ => $id)->fetchField()) {
// Run an update using WHERE id = $id
}
else {
// Run an insert, inserting $id for id
}
?>
In the new database API structure the merge query’s are build up like this:
<?php
db_merge(‘example’)
->key(array(‘name’ => $name))
->fields(array(
‘field1′ => $value1,
‘field2′ => $value2,
))
->execute();
?>
Here the “example” table is used. The specified key field ‘name’ has the value of $name. Now two things could happen.
First option: If the $name value exists in the database, then fields “field1” and “field2” will get an update with the correspondingvalues.
Second option: If the $name value doesn’t exist in the database, a new row will be created in which “name” gets the value $name, “field1” gets the value $field1 and “field2” gets the value $field2.
In some cases the values you want to set will have to be different, according to the fact that the key field does or doesn’t already exist. This can be handled in two ways.
<?php
db_merge(‘example’)
->key(array(‘name’ => $name))
->fields(array(
‘field1′ => $value1,
‘field2′ => $value2,
))
->update(array(
‘field1′ => $alternate1,
))
->execute();
?>
In this case, if the “name” already exists the value of “field1” will be $alternate1, and the value of “field2” will be $value2. If the “name” doesn’t allready exist, $value1 and $value2 will be used.
It is also possible to use expressions. I’ll give you an example in which, if the ‘name’ already exists, the “value1” field will become the current value +1:
<?php
db_merge(‘example’)
->key(array(‘name’ => $name))
->fields(array(
‘field1′ => $value1,
‘field2′ => $value2,
))
->expression(‘field1′, ‘field1 + :inc’, array(‘:inc’ => 1))
->execute();
?>
Note that expression() can be used multiple times, 1 time for each field.
Field updates can also be limited, if the row already exists. In this case, if the “name” already exists, only “field2” will be updated, and “field1” will be ignored:
<?php
db_merge(‘example’)
->key(array(‘name’ => $name))
->fields(array(
‘field1′ => $value1,
‘field2′ => $value2,
))
->updateExcept(‘field1′)
->execute();
?>
This is the end of my quick guide into the new Drupal 7 database layer. Hope you’ve enjoyed it. For more detailed information about this system, I would like to refere to the official drupal database API: http://drupal.org/developing/api/database

Database Drupal 7 theme_table example

Database Drupal 7 theme_table example
<?php
//;$Id$

/**
 * @file
 * Enables a single blog for an individual or multiple users.
 */
// After you learn Form API in Chapter 5, you'll be able to
// make these settings configurable.

function deductible_help($section) {
      switch ($section) {
        case 'admin/help#deductible':
          return t('This module stores deductible for given make an Model');
      }
}

function deductible_menu(){
$items['deductible/calculate']=array(
'title'=>'Calculate Deductible',
'page callback'=>'drupal_get_form',
'page arguments'=>array('deductible_simple_form'),
'access arguments' => array('administer user'),
'type' => MENU_CALLBACK,
);
//watchdog('Deductibe', '1', array(), WATCHDOG_DEBUG);
$items['deductible/display_results'] = array(
        'access arguments' => array('administer user'),
        'page callback' => 'display_results',
        'access callback' => TRUE,
        'type' => MENU_CALLBACK,
);
//watchdog('Deductibe', '2', array(), WATCHDOG_DEBUG);
return $items;
}

/*
function calculator_jquery_menu() {
  $items['calculator_jquery'] = array(
    'title' => "Craig's jquery calculator module",
    'description' => 'Demonstration of various JavaScript utilities',
    'page callback' => 'calculator_jquery_p',
    'access callback' => TRUE,
  );
  return $items;
}

function calculator_jquery_p(){
  // Set the path to our script.
  $script = drupal_get_path('module', 'calculator_jquery') . '/calculator_jquery.js';

  // Include a JavaScript file.
  $js = drupal_add_js($script);

 $build = array(
 //  '#type' => 'markup',
 //  '#markup' => '<p>This is an examples page.</p>',
  );

  return $build;
}*/

/*function my_color_data_entry_form_validate($node, &$form_state) {
    $user_entered_color = $form_state['values']['color'];
    $allowed_colors = array("red","blue","white");
    if (! in_array( trim($user_entered_color),$allowed_colors,false)) {
       form_set_error('color',
          "Invalid Entry, you must enter either red, white or blue"
       );
    } else {
     drupal_set_message(
      "You submitted a valid color: ".$form_state['values']['color']
     );
    }
}*/


function deductible_simple_form($form,&$form_submit){
      $form_state['redirect'] = 'deductilbe/display_results';
      $form['Make'] = array(
        '#type' => 'textfield',
        '#title' => t('Make'),
          '#size' => 30,
             '#cols' => 30,
          '#required'=>true,
        '#default_value'=>' ',
           '#rows' => 1,
        '#maxlength'=>30,
    //    '#weight'=>1,
      );
        $form['Model'] = array(
        '#type' => 'textfield',
        '#title' => t('Models'),
        '#size' => 30,
          '#cols' => 30,
        '#required'=>true,
        '#default_value'=>' ',
        //'#weight' => 7,
        '#rows' => 1,
        '#maxlength'=>30,
    //    '#weight'=>2,
      );
      $form['Deductible'] = array(
        '#type' => 'textfield',
        '#title' => t('Deductible'),
        '#size' => 30,
          '#cols' => 30,
          '#required'=>true,
        '#default_value'=>' ',
          //'#weight' => 7,
          '#rows' => 1,
        '#maxlength'=>30,
      //  '#weight'=>3,
      );
      $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Save'),
          //'#weight' => 7,
        '#submit' => array('deductible_submit'),
     //  '#weight'=>4,
      );
      return $form;
}

/**
 * Implementation of hook_perm().
 */
function deductible_perm() {
  return array('use save and edit', 'administer save and edit');
}

function display_results()
{
   // $db_result = db_query( "select name from {Deductible} ");
 /*   $db_result  = db_select('Deductible')
     ->fields(array('userid', 'Make', 'Model', 'Deductible'))
     ->orderBy('Make', 'DESC')
     ->execute();*/
   
/*    $result  = db_select('Deductible', 'c')
    ->fields('c',array('Make'))
    ->execute();*/
      $result = db_query("SELECT userid,make,model,deductible FROM {Deductible}");
     $listitems=array();
     $bigitems = array();
        foreach ($result as $node) {
         watchdog('Deductibe', 'hi', array(), WATCHDOG_DEBUG);
         $listitems=array($node->make,
            $node->model,
            $node->deductible);
           $bigitems[]=$listitems;
       }
     
    //   return print_r($bigitems);
    if (count($listitems) == 0)
        $make[] = array("No Models Entered Yet");
     else{
          watchdog('Deductibe', 'a', array(), WATCHDOG_DEBUG);
         }
       
      $link_to_add_form = l('Add More Models','deductible/calculate');
        $variable=array(
             'header' =>  array(t('Make'), t('Model'),t('Deductible')),
             'rows'  =>  $bigitems,
             'attributes' => array(),
             'caption' => NULL,
             'colgroups' => NULL,
             'sticky' => NULL,
             'empty' => NULL,
         );
        // return print_r($items);
    return theme_table($variable).'<br/>'.$link_to_add_form;
}

function deductible_submit($form, &$form_state){
  global $user;
  $userid = $user->uid;
  $Make = $form_state['values']['Make'];
  $Model = $form_state['values']['Model'];
  $Deductible = $form_state['values']['Deductible'];
/*  $calcdate = strtotime($formdate);
  $timeperiod = 90*86400;
  $formdatestore = $calcdate + $timeperiod;    */

  //      watchdog('Deductibe', 'deductible', array(), WATCHDOG_DEBUG);
   
      $insertquery = db_insert('Deductible')->fields(array(
    //  'userid' => $userid,
//      'insertdate' => $formdatestore,
      'Make'=>$form_state['values']['Make'],
       'model'=>$form_state['values']['Model'],
       'deductible'=>$form_state['values']['Deductible']
      ))->execute();
      if($insertquery!==false){
           $message = 'You have submitted the '  . ' form which contains the following data:<pre>' . print_r($form_state['values']['Make'],true) . '</pre>';
         drupal_set_message(t($message));
         $form_state['redirect'] = 'deductible/display_results';
      }else{
          drupal_set_message(t('Error-Contact Administrator'));
      }
    }

Tuesday, March 8, 2011

Logging in Drupal 7

 Logging in Drupal 7
 Debugging in Drupal 7

If you are coming from java world .logging is what you are looking for or missing it.


Drupal has inbuilt logging system called watchdog which is enabled by default
Click on Reports->Recent log Messages you will find current log entries.


Next step is in your code just place the below line where you want the logger


watchdog('name of your module as declared in your .info file ', 'some text', array(), WATCHDOG_DEBUG);


bingo you should see a logger in recent log messages

Please leave a comment if you like the article..