Flipkart

Showing posts with label Drupal. Show all posts
Showing posts with label Drupal. Show all posts

Thursday, July 21, 2011

Add Input Format to Textarea in Custom Module

To apply input formats to any textarea in our custom module forms we can use below code:

$form['format'] = filter_form(FILTER_FORMAT_DEFAULT);

example:
$form['body'] = array(
    '#type' => 'textarea',
    '#title' => t('Body'),
    '#default_value' => 'sample',
  );
$form['format'] = filter_form(FILTER_FORMAT_DEFAULT);


If you are creating Textarea under Fieldset then we have to apply filedset name to that format element as array like:

$form['filedset']['format'] = filter_form(FILTER_FORMAT_DEFAULT);

Wednesday, June 22, 2011

Drupal Module List

Here is the link where you can find all the module list based on the usage per week.

http://drupal.org/project/usage


Below you can find the video which explains the usage of the each module in real time.

http://gotdrupal.com/videos/top-drupal-modules


Monday, June 20, 2011

Reset admin(uid = 1) password in drupal 7

When the password for the user to Drupal (the administrator) is lost and the e-mail notification does not work, you can set the password via an SQL query.

But you must first generate a password hash that apply to your site.

Run the following commands from the command line, in the Drupal root directory:
For Linux:
./scripts/password-hash.sh newpassword

For Windows:
php .\scripts\password-hash.sh newpassword 

Then it will generate the Hash Password which somethink like
$S$CTo9G7Lx28rzCfpn4WB2hUlknDKv6QTqHaf82WHTsTHiod

Then execute the following query on the Drupal database:
UPDATE users SET pass ='thepasswordhash' WHERE uid = 1; 

OR you can use below code to get the Password:

require_once 'includes/password.inc';
echo user_hash_password('newpassword'); 
die();

Add above lines in index.php below this
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);


And refresh it .

Friday, June 17, 2011

Downloaded modules not showing up Drupal

There are mant reasons to not displaying downloaded modules in admin->site_build->modules. I f you face similar issue then please check below methods to resolve it

Run Cron Manually
Apply Permission to 755 to modules folder
Check whether same module is existing with other name(Check file names in side the module folder)
safe_mode should be OFF(check in phpinfo())

Friday, June 10, 2011

Implement Start Number and End Number of the Search Results in Drupal

Here is the code for implement start result and end result of the search results in Drupal.
 First we need to define Global variables of the Pager.


global $pager_page_array, $pager_total, $pager_total_items;

//establish page variables
  $total_pages = $pager_total['0'];
  $total_page_count = $total_pages - 1;
  //approx number of results based on page count
  $approx_results = $total_pages * 10;
  //calculate range
  $page_number = $pager_page_array['0'];
  $start_result = $page_number * 10 + 1;
  $end_result = $page_number * 10 + 10;

Customize "Your search yielded no results" Text in Search Results Drupal

Below is the sample code for customizing the "Your search yielded no results"  message in Template.php file

function theme_name_box($title, $content, $region = 'main') {

  if ($title == 'Your search yielded no results')

  {

    $title = 'Sorry, we couldn\'t find what you were looking for';
    $content = 'Check if your spelling is correct.';
}

 $output = '<div style="margin:10px"><h3>'. $title .'</h3>'. $content .'</div>';

  return $output;

}

Wednesday, June 8, 2011

Ajax Module With Image Button Drupal

If you are using Ajax module for Drupal Forms which having image button, then you can not submit the form.
To fix that kind of issue then we have to use  '#button_type' => 'submit ajax-trigger', attribute to submit button. Below is the sample code...

$path = drupal_get_path('theme', 'tradenet').'/images/image_button.png';
      $form['#ajax'] = array(
        'enabled' => TRUE
      );
      $form['submit'] = array(
             '#type' => 'image_button',
             '#access' => 1,
             '#button_type' => 'submit ajax-trigger',
             '#src'=>$path,
             '#ajax' => array('submitter' => TRUE ),

            
          );

Remove colon from label Drupal

To remove Colon from label for form elements just add this below code in to your template.php of the active theme. And replace Theme with your theme name. You can find Original code at includes/form.inc

 
function theme_form_element($element, $value) {
  // This is also used in the installer, pre-database setup.
  $t = get_t();

  $output = '


  if (!empty($element['#id'])) {
    $output .= ' id="'. $element['#id'] .'-wrapper"';
  }
  $output .= ">\n";
  $required = !empty($element['#required']) ? '*' : '';

  if (!empty($element['#title'])) {
    $title = $element['#title'];
    if (!empty($element['#id'])) {
      $output .= ' \n";
    }
    else {
      $output .= ' \n";
    }
  }

  $output .= " $value\n";

  if (!empty($element['#description'])) {
    $output .= '
'. $element['#description'] ."
\n";
  }

  $output .= "
\n";

  return $output;
}

