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


Thursday 26 July 2012

Magento: Find subcategories for a particular root category


We can use the below code to find all child categories for a particular root category in Magento


<?php
   
   //get category model

    $category_model = Mage::getModel('catalog/category'); 

 //$categoryid for which we have to find the child categories (root category id   or other parent category id)

    $_category = $category_model->load($categoryid); 

 //array that contains all child categories id
        
$all_child_categories = $category_model->getResource()->getAllChildren($_category);

foreach($all_child_categories as $childcatId)
{
   echo $childcatId; //// here you get child categories id
}

?>

Friday 13 July 2012

How to set different themes for logged in users?

Now you can change your magento theme for different users like logged in user and guest user

1. got to design/frontend/default/You theme/template/page
 find 1column.phtml,2columns-left.phtml,2columns-right.phtml,3columns.phtml,empty.phtml in all this files put below code above <html> tag


<?php
if(Mage::getSingleton('customer/session')->isLoggedIn()):
Mage::getDesign()->setPackageName('package_name')->setTheme('themename');
endif;
?>

ex.
if you put code like this


<?php
if(Mage::getSingleton('customer/session')->isLoggedIn()):
Mage::getDesign()->setPackageName('default')->setTheme('modern');
endif;
?>
than if user logged in site that time theme change to modern them and for guest user site theme is default that you set,
here instade of modern you can use your own theme so you store theme change according to user

may this post help you,
thank you....





Friday 30 March 2012

Get Cart items in magento


Using checkout session you can find all items that in cart and also get subtotal and grand total of cart

$items = Mage::getSingleton('checkout/session')->getQuote()->getAllItems();

foreach($items as $item) {
    echo 'ID: '.$item->getProductId().'<br />';
    echo 'Name: '.$item->getName().'<br />';
    echo 'Sku: '.$item->getSku().'<br />';
    echo 'Quantity: '.$item->getQty().'<br />';
    echo 'Price: '.$item->getPrice().'<br />';
    echo "<br />";
}

Get total items and total quantity in cart
$totalItems = Mage::getModel('checkout/cart')->getQuote()->getItemsCount();
$totalQuantity = Mage::getModel('checkout/cart')->getQuote()->getItemsQty();

Get subtotal and grand total price of cart
$subTotal = Mage::getModel('checkout/cart')->getQuote()->getSubtotal();
$grandTotal = Mage::getModel('checkout/cart')->getQuote()->getGrandTotal();

Browser Detection Code

You can detect your browser using below code


<?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);
?>

may this code help you to find out detail about your browser

Magento – How to Reset the Admin Password


Use any password for admin username and after that you can change your password:

Only need FTP Access:



Use any password for admin username:

Only need FTP Access :


To login into magento admin, using only ftp access is a little tricky. Through FTP open the class Mage_Admin_Model_User located at app\code\core\Mage\Admin\Model\User.php
Next find the authenticate() function around line no: 225. Inside the authenticate function, this code is written

$this->loadByUsername($username);

You need to add the line return true; after this i.e

$this->loadByUsername($username);
return true;

And that’s it..
now find username using below script :


<?php
require_once 'app/Mage.php';
umask(0);
Mage::app('');
$tprefix = (string) Mage::getConfig()->getTablePrefix();
echo "<br/>".$tprefix;
        $connection = Mage::getSingleton('core/resource')->getConnection('core_write');
$b=$connection->query("select * from ".$tprefix."admin_user ");
$t=0;
while($roes2=$b->fetch(PDO::FETCH_ASSOC)) 
{
$adminemail=$roes2['email'];
$adminuser=$roes2['username'];
echo $adminemail.'=>'.$adminuser.'<br/>';
}
?>
make one php file and past above code in it,after that put that php file in root and run it ex. if php file name is findadnim.php than run http://yourdomainname.com/findadmin.php
so you get all usernames of admin select any of them , now you login in admin using any password for. Since, we have skipped the code for password checking, login using any password and then change the password in admin from System -> Permission -> Users.

Programmatically Add Product In Cart in Magento

Adding a Product to the Cart via Querystring


For Simple Product :

$this->getUrl('checkout/cart').'add?product='.$pro_id.'&qty='.$qty.';
where : $pro_id= 'Product id' ; $qty = 'Product Quentity'

