term of taxonomy used as menu item in drupal

sometime our requirement is different that Drupal behaviour.
client wants to put some Taxonomy term as Primary menu. The taxonomy menu module adds links to the navigation menu for taxonomy terms.

(1) Install taxonomy menu module
(2) make some setting of taxonomy menu module

now we want to change path of these term in menu. it provides some hook for ..

/**
* Implementation of hook_taxonomy_menu_path.
*
* @return array
* function name => Display Title
* a list of the path options.
*/
function ess_public_taxonomy_menu_path() {

$output = array('ess_public_menu_path_default' => t('Ess Category Search'));

return $output;
}

/**
* Callback for hook_taxonomy_menu_path
*/

function ess_public_menu_path_default($vid, $tid) {
//if tid = 0 then we are creating the vocab menu item format will be taxonomy/term/$tid+$tid+$tid....

if ($tid == 0) {
//get all of the terms for the vocab
$path = "ess_public/search_result/category/";
}
else {
$path = taxonomy_term_path(taxonomy_get_term($tid));

if (variable_get('taxonomy_menu_display_descendants_'. $vid, FALSE)) {
//Use 'all' at the end of the path
$term = taxonomy_get_term($tid);
$path = "ess_public/search_result/category/".$term->name;

if (variable_get('taxonomy_menu_end_all_'. $vid, FALSE)) {
// $path .= '/all';
$term = taxonomy_get_term($tid);
$path = "ess_public/search_result/category/".$term->name;
}
else {
//we wait to run this instead of durning the if above
//because we only wan to run it once.
$terms = taxonomy_get_tree($vid, $tid);
foreach ($terms as $term) {
$tids[] = $term->tid;
}
if ($tids) {
$end = implode(' ', $tids);
$path .= $end;
}
}
}
else
{
$term = taxonomy_get_term($tid);
$path = "ess_public/search_result/category/".$term->name;
}
}

return $path;
}

MySql sorting fields in which certain order.

MySql provides nice functionality to sort fields in certain order. This is very useful in scenarios where we have an enum Field represented as varchar and the values that it can hold are fairly static.

CHANNELS
——————————–
| ID | NAME | TYPE |
——————————–
TYPE field is a varchar that can take only SD, HD and 3D.

PROBLEM:

To get a list of channels sorted by TYPE in an order of SD, HD and 3D. This can be done in couple of different ways:
-- Using by FIELD
SELECT * FROM CHANNELS ORDER BY FIELD(TYPE, 'SD', 'HD', '3D');

-- Using by FIND_IN_SET
SELECT * FROM CHANNELS ORDER BY FIND_IN_SET(TYPE, 'SD,HD,3D');

programmatically create or add new Taxonomy Terms in drupal

To create a new taxonomy term through PHP you can use taxonomy_save_term(&$form_values) which is mainly intended for use as a helper function to by the real drupal taxonomy add term form.
The relevant term details are passed as parameter and the Term Id of the newly created taxonomy term is placed back in this array and can be accessed by the calling code.

here I explain small code to assign taxonomy term to node if taxonomy is new , first you save in taxonomy in db.

/**
* Save Node
*/
foreach($arrNodeIds as $intNodeId){
$objNodeInfo = node_load($intNodeId);
$arrTermsIds = getTermIds($_POST['txt_tag_val_'.$intNodeId]);
$objNodeInfo->taxonomy = $arrTermsIds;
node_save($objNodeInfo);
}
/**
* See If the term exists in the chosen vocabulary and return the tid; otherwise, add a new record.
* @param $strTerms
* - Terms Name
* @return
* - Terms Ids
*/
function getTermIds($strTerms){
$arrTerms = explode(",",$strTerms);
if(!is_array($arrTerms)){
$arrTerms[0] = $strTerms;
}
foreach ($arrTerms as $strTerm){
if(strlen($strTerm) > 0){
$possibilities = taxonomy_get_term_by_name(trim($strTerm));
$intTermTid = NULL;
foreach ($possibilities as $possibility){
$intTermTid = $possibility->tid;
}
// Check new term , If yes then insert this new term in db
if (!$intTermTid){
$arrParam = array('vid' => 2, 'name' => $strTerm);
$status = taxonomy_save_term($arrParam);
$intTermTid = $arrParam['tid'];
}
$arrTermIds[] = $intTermTid;
}
}
return $arrTermIds;
}