Friday, June 3, 2011

Drupal 7 supports RDF

RDF (Resource Description Framework), which is a standard for encoding metadata and other information on the Semantic Web. In the Semantic Web, data processing applications using the dissemination of structured information in a decentralized and distributed all over the web today. RDF is an abstract, how to break information into separate pieces, and even if it is more popularly known in / RDF XML syntax, RDF can be stored in different formats. This article discusses the abstract RDF model, two specific serialization formats such as RDF is used and how it differs from the standard XML, the higher the level of the RDF semantics, best practices, implementation and querying RDF data sources.

Here are the some good Video Tutorials about RDF:




Thursday, May 12, 2011

Apply a patch to a drupal Module from Windows

Using Eclips we can easily apply patch to drupal module.Below are the steps..


Eclipse
To apply patches to code using Eclipse:

1. Menu > windows > open perspective > others > team synchronizing
2. Open the patch file, select all text and copy it to clipboard (Ctrl+ C)
3. Menu > project > apply patch
4. Select clipboard, click next, select the file you want to patch, click finish or next to setup patching options.

Friday, March 18, 2011

extend CCK-fields with custom formatters

We can create new custom formatter for CCK fields using hook_field_formatter_info(), below is the example


/**
* Implementation of hook_field_formatter_info().
*/
function myModule_field_formatter_info() {
 
$formatters = array();
  if (
module_exists('filefield')) {
     
$formatters['myFormatter'] = array(
       
'label' => t('My Formatter'),
       
'field types' => array('filefield'),
       
'multiple values' => CONTENT_HANDLE_CORE,
      );
  }
  return
$formatters;
}
/**
* Theme function for myFormatter from hook_field_formatter_info.
* @param $element
*   an array of formatter info and the item to theme. look in $element['#item'] for the field item to theme.
*/
function theme_myModule_formatter_myFormatter($element) {
  return
"themed element"
}
/**
* Implementation of hook_theme().
*/
function myModule_theme($existing, $type, $theme, $path) {
  return array(
   
'myModule_formatter_myFormatter' => array(
     
'arguments' => array('element' => NULL),
    ),
  );
}
?>

Monday, November 15, 2010

drupal_set_message() in user_logout

http://drupal.org/node/754560


   $cookieParams = session_get_cookie_params();
    session_start();
    session_set_cookie_params($
cookieParams);
  // Load the anonymous user
  $user = drupal_anonymous_user(session_id());
  drupal_set_message(t('You have successfully logged out of the system. Enter your Username and Passwords below to login again.'));

Thursday, October 28, 2010

drupal_get_form() for returning a node form

// required for Drupal 6
module_load_include('inc', 'node', 'node.pages');
// which nodeform you want
$node_type = 'YOURNODETYPE';
$form_id = $node_type . '_node_form';
// maybe add current users info
global $user;
// create a blank node

$node->uid = $user->uid;
$node->name = (isset($user->name) ? $user->name : '');
$node->type = $node_type;

// Invoke hook_nodapi and hook_node
node_object_prepare($node);
// Or you can also use an exiting node, for example
// $node = node_load(123);
// and the display the form:
$output = drupal_get_form($form_id, $node);

---------------------------------------------------------------------------------------
For User Edit Form:

include_once drupal_get_path('module', 'user') . '/user.pages.inc';
global $user;
 $output = "";
 $account = user_load($user->uid);
 $category = 'account';
//  print_r($userInfo);
 $output = drupal_get_form('user_profile_form', $account, $category);
return $output;

Friday, September 3, 2010

Drupal l() With complex link with image Example

$img = '< img src="'.$base_path . $directory . '/images/rssIcon.png" >';
l($img, 'user/3', array('attributes' => array('class' => 'link', 'id' => 'xxx', 'title' => 'Title'), 'html' => 'true'));

Monday, August 2, 2010

Add JS and CSS files in *.tpl.php in Drupal6

