Magento: Working with URLs

Hello friends,

Before few weeks, while working with magento, we have a requirement to change some pages’ url and to remove index.php from urls.

To fulfill our requirement I have searched the web and got proper solution.

Where to remove the index.php from urls we have to enable “Web Server Rewrites” from Admin -> System -> Configuration -> Web -> Search Engine Optimization.

To change the url’s of CMS pages, we have to change the URL Key of CMS pages from Admin -> CMS -> Pages.

For Example: If we want to change the url of About Us page, then we have to go at Admin -> CMS -> Pages, select About Us page and change the URL Key of it.

And to change the url’s of categories, products and custom pages, we have to go in Admin -> Catalog -> URL Rewrite Management.

Here we can edit the url’s of particular category, product or custom page and we can add new url rewrite also.

For Example: If we want to rewrite the url of Contact Us page, then we have to add new custom url rewrite from Admin -> Catalog -> URL Rewrite Management.

Hope this will help you.

Advertisements

Customize Magento functionality: Override core code

The very first thing any beginner in magento development learns is this: DO NOT change core code! It is absolutely necessary that we don’t make our customizations in the base code of magento. The main reason for that is core files get overwritten when we upgrade to newer version of magento which in turn removes any changes whatsoever we did. Also it is best practice to just let the core alone and do changes elsewhere. That brings us to the topic of discussion: overriding magento core code.

So now we know WHY we need to override classes but HOW does it actually happen? For those of you who don’t know the basic structure of files/folders in magento, here is a quick look. There are two different themes applied to your magento site at any given point of time. The one you specifically select to be applied and the one that gets implemented by default in case your current theme fails due to any reason. Just like the theme (read design), the code is also implemented twofold. Magento looks for code to run in your current theme. If there is some file missing or some code missing it will go to the base theme and get the code/ design from there. So basically when you want to customize anything just write code for it in your current theme. So magento will execute that first.

This sounds nice and dandy.. Write our code in the current theme and changes will take effect. But when you create a module; things kind of change a little bit. You no longer work on the same file structure as your magento base. The module you created is not part of the magento that we get out of the box. Now you want to enhance some functionality of magento using your new module instead of making changes directly in your installation. The concept is still the same with a little bit of twist. You put the layout and templates of your module in the theme you want it to display in. So magento will run it from there.

But when you want to use some already existing functionality in magento a little differently you need to override the underlying code and write your own.I am going to describe how the whole process works from the scratch. There are only three basic steps you need to follow.

1) Copy core files in your module: Copy the core files that you are going to use for your own needs in your module.

2) Rename the class: Rename the class in your module’s file and extend it to the original class in that file.

3) Rewrite the class in the config file: By doing this you let magento know that you have created a new class and that it needs to be executed instead of the original class defined in the core file.

Let us check all three steps in detail now. Suppose you have created a module named Mymodule. It should be in the local folder of your magento root. The folder structure of your module will be like this.

app/code/local/Mynamespace/Mymodule

Now we want to use a class that is defined in the checkout module of core magento. We need to add some additional functionality when the user adds items to the cart. For that magento uses the file stored here.

app/code/core/Mage/Checkout/Model/Cart.php

We will override this class and put our additional function in it or maybe some updates in the existing functions. First copy this file to your module. I have a simple strategy when it comes to determining the place to copy core files in our modules. User the same structure as magento core is using. Helps us keep track of files and especially useful when some file is not getting called we can compare it to the core structure and IMHO it is just a clean approach. So copy this file in local so that file structure is like this :

app/code/local/Mynamespace/Checkout/Model/Cart.php

You can place the file anywhere in your namespace but it is advisable for the reasons above to put it where we can find it easily.The file is copied.

Now we come to the second step of our process. Rename the class. The original file has a class name that looks something like this.


class Mage_Checkout_Model_Cart extends Varien_Object{

//core code

}

What we need to do is rename the class to match the location that we just changed and extend it to this original class. So that it looks like this:


class Mynamespace_Checkout_Model_Cart extends Mage_Checkout_Mode_Cart{

//your code

}