/**
* add a new record as Term of Texonomy.
* @param $arrParam
* - param (vid , name)
* @return
* - status
*/
function addTaxonomyTerm($arrParam){
$vid = $arrParam['vid'];
$name = trim($arrParam['name']);
return taxonomy_save_term($form_values);
}

Create block by drupal code

If you most likely want to generate a block using code / programming , it is simple develope following code for that as I explain here.

Once you know the module and the delta, It is simple for creating the block.
The trick is you need to send an object with the right parameters. The code below should get you started. Remember this code may be different in Drupal7

/**
* Load drupal Block By Delta & Module
*
* @param $strModule
* - Module Name
*
* @param $intDelta
* - Module Name
*
* @return
* - Themed Block HTML
*/

function loadDrupalBlock($strModule, $intDelta) {
$block = new stdclass(); // empty object
$module = $strModule;
$delta = $intDelta; // could also be a string

$array = module_invoke($module, 'block', 'view', $delta);
if (isset($array) && is_array($array)) {
foreach ($array as $k => $v) {
$block->$k = $v;
}
}
$block->module = $module;
$block->delta = $delta;
return theme('block', $block);
}


This is calling by this way
$staticBlockHtml = loadDrupalBlock('block', 7);

Delete many thousands of nodes

We recently had reason to delete over a thousand Drupal 6 nodes of the same type,
but we wanted to leave all other content on the site intact.

What do you do when you want to delete multiple nodes from a drupal site?
You go to admin » content and then delete nodes one by one or delete up to 50 nodes at one time?

In this example we will delete all nodes of a particular type (page), It is quick way to delete


$node_type = 'image_album'; //fetch the nodes we want to delete
$result = db_query("SELECT nid FROM {node} WHERE type='%s'",$node_type);
while ($row = db_fetch_object($result)){
node_delete($row-?>nid);
$deleted_count+=1;
}
//simple debug message so we can see what had been deleted.
drupal_set_message("$deleted_count nodes have been deleted");

conformation alert using javascript

Sometimes it is useful to display a confirmation message before processing any action. Some application often asks for confirmation before doing something irreversible, like deleting content. 
the user to conform once again the deleting process. Here the user can change his mind and can cancel the operation or conform his action by clicking the submit button.

function confirmDelete(item){
 var strMsg = "Are you sure you want to delete this "+item+" ? ";
 var intAgree = confirm(strMsg);
 if (intAgree)
  return true ;
 else
  return false ;
}


Pass an array from an HTML form using Hidden field

It is simple way to pass your array using hidden field of form and get to another side  where you want to use this array's value


Snippet

Create Array

$arrNodeIds = array();
foreach ($data as $k => $objNode) {
$arrNodeIds[] = $objNode->nid;
}

Assign array to hideen field of form
<form method="post" action="/ess_upload/save_images">
<input type="hidden" name="hdnArrNodeIds" value="">
</form>

Get value from other side

$arrNodeIds = unserialize(urldecode($_POST["hdnArrNodeIds"]));
foreach($arrNodeIds as $intNodeId){
    echo $intNodeId;
}

Check Node is Exists In Drupal

It is good way to check Node is exists or not bellow example code would be helpful 

In this example , If node is exists in our database, then It will be deleted. otherwise give a error message and redirect to perticular page.

Example :
  $bolIsNodeAvail = node_load(array('nid' => $intNodeId)); 
  if($bolIsNodeAvail != false)
  {
        node_delete($intNodeId);  
  }else{
        drupal_set_message(t("node id is not exists."), 'error');  
  }
  drupal_goto('ess_upload/album_images');
 

Insert and Update Record using drupal_write_record()

It saves a record to the database based upon the schema.

you can simply call the new drupal_write_record function telling it what database table to write to and the information to write and the function will do the rest. SO you'll find yourself writing less and less of those long db_query insert and update commands!

Insert Record To Table
This would insert all the data in the $node object into the node database table.

drupal_write_record('node', $node);

