Tuesday 21 August 2012

Magento - Creating and Showing a static block in Frontend

The content of the blocks are created and modified from Magento Admin panel which can be placed on one or multiple pages. To create a static block you can follow some simple steps which are given bellow.

Creating a Static Block:


A. Go to the Magento Admin panel and then select the  CMS -> Static Blocks.
B. Then Click on the “Add New Block” button from the right top .
C. Now fillup the following fields:
  1. Block Title: Give the Name of the static block here. This will not show on the frontend.
  2. Identifier: Give the id of this block. It used as reference of this block, when adding to a template file or CMS page.
  3. Status: Its define visibility of this static block on the frontend.
  4. Content: Content of static block can be plain text, HTML code and Javascript. PHP code can’t use in this area.
D. After fillup all fields then click on “Save Block” button from the right top .

Showing a Static Block in Frontend:


A static block can be added to display on the frontend by some different ways which are discribed bellow:

1. Adding a static block to a CMS page From the Magento admin:
Go to CMS > Pages and click on a pre-existing page or create a new page where you want to show your static block.
Now use the following code in the Content field of the CMS page:

{{block type="cms/block" block_id="your_block_identifier" template="cms/content.phtml"}}

2. Adding a static block by using template phtml file:
Open your phtml file where you want to add the static block.
For Example: /app/design/frontend/your-instance-name/your_theme/template/callouts/right_col.phtml
Then you can use the following code in your phtml file to show the content of your ststic block:

<?php echo $this->getLayout()->createBlock('cms/block')->setBlockId('your_block_identifier')->toHtml() ?>




3. Adding a static block by using XML layout file:
Use the following code to show the content of static block by using Layout XML file:


<reference name="content/left/right">
       <block type="cms/block" name="your_block_name" before="-">
        <action ethod="setBlockId"><block_id>your_block_identifier</block_id></action>
      </block>
 </reference>


Note: You can use the above code to show the block content in specific page by using “ Layout Update XML ” field of CMS page.
To do this go: CMS -> pages from your magento backend. Then click on on that page where you want to show the static block.
Then click on Design tab from left panel like:

Now Past the above code in Layout Update XML  field.
here i wrote <reference name=”content/left/right”> in code. You must use only one like- content / left or right as your reference name.



PHP - Browser Detection code

Past below code in you site to detecte browser : 

<?php
function getBrowser()
{
    $u_agent = $_SERVER['HTTP_USER_AGENT'];
    $bname = 'Unknown';
    $platform = 'Unknown';
    $version= "";

    //First get the platform?
    if (preg_match('/linux/i', $u_agent)) {
        $platform = 'linux';
    }
    elseif (preg_match('/macintosh|mac os x/i', $u_agent)) {
        $platform = 'mac';
    }
    elseif (preg_match('/windows|win32/i', $u_agent)) {
        $platform = 'windows';
    }
   
    // Next get the name of the useragent yes seperately and for good reason
    if(preg_match('/MSIE/i',$u_agent) && !preg_match('/Opera/i',$u_agent))
    {
        $bname = 'Internet Explorer';
        $ub = "MSIE";
    }
    elseif(preg_match('/Firefox/i',$u_agent))
    {
        $bname = 'Mozilla Firefox';
        $ub = "Firefox";
    }
    elseif(preg_match('/Chrome/i',$u_agent))
    {
        $bname = 'Google Chrome';
        $ub = "Chrome";
    }
    elseif(preg_match('/Safari/i',$u_agent))
    {
        $bname = 'Apple Safari';
        $ub = "Safari";
    }
    elseif(preg_match('/Opera/i',$u_agent))
    {
        $bname = 'Opera';
        $ub = "Opera";
    }
    elseif(preg_match('/Netscape/i',$u_agent))
    {
        $bname = 'Netscape';
        $ub = "Netscape";
    }
   
    // finally get the correct version number
    $known = array('Version', $ub, 'other');
    $pattern = '#(?<browser>' . join('|', $known) .
    ')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#';
    if (!preg_match_all($pattern, $u_agent, $matches)) {
        // we have no matching number just continue
    }
   
    // see how many we have
    $i = count($matches['browser']);
    if ($i != 1) {
        //we will have two since we are not using 'other' argument yet
        //see if version is before or after the name
        if (strripos($u_agent,"Version") < strripos($u_agent,$ub)){
            $version= $matches['version'][0];
        }
        else {
            $version= $matches['version'][1];
        }
    }
    else {
        $version= $matches['version'][0];
    }
   
    // check if we have a number
    if ($version==null || $version=="") {$version="?";}
   
    return array(
        'userAgent' => $u_agent,
        'name'      => $bname,
        'version'   => $version,
        'platform'  => $platform,
        'pattern'    => $pattern
    );
}

// now try it
$ua=getBrowser();
$yourbrowser= "Your browser: " . $ua['name'] . " " . $ua['version'] . " on " .$ua['platform'] . " reports: <br >" . $ua['userAgent'];
print_r($yourbrowser);
?>