function yourtheme_preprocess_node(&$variables) {
if ($your_condition) {
drupal_add_css(path_to_theme(). "/filename.css", "theme");
$variables['styles'] = drupal_get_css();

drupal_add_js(file_directory_path() .'/javascript.js', 'inline');
$vars['scripts'] = drupal_get_js();
}
}

Wednesday, April 21, 2010

Drupal: Turn off Register_Globals

Method 1

Place a file called php.ini in your accounts root directory with the following content: register_globals = false (you can also try using 'off', or '0'instead of 'false').

Method 2

Place a file called .htaccess in your acccounts root directory with the following content:
php_flag register_globals off

Monday, March 22, 2010

Create Multisite in Drupal

To create multisite in drupal we need to change hosts configuration file as follows:
Windows/System32/drivers/etc/hosts (for windows)
And add new line like
127.0.0.1 loclahost
127.0.0.1 subdomain

after that just craete a folder called subdomian in drupal6/sites, then copy the settings.php file in newly created folder.Once done all the above steps Just type the URL like http;//subdomain/drupal6 in your browser then it will install new site.

If you want to create a url like just http://subdomain then you need create the Virtualhost in httpd.conf file like,


< VirtualHost *:80 >
DocumentRoot C:/xampp/htdocs/drupal6
ServerName subdomain

< /VirtualHost >

Wednesday, March 10, 2010

Drupal Pagination using pager_query()

This is the simplest pagination method using pager theme in Drupal, we can customize the links using pagination.inc file in includes folder also.

$limit = 7;
$query = "select nid,title from {node} where type='event'";
$count = "select count(*) from {node} where type='event'";

  $result = pager_query($query, $limit , 0, $sql_count);
  $output .= theme('pager', NULL, $items_per_page, 0);


GROUP BY

Queries with GROUP BY clauses need special care. Copied from the documentation on pager_query:

Unfortunately, the rewrite rule does not always work as intended for queries that already have a "COUNT(*)" or a "GROUP BY" clause, and possibly for other complex queries. In those cases, you can optionally pass a query that will be used to count the records. For example, if you want to page the query "SELECT COUNT(*), TYPE FROM node GROUP BY TYPE", pager_query() would invoke the incorrect query "SELECT COUNT(*) FROM node GROUP BY TYPE". So instead, you should pass "SELECT COUNT(DISTINCT(TYPE)) FROM node" as the optional $count_query [fourth] parameter.

Wednesday, September 16, 2009

Write Module in Drupal

//$id$

function form_help($path, $arg) {
$output = ''; //declare your output variable
switch ($path) {
case "admin/help#form":
$output = '
'. t("Write CRUD functionalities") .'
';
break;
}
return $output;
}



/**
* Valid permissions for this module
* @return array An array of valid permissions for the onthisdate module
*/
function form_perm() {
return array('access form content');
}



/**
* Implementation of hook_block
* @param string $op one of "list", "view", "save" and "configure"
* @param integer $delta code to identify the block
* @param array $edit only for "save" operation
**/
function form_block($op = 'list', $delta = 0, $edit = array()) {
if ($op == "list") {
// Generate listing of blocks from this module, for the admin/block page
$block = array();
$block[0]["info"] = t('On CRUD FORM');
return $block;
}

else if ($op == 'view') {

// Generate our block content

// Get today's date
$today = getdate();

// calculate midnight one week ago
$start_time = mktime(0, 0, 0,
$today['mon'], ($today['mday'] - 7), $today['year']);

// we want items that occur only on the day in question, so
// calculate 1 day
$end_time = time()/*$start_time + 86400*/;
// 60 * 60 * 24 = 86400 seconds in a day

$limitnum = variable_get("form_maxdisp", 3);


$query = "SELECT nid, title, created FROM " .
"{node} WHERE created >= %d " .
"AND created <= %d"; $query_result = db_query_range($query, $start_time, $end_time, 0, $limitnum); $block_content = ''; while ($links = db_fetch_object($query_result)) { $block_content .= l($links->title, 'node/'. $links->nid) .'
';
}
// check to see if there was any content before returning
// the block view
if ($block_content == '') {
// no content from a week ago
$options = array( "attributes" => array("title" => t("More events on this day.") ) );
$link = l( t("more"), "form", $options );

$block_content .= "
" . $link . "
";
$block['subject'] = 'CRUD FORM';
$block['content'] = 'Sorry No Content';
return $block;
}

// set up the block
$block = array();
$block['subject'] = 'CRUD FORM';
$block['content'] = $block_content;
return $block;
// more coming...
}

}