Example :
$objFile = new stdClass();
$objFile->uid = $uId;
$objFile->filemime = $arrFile['str_file_mime'];
$objFile->filesize = $arrFile['int_file_size'];
$objFile->status = FILE_STATUS_PERMANENT;
$objFile->timestamp = time();
drupal_write_record('files', $objFile);


Update Record In Table
This would update the node in the node database table with the data in the $node object 
where nid is equal to the $node->nid

drupal_write_record('node', $node, 'nid')


Example :
$strFileExtension = getFileExtension($arrFile['str_orgin_file_name']);
$strFileNewName = $objFile->fid.".".$strFileExtension;
$objFile->filename = $strFileNewName;
$objFile->filepath = $arrFile['str_rel_file_path'].$uId.DIRECTORY_SEPARATOR.$strFileNewName;
drupal_write_record('files', $objFile,'fid');

How to do saved Node and get that node Id

I was trying to create a new node programatically by inserting information in node, I used below snippet.

  Saved Node

  $objNode = new StdClass();
  $objNode->title = utf8_encode($strTitle);
  $objNode->type = 'album_image';
  $objNode->status = 1;
  $objNode->moderate = 0;
  $objNode->promote = 0;
  $objNode->sticky = 0;
  $objNode->revision = 0;
  $objNode->comment = 0;
  $objNode = node_submit($objNode);

  $intTimestamp = time();
  $objNode->uid = $uId;
  $objNode->created = $intTimestamp;
  $objNode->changed = $intTimestamp;
  node_save($objNode);
 

  How to get the nid after node_save() in drupal 6

  Previously node_save() returned the $nid but not anymore... so what do we do? 

  It's simple. You have just saved a variable as your node. in our case we use $objNode 

  intInsertedNodeID = $objNode->nid;

  It is easy to use 

Pass Finnish character to ajax request and get junk character (skandinavian charachters)

I have found some of character passes ajax through php file and get stange output (skandinavian charachters)

I pass data with escape() function [escape(output)]. see in bellow snippet

Passed such string to ajax call:
Klikkaa lisätäksesi
tekstiä

and get result of such string
Klikkaa lis�t�ksesi
teksti�

what's problem occure in this script

var callBackActUrl = "dvk.eirikvae.aum"
var textdata = "text="+escape(output);
jQuery.ajax({
type: "POST",
url: callBackActUrl,
data: textdata,
cache: false,
success:function(responseText){
alert(responseText);

}
});


Solution :
I had read lot of artical on google and find solution for. I passed data in ajax using escape function, we replaced escape() function with
encodeURIComponent() and it is working proper.

var textdata = "text="+encodeURIComponent(output);

This method will encode certain chars that would normally be recognized as special chars for URIs.

How to disable resizable textarea in drupal

I am using the profile module but I remove the resizable textarea on the frontend of website.

There doesn't seem to be an option to enable/disable in drupal or even profile module so I tried implementing this:

Snippet :

function mymodule_form_alter(&$form,$form_state, $form_id){
if (
$form_id == 'user_register'){
$form['account_information']['profile_address']['#resizable'] = false;
}
}


It should only point to the profile module. I Couldn't find any other the right code.

Magento - Add External Javascript in CMS Static block

Template tags can be used on CMS pages in static blocks and in email templates also

Template tag is special tag, it has text surrounded by double curly braces which has a special meaning to Magento,
for example {{store url=""}}.

Problem :
I have one javascript , "slide_home.js" and want to include in one cms Static Blocks
This javascript file is in root-directory/js/commmon/slide_home.js

Solution : (you can write this line at top of static blocks [tine mce editor] )
/*

*/

learn more from here
http://inchoo.net/ecommerce/magento/magento-cms-syntax-part1/

Magento – Write Sql query

Simple step to execute MySQL query in Magento.
(1) Select SQL :