You can either create new functions or add more code to make the already written functions in this class customized to your needs. Which takes us to our last and important step. Rewrite the class in config file. After adding your new class you now need to let magento know that you have created it and that it should run it first now in place of the original class. For that open the config file of your module, which is located at :

app/code/local/Mynamespace/Mymodule/etc/config.xml

Rewrite the class name in config file of the module under <models> tag as we are rewriting the class of a model.


<models>

<checkout>
             <rewrite>
                       <mage_chekcout_model_cart>Mynamespace_Checkout_Model_Cart</mage_chekcout_model_cart>
             </rewrite>
 </checkout>

</models>

And voila!! It’s done. Now cross your fingers and clear your cache! Test your module.

Keep coding 🙂

Posted in Magento. 1 Comment »

Create Shopping Cart Price Rules Programmatically in Magento

We can create Shopping Cart Price Rules from the Admin panel of our store from Promotions->Shopping Cart Price Rules. Click on “Add New Rule” button and Fill all the information about your shopping cart price rule with Conditions and Actions which you want.

The Shopping Cart Price Rules are to be applied when customer reaches to Shopping Cart Page or adds any product into cart.

The shopping cart price rule has divided into mainly 3 tabs which are following.

1). Rule Information:-

Here, you can specify the details of the rule like, Rule Name, Description, Status, accessibility, coupon code etc.

2). Conditions: –

In a conditions tab you can put the condition for applying the price rule on cart when the conditions will true then shopping cart price rule will be applied to the cart.

3). Actions: –

In an actions tab you can update the price of particular product and whole cart as well with Fixed Amount Discount, Percent of Product Price Discount, etc. and you can also put conditions for shopping cart price rules in Actions tab as well.

4). Labels: –

Here, you can specify label of price rule which will display on cart page.

I have created the example code of shopping cart price rule with following information.

-> The Rule will only be applied when the “Price” is greater than or equal to (>=) to 200.

-> The Rule will be applied explicitly on specific product as a percentage discount by certain amount of discount (Here: BY 25 PERCENT) of Currency Amount.


<?php

ini_set('max_execution_time', 600);
ini_set('memory_limit', '1024M');

require 'app/Mage.php';
$app = Mage::app('');

$labels = array('0'=>'25% off','1'=>'25% off','2'=>'25% off','3'=>'25% off');
$shoppingCartPriceRule = Mage::getModel('salesrule/rule');

$shoppingCartPriceRule
        ->setName("25% off")
        ->setDescription('Get 25% Discount on Product which price is greater than or equal to 200')
        ->setIsActive(1)
        ->setWebsiteIds(array(1))
        ->setCustomerGroupIds(array(0,1,2,3,4))
        ->setFromDate('')
        ->setToDate('')
        ->setSortOrder('')
        ->setSimpleAction('by_percent')
        ->setDiscountAmount(25)
        ->setStopRulesProcessing(0);