function form_admin() {
$form = array();

$form['form_maxdisp'] = array(
'#type' => 'textfield',
'#title' => t('Maximum number of links'),
'#default_value' => variable_get('form_maxdisp', 3),
'#size' => 2,
'#maxlength' => 2,
'#description' => t("The maximum number of links to display in the block."),
'#required' => TRUE,
);

return system_settings_form($form);
}

function form_admin_validate($form, &$form_state) {
$maxdisp = $form_state['values']['form_maxdisp'];
if (!is_numeric($maxdisp)) {
form_set_error('form_maxdisp', t('You must enter an integer for the maximum number of links.'));
}
else if ($maxdisp <= 0) { form_set_error('form_maxdisp', t('Maximum number of links must be positive.')); } } function form_menu() { $items = array(); $items['admin/settings/form'] = array( 'title' => 'On this date module settings',
'description' => 'Description of your On this date settings page',
'page callback' => 'drupal_get_form',
'page arguments' => array('form_admin'),
'access arguments' => array('access administration pages'),
'type' => MENU_NORMAL_ITEM,
);

$items['form'] = array(
'title' => 'On Form',
'page callback' => 'form_all',
'access arguments' => array('access form content'),
'type' => MENU_CALLBACK
);
$items['empform'] = array(
'title' => 'ADD Employee Details',
'page callback' => 'form_add',
'access arguments' => array('access add employees content'),
'type' => MENU_CALLBACK
);
$items['emplist'] = array(
'title' => 'ADD Employee Details',
'page callback' => 'emp_list',
'access arguments' => array('access list employees content'),
'type' => MENU_CALLBACK
);
$items['empedit'] = array(
'title' => 'Edit Employee Details',
'page callback' => 'emp_edit',
'access arguments' => array('access edit employees content'),
'type' => MENU_CALLBACK
);
return $items;
}
function form_add() {
$page_content = '';


$page_content .= drupal_get_form('form_add_form');
return $page_content;
}

function form_add_form() {

if(isset($_GET['id'])) {
//print_r($_GET['id']);
$res = db_query("select * from employees where id=".$_GET['id']);
$data = db_fetch_object($res);
$ename = $data->ename;
$add1= $data->add1;
}

$form = array();

$form['ename'] = array(
'#type' => 'textfield',
'#size' => 25,
'#id' => 'ename',
'#title' => t('Employee Name'),
'#default_value' => ($ename ? $ename : ''),
'#required' => TRUE,
);
$form['add1'] = array(
'#type' => 'textarea',
'#id' => 'add1',
'#cols' => 25,
'#rows' =>2,
'#resizable' => false,
'#default_value' => ($add1 ? $add1 : ''),
'#title' => t('Address1'),
);
$form['add2'] = array(
'#type' => 'textarea',
'#id' => 'add2',
'#cols' => 25,
'#rows' =>2,
'#resizable' => false,
'#default_value' => ($data->add2 ? $data->add2 : ''),
'#title' => t('Address2'),
);
$form['phone'] = array(
'#type' => 'textfield',
'#size' => 25,
'#id' => 'phone',
'#default_value' => ($data->phone ? $data->phone : ''),
'#title' => t('Phone Number'),

);
$form['email'] = array(
'#type' => 'textfield',
'#size' => 25,
'#id' => 'email',
'#title' => t('Email'),
'#default_value' => ($data->email ? $data->email : ''),
'#required' => TRUE,
);
$form['salary'] = array(
'#type' => 'textfield',
'#size' => 25,
'#id' => 'salery',
'#default_value' => ($data->salary ? $data->salery : ''),
'#title' => t('Salary'),

);
$form['dept'] = array(
'#type' => 'textfield',
'#size' => 25,
'#id' => 'dept',
'#default_value' => ($data->dept ? $data->dept : arg(4)),
'#title' => t('Department'),

);
if(isset($_GET['id'])) {

$form['id'] = array(
'#type' => 'hidden',
'#title' => t('Name'),
'#default_value' =>$data->id,
);


$form['update'] = array(
'#type' => 'submit',
'#value' => t('Update')
);
}else{
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit')
);
}
return $form;
}
function form_add_form_validate($form_id, $form) {

if (!valid_email_address($form['values']['email'])) {
form_set_error('email', 'Please enter valid Email');
}

}
function form_add_form_submit($from_id, $form_values) {
//print_r($form_values);
if(isset($form_values['values']['id'])) {
db_query("update employees set ename='".$form_values['values']['ename']."',add1='".$form_values['values']['add1']."',add2='".$form_values['values']['add2']."',phone='".$form_values['values']['phone']."',email='".$form_values['values']['email']."',salary='".$form_values['values']['salary']."',dept='".$form_values['values']['dept']."' where id='".$form_values['values']['id']."'");
}else{
db_query("insert into employees(ename,add1,add2,phone,email,salary,dept) values('".$form_values['values']['ename']."','".$form_values['values']['add1']."','".$form_values['values']['add2']."','".$form_values['values']['phone']."','".$form_values['values']['email']."','".$form_values['values']['salary']."','".$form_values['values']['dept']."')");
}
drupal_goto('emplist');

}