$objCon = Mage::getSingleton('core/resource')->getConnection('core_write');
$result = $objCon->query('SELECT 'entity_id' FROM 'catalog_product_entity');

if(!$result) {
$rows = $result->fetch(PDO::FETCH_ASSOC);
if(!$rows) {
print_r($rows);
}
}


(2) Insert SQL :

$objCon = Mage::getSingleton('core/resource')->getConnection('core_write');
$objCon->query("insert into table name (fields) values (values) ");

Mage_Cms_Block_Widget_Interface not found

when I was developing Widget of magento in Magento EE version 1.6 . I have spent lot of time behind to fin it out that Mage_Cms_Block_Widget_Interface is not working with Magento EE 1.6 version and got like this "PHP Fatal error: Interface 'Mage_Cms_Block_Widget_Interface' not found."

After I got information about this interface that It moved Mage_Cms_Block_Widget_Interface to Mage_Widget_Block_Interface in Magento EE version 1.6

Magento Admin login problem


Problem:

I had a new installation of magento. But I was unable to login as an administrator. I went to the admin login page, entered correct username and password but was redirected to the same login page. I could not enter the dashboard page. Error message is displayed when I enter wrong username or password. But nothing is displayed and I am redirected to the same login page when I insert correct username and password.

Solution:

I googled and found these solutions:-

1) Use 127.0.0.1 instead of localhost in your url, i.e. using http://127.0.0.1/magento/index.php/admin instead of
http://localhost/magento/index.php/admin . But this didn’t solve my problem.

2) Since I am using Windows XP, I was suggested to open “host” file from
C:\WINDOWS\system32\drivers\etc and have 127.0.0.1 point to something like magento.localhost or even 127.0.0.1 point to http://www.localhost.com . But this also didn’t work either.

3) This solution finally helped me out of this problem. The solution was to modify the core Magento code. Open app/code/core/Mage/Core/Model/Session/Abstract/Varien.php. Comment out the lines 80 to 83. The line number may vary according to the Magento version. But these lines are present somewhere near line 80. You have to comment the comma (,) in line: $this->getCookie()->getPath()//,

// set session cookie params
session_set_cookie_params(
$this->getCookie()->getLifetime(),
$this->getCookie()->getPath()//,
//$this->getCookie()->getDomain(),
//$this->getCookie()->isSecure(),
//$this->getCookie()->getHttponly()
);

Well, I am out of this problem. Hope, this solution you also help you.


Barcodes On your Web apps


The bar code is method of automatic identification and data collection.
Their use is widespread and the technology behind barcodes is constantly improving. Almost every item purchased from a grocery store, department store, and mass merchandiser has a UPC barcode on it. Now rarely will one come across any product that doesn’t have a barcode.

Varieties of barcodes
Barcodes bascially come in two main type: linear (1-dimensional) and Matrix (2-dimensional) with each offering a variety of formats, depending on your application purpose

(1) linear (1-dimensional) : The barcodes we usually see on books and other standard products are of the linear type. These only encode data in one dimension, from left to right. The following shows a typical UPC barcode.
(2) Matrix (2-dimensional) : They also come in patterns of squares, dots, hexagons and other geometric patterns within images termed 2D (2 dimensional) matrix codes or symbologies.

It is to use the PEAR::Image_Barcode class in PHP to dynamically create barcodes for Web applications. The backbone to the PEAR::Image_Barcode's ability to produce barcode images is in the GD library,If you haven't already installed PEAR, you will need to do so in order to get this application to work.


Installation
You can install Image_Barcode issuing the following command (as root):
# pear install Image_Barcode

You can get the latest code at the PEAR site:
http://pear.php.net/package/Image_Barcode/


Using Image_Barcode
Creating a barcode is as simple as calling the classes static draw() method.
The method has four parameters:

Text : string that shall be converted into barcode representation.
Type : this parameter determines which driver/type should be used; it is one of: Code39, code128, ean13, int25, postnet or upca.
Imgtype : determines the type of the image that is generated; one of jpg, png and gif.

By default, the image generated by the barcode driver is directly output to the browser. If you do not want this, pass false as fourth parameter and draw() will return the GD image resource object; allowing you to do further things with it.

Example code
A sample code for generating a CODE128 barcode is shown below.

/* Data that will be encoded in the bar code */
$bar_code_data = "TRSD5656";

/* The third parameter can accept any from the following,
* jpg, png and gif.
*/
Image_Barcode::draw($bar_code_data, 'code128', 'png');
?>

Supported Types
The ‘Image_Barcode’ library supports the following barcode types:
* Code 39
* Code 128
* EAN 13
* INT 25
* PostNet
* UPCA