$priceCondition = Mage::getModel('salesrule/rule_condition_product')
        ->setType('salesrule/rule_condition_product')
        ->setAttribute('price’)
        ->setOperator('>=')
        ->setValue(200);

try
{
        $shoppingCartPriceRule->getActions()->addCondition($skuCondition);
        $shoppingCartPriceRule->save();
        $rule_id = $shoppingCartPriceRule->getId();
        $shoppingCartPriceRule = Mage::getResourceModel('salesrule/rule');
        $shoppingCartPriceRule->saveStoreLabels($rule_id,$labels);
}
catch (Exception $e)
{
        Mage::getSingleton('core/session')->addError(Mage::helper('catalog')->__($e->getMessage()));
        return;
}

?>

Magento: Get current page url

Hello friends,

Before few days, while working with magento, we have a requirement to get current page url.

To fulfill our requirement we have searched the web and got proper solution.

And to get current page url we have used under given code:


$this->helper('core/url')->getCurrentUrl();

Same as above code, we can use under given magento code lines to get base url of magento installation, to get url of media directory, to get url of skin directory and to get url of js directory respectively.


Mage::getBaseUrl();
Mage::getBaseUrl('media');
Mage::getBaseUrl('skin');
Mage::getBaseUrl('js');

Hope this will help you.

Posted in Magento. 1 Comment »

Magento:To Show Product Navigation on Product view page

hello friend,
for showing product navigation on product view page.then Add following code in view.phtml file after messages_product_view div.
<!– start pagination nav –>

<div class=”product-navigation”>
<?php
//Determine the previous/next link and link to current category

if ($this->helper(‘catalog/data’)->getCategory()) {
$_ccat = $this->helper(‘catalog/data’)->getCategory();
$_ccatname= $this->helper(‘catalog/data’)->getCategory()->getName();
} else {
$_ccats = $this->helper(‘catalog/data’)->getProduct()->getCategoryIds();
$_ccat = Mage::getModel(‘catalog/category’)->load($_ccats[0]);
$_ccatname = Mage::getModel(‘catalog/category’)->getName($_ccats);
}; //missing “;” causes 503 error for validation service

$ppos         = $_ccat->getProductsPosition();
$current_pid  = $this->helper(‘catalog/data’)->getProduct()->getId();
// build array from products positions
$plist = array();
foreach ($ppos as $pid => $pos) {
$plist[] = $pid;
}
$total=sizeof($plist);
$curpos   = array_search($current_pid, $plist);
// get link for prev product
$previd   = isset($plist[$curpos+1])? $plist[$curpos+1] : $current_pid;
$product  = Mage::getModel(‘catalog/product’)->load($previd);
$prevpos  = $curpos;
while (!$product->isVisibleInCatalog()) {
$prevpos += 1;
$nextid   = isset($plist[$prevpos])? $plist[$prevpos] : $current_pid;
$product  = Mage::getModel(‘catalog/product’)->load($nextid);
}
$prev_url = $product->getProductUrl();
// get link for next product
$nextid   = isset($plist[$curpos-1])? $plist[$curpos-1] : $current_pid;
$product  = Mage::getModel(‘catalog/product’)->load($nextid);
$nextpos  = $curpos;
while (!$product->isVisibleInCatalog()) {
$nextpos -= 1;
$nextid   = isset($plist[$nextpos])? $plist[$nextpos] : $current_pid;
$product  = Mage::getModel(‘catalog/product’)->load($nextid);
}
$next_url = $product->getProductUrl();
// get link for current category
$more_url = $_ccat->getUrl();
?>

<?php
$url = ‘http://&#8217; . $_SERVER[‘HTTP_HOST’] . $_SERVER[‘REQUEST_URI’];
?>
<p><?php if( $url <> $next_url ) { echo ‘<a href=”‘ . $next_url . ‘”>’ . $this->__(‘Previous’) . ‘</a>’; } ?><?php echo “Product “;  ?><?php echo $curpos +1;  ?><?php echo ” of “;  ?><?php echo ” $total “;  ?><?php echo ” of   Categary “;  ?><?php echo ”     $_ccatname “;  ?><?php if( $url <> $prev_url ) { echo ‘<a href=”‘ . $prev_url . ‘”>’ . $this->__(‘Next’) . ‘</a>’; } ?></p>
</div><!– end pagination nav –>

Posted in Magento. 1 Comment »

PHP: Get name of the class of an object

Hello friends,

While working with PHP class and object hierarchy, sometimes it is difficult to know and get class name of a particular object.

To make it easy and to get class name information of an object, we can use “get_class()” function of PHP.

Where, get_class() has an object as an argument, and it returns the class name of the given object.

For Example:

class ExampleClass
{
}
$object1 = new ExampleClass();
echo get_class($object1);

And it will print the class name of the $object1.

Hope this will help you.

Apply or edit a custom layer style

Step:1 Select a single layer from the Layers panel.

Step:2 Do one of the following:

-:Double-click the layer, outside the layer name or thumbnail.

-:Click the Add a Layer Style icon   at the bottom of the Layers panel and choose an effect from the list.

-:Choose an effect from the Layer > Layer Style submenu.

-:To edit an existing style, double-click an effect displayed below the layer name in the Layers panel. (Click the triangle next to the Add a Layer Style icon   to display the effects contained in the style.)

Step:3 Set effect options in the Layer Style dialog box.

Step:4 Add other effects to the style, if needed. In the Layer Style dialog box, click the check box to the      left of the effect name to add the effect without selecting it.