For Simple Product with Custome Option:

$this->getUrl('checkout/cart').'add?product = '.$pro_id.'&qty = '.$qty.'&options['.$pro_value.'] = '.$pro_opt_val.'
where : $pro_value= 'Product option_id';$pro_opt_val= 'Product option_type_id';

For Bundle Product :

$this->getUrl('checkout/cart').'add/product/['.$pro_id.']/?bundle_option[['.option_id.']][]=['.selection_id.']

like if bundle product's id is 2790 than :
      $_product = Mage::getModel('catalog/product')->load(2790);
      if ($_product->getTypeId() == 'bundle') 
     {
        $w = Mage::getSingleton('core/resource')->getConnection('core_write');
        $result = $w->query("select `option_id`, `selection_id` from `catalog_product_bundle_selection` where        `parent_product_id`=$id");
        $route = "checkout/cart/add";
        $params = array('product' => $id);
        while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
            $params['bundle_option['. $row[option_id] .']'][] = $row['selection_id'];
       };
        header("Location: ". Mage::getUrl($route, $params));
   }

For Adding a Configurable Product to the Cart via Querystring:

http://www.your_domain.com/checkout/cart/add?product = 68&qty = 1&super_attribute[528] = 55& super_attribute[525] = 56


Here  68  is the product entity id displayed in magento admin panel.  528 and 525  is the attribute associated with this product and  55 and 56  is the selected value of that attribute. 

Another way to add product in cart :

For Simple Product :

$params = array(
    'product' => 23,
    'qty' => 2,
);
$cart = Mage::getSingleton('checkout/cart'); 
$product = new Mage_Catalog_Model_Product();
$product->load(23); 
$cart->addProduct($product, $params);
$cart->save(); 
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);



For  Configurable  Product  :



$params = array(
    'product' => 23,
    'super_attribute' => array(
         528 =>55,
    ),
    'qty' => 2,
);

$cart = Mage::getSingleton('checkout/cart'); 
$product = new Mage_Catalog_Model_Product();
$product->load(23); 
$cart->addProduct($product, $params);
$cart->save(); 
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);

Programmatically Create New Magento Admin User


<?php
/*
 * Create New Admin User
 */


//define USERNAME, EMAIL and PASSWORD below whta ever you want and uncomment this 3 lines (remove # sign)


#define('USERNAME','admin');
#define('EMAIL','xyz@xyz.com');
#define('PASSWORD','admin123');




if(!defined('USERNAME') || !defined('EMAIL') || !defined('PASSWORD')){
echo 'Edit this file and define USERNAME, EMAIL and PASSWORD.';
exit;
}


//load Magento
$mageFilename = 'app/Mage.php';
if (!file_exists($mageFilename)) {
echo $mageFilename." was not found";
exit;
}
require_once $mageFilename;
Mage::app();


try {
//create new user write you firstname,lastname
$user = Mage::getModel('admin/user')
->setData(array(
'username'  => USERNAME,
'firstname' => 'Gz',
'lastname' => 'Chauhan',
'email'     => EMAIL,
'password'  => PASSWORD,
'is_active' => 1
))->save();


} catch (Exception $e) {
echo $e->getMessage();
exit;
}


try {
//create new role
$role = Mage::getModel("admin/roles")
->setName('Inchoo')
->setRoleType('G')
->save();

//give "all" privileges to role
Mage::getModel("admin/rules")
->setRoleId($role->getId())
->setResources(array("all"))
->saveRel();


} catch (Mage_Core_Exception $e) {
echo $e->getMessage();
exit;
} catch (Exception $e) {
echo 'Error while saving role.';
exit;
}


try {
//assign user to role
$user->setRoleIds(array($role->getId()))
->setRoleUserId($user->getUserId())
->saveRelations();


} catch (Exception $e) {
echo $e->getMessage();
exit;
}


echo 'Admin User sucessfully created!<br /><br /><b>THIS FILE WILL NOW TRY TO DELETE ITSELF, BUT PLEASE CHECK TO BE SURE!</b>';
@unlink(__FILE__);


?>

create php file like newuser.php and past above code in that file, put newuser.php file in magento root and run script like http://yourdomain.com/newuser.php thats it, now you can login in magento admin using username and password that you enter above code