Magento - Previous/Next link in product page


Below code Use for show previous/next link in product page:

open view.phtml file (app/design/frontend/base(or your theme interface)/default(your theme interface)/template/catalog/product/view.phtml)

past below code above <div class="product-view">

<!-- Product Navigation -->
<div id="product-navigation">
  <?php // Previous and Next product links in product page
      if ($this->helper('catalog/data')->getCategory()) {
         $cat = $this->helper('catalog/data')->getCategory();
      } else {
         $_ccats = $this->helper('catalog/data')->getProduct()->getCategoryIds();
         $cat = Mage::getModel('catalog/category')->load($_ccats[0]);
      }; //missing ";" causes 503 error for validation service
                
     $_product = $this->getProduct();
                 
     if(!$_product->getCategoryIds())
     return; // Don't show Previous and Next if product is not in any category
                 
                 
     $order = Mage::getStoreConfig('catalog/frontend/default_sort_by');
     $direction = 'asc'; // asc or desc
                 
     $category_products = $cat->getProductCollection()->addAttributeToSort($order, $direction);
     $category_products->addAttributeToFilter('status',1); // 1 or 2
     $category_products->addAttributeToFilter('visibility',4); // 1.2.3.4
                 
     $cat_prod_ids = $category_products->getAllIds(); // get all products from the category
     $_product_id = $_product->getId();
                 
     $_pos = array_search($_product_id, $cat_prod_ids); // get position of current product
     $_next_pos = $_pos+1;
     $_prev_pos = $_pos-1;
                 
     // get the next product url
    if( isset($cat_prod_ids[$_next_pos]) ) {
       $_next_prod = Mage::getModel('catalog/product')->load( $cat_prod_ids[$_next_pos] );
    } else {
       $_next_prod = Mage::getModel('catalog/product')->load( reset($cat_prod_ids) );
    }
      
    // get the previous product url
    if( isset($cat_prod_ids[$_prev_pos]) ) {
        $_prev_prod = Mage::getModel('catalog/product')->load( $cat_prod_ids[$_prev_pos] );
    } else {
        $_prev_prod = Mage::getModel('catalog/product')->load( end($cat_prod_ids) );
    }

    $more_url = $cat->getUrl();
    $nxtname=substr($_next_prod->getName(),0,25);
    $prvname=substr($_prev_prod->getName(),0,25);
    
  ?>
  <style>
   .prelinknav{float: left;width: 33%;font-size: 11px;text-align: left;}
   .nxtlinknav{float: left;width: 33%;font-size: 11px;text-align: right;}
   .catlinknav{float: left;width: 33%;font-size: 11px;text-align: center;}
   .product-view{float: left;}
                 
 </style>
 <div>
   <?php if($_prev_prod != NULL): ?>
    <div class="prelinknav"><a href="<?php print $_prev_prod->getUrlPath(); if($search_parameter):?>?search=1<?php endif;?>" ><span 

style="font-weight: bolder;"><?php echo $this->__('<<< PREVIOUS') ?></span>(<?php echo $prvname; ?>)</a></div>
   <?php endif; ?>
     <div class="catlinknav"><a href="<?= $more_url; ?>"><span style="font-weight: bolder;">Back</span>(<?php echo $cat->getName() ?>)

</a></div>
   <?php if($_next_prod != NULL): ?>
     <div class="nxtlinknav"><a href="<?php print $_next_prod->getUrlPath(); if($search_parameter):?>?search=1<?php endif;?>"><span 

style="font-weight: bolder;"><?php echo $this->__('NEXT') ?></span>(<?php echo $nxtname; ?>)<span style="font-weight: bolder;"><?php echo 

$this->__('>>>') ?></span></a></div>
   <?php endif; ?>
 </div>
</div>
<!-- end pagination nav -->

now check in frontend product view page

Magento - Product Price without decimal points

If you want to remove decimal points from Price ( front-end ) then use following steps :


Step 1:

Change the following file to remove the decimal points:

go to : lib/Zend/Currency.php

In the “toCurrency” function add the following line:

$options['precision'] = 0; around 184 line
above this :

$value    = Zend_Locale_Format::toNumber($value, array('locale'        => $locale,
                                                               'number_format' => $format,
                                                               'precision'     => $options['precision']));
replace to :
$value    = Zend_Locale_Format::toNumber($value, array('locale'        => $locale,
                                                               'number_format' => $format,
                                                               'precision'     => 0));


Step 2:

Change the following price to round the price:

app/code/core/Mage/Core/Model/Store.php

Change in method “roundPrice()” to the round prices in product listing and view pages like this:

return round(ceil($price), 0 );

like this :

public function roundPrice($price)
{
        //return round($price, 0);
        return round(ceil($price), 0 );
}

Please let me know if you have any questions