function emp_list() {
$page_content = '';
$page_content = 'Add Employees';
$page_content .= drupal_get_form('emp_list_form');
return $page_content;
}

function emp_list_form() {
$form = array();
$list = db_query('select * from employees');
while($res = db_fetch_array($list)) {
$data[] = $res;//print_r($res);
}

$cn = count($data);
for($i=0;$i<$cn;$i++) { $form['check'.$i] = array( '#type' => 'checkbox',
'#default_value'=> 0,
'#return_value' => $data[$i]['id'],
'#title'=> t($data[$i]['ename'].'    Edit')
);
}
$form['count'] = array(
'#type' => 'hidden',
'#title' => t('Name'),
'#default_value' =>$cn,
);

$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Delete Selected')

);
return $form;
}

function emp_list_form_submit($form_id,$form_values) {
//print_r($form_values['values']);
for($i=0;$i<$form_values['values']['count'];$i++) { if($form_values['values']['check'.$i] != '') { $empids[] = $form_values['values']['check'.$i]; } } //print_r($empids); $cnt = count($empids); foreach($empids as $key=>$value) {
db_query('delete from employees where id="'.$value.'"');

}
drupal_goto('emplist');
}


// function emp_edit() {
//
// $page_content = '';
// $page
//
// }



















function form_all() {
// content variable that will be returned for display
$page_content = '';

// Get today's date
$today = getdate();

// calculate midnight one week ago
$start_time = mktime(0, 0, 0, $today['mon'], ($today['mday'] - 7), $today['year']);

// we want items that occur only on the day in question,
// so calculate 1 day
$end_time = time();
// 60 * 60 * 24 = 86400 seconds in a day

$query = "SELECT nid, title, created FROM " .
"{node} WHERE created >= '%d' " .
" AND created <= '%d'"; // get the links (no range limit here) $queryResult = db_query($query, $start_time, $end_time); while ($links = db_fetch_object($queryResult)) { $page_content .= l($links->title, 'node/'.$links->nid) . '
';
}
if ($page_content == '') {
// no content from a week ago, let the user know
$page_content = "No events occurred on this site on this date in history.";
}
return $page_content;
// More coming....
}

function emptest_form() {
$form['#attributes'] = array('enctype' => "multipart/form-data");
$year = drupal_map_assoc(array('Select','2000','2001','2002','2003','2004'));
$form['select'] = array(
'#type' => 'select',
'#title' => t('Year'),
'#options' => $year
);
$form['radio'] = array(
'#type' => 'radios',
'#title' => 'Gender',
// '#default_value' => 1,
'#options' => array(t('Male'), t('Female')),
);
$today = getdate();
//$dt=$today['mday'].'/'.$today['mon'].'/'.$today['year'];
$form['date'] = array(
'#type' => 'date',
'#title' => t('date'),
'#default_value' => array('year' => $today['year'], 'month' => $today['mon'], 'day' => $today['mday']),
);
$form['upload'] = array(
'#type' => 'file',
'#title' => t('Attach new file'),
'#size' => 40,
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit')
);
return $form;

}
function emptest_form_submit($formid,$form_values) {
//print_r($_FILES['files']['name']['upload']);
$dir = drupal_get_path('module', 'fileupload') . '/files'; //echo base_path();
if(isset($_FILES['files']['name']['upload'])){
$name = $_FILES['files']['name']['upload'];
$size = $_FILES['files']['size']['upload'];
$type = $_FILES['files']['type']['upload'];
$tmp = $_FILES['files']['tmp_name']['upload'];
$file = file_save_upload('upload', array() , $dir);
if($file){
drupal_set_message("You uploaded $name, it is $size bytes, and has a mimetype of $type.");
}
else{
drupal_set_message("file upload failure");
}
}
}