Pages

Sunday, June 30, 2013

Magento Advanced Collection Filters

I always seem to end up in a position where I need more specific information from a collection than addFilter() can give me. Functions like addAttributeToFilter() are great if you’re working with EAV-based collections like products and categories, but they don’t work with a lot of core Magento collections. In this post I’ll go into some detail on how to use the ->getSelect() function to filter collection results. This post comes with a warning: The methods detailed below are intended primarily for data output, not data manipulation. Be careful saving models returned from your original collection.

Calling $collection->getSelect() on your collection will return a model of class type Varien_Db_Select. This model represents the SQL query that is performed to select your collection. I’ve created a module called Mby_Testmodule, and within it I have a model of type testmodule/comment. Let’s get the Select element and play with it a bit.

<?php
        $collection = Mage::getModel('testmodule/comment')->getCollection();
        $select = $collection->getSelect();
        echo $select->__toString();

This will echo the following:

SELECT `main_table`.* FROM `mby_testmodule_comment` AS `main_table`

Essentially we’re returning all data. If I want to filter that result I can use a number of functions. Lets search for all comments by people whose name starts with “abcefg”:

<?php
    $name = "abcefg%";
    $select->where("author_name LIKE ?", $name);
    echo $select->__toString();
?>

Outputs:
SELECT `main_table`.* FROM `mby_testmodule_comment` AS `main_table` WHERE (author_name LIKE 'abcefg%')

If we want to reverse the order of the collection:

<?php
    $select->order("comment_id DESC");
    echo $select->__toString();
?>

Outputs:
SELECT `main_table`.* FROM `mby_testmodule_comment` AS `main_table` WHERE (author_name LIKE 'abcefg%') ORDER BY `comment_id` DESC

If we want to then limit the results to the first 20 comments, we can use:

<?php
    $select->limit(20);
    echo $select->__toString();
?>

Outputs:
SELECT `main_table`.* FROM `mby_testmodule_comment` AS `main_table` WHERE (author_name LIKE 'abcefg%') ORDER BY `comment_id` DESC LIMIT 20

Or if we wanted to limit the results to 20 comments, starting from comment 10:

<?php
    $select->limit(20, 10);
    echo $select->__toString();
?>

Outputs:
SELECT `main_table`.* FROM `mby_testmodule_comment` AS `main_table` WHERE (author_name LIKE 'abcefg%') ORDER BY `comment_id` DESC LIMIT 20 OFFSET 10

Say we also wanted to join these comments to the blog posts that they were made against, we could use an inner join like so:

<?php
    $select->joinInner(
        array(
            'blogpost_table' => 'mby_testmodule_blogpost'
        ),
        'blogpost_table.blogpost_id = main_table.blogpost_id'
    );
    echo $select->__toString();
?>

Outputs:
SELECT `main_table`.*, `blogpost_table`.* FROM `mby_testmodule_comment` AS `main_table` INNER JOIN `mby_testmodule_blogpost` AS `blogpost_table` ON blogpost_table.blogpost_id = main_table.blogpost_id WHERE (author_name LIKE 'abcefg%') ORDER BY `comment_id` DESC LIMIT 20 OFFSET 10

You get the idea.

Modifying the Select model will filter the data returned by your collection when you iterate through it. Implementing the process above will look something like the following:

<?php
        $name = "abcefg%";
        $collection = Mage::getModel('testmodule/comment')->getCollection();
        $collection->getSelect()
            ->where("author_name LIKE ?", $name)
            ->order("comment_id DESC")
            ->limit(20, 10)
            ->joinInner(
                array(
                    'blogpost_table' => 'mby_testmodule_blogpost'
                ),
                'blogpost_table.blogpost_id = main_table.blogpost_id'
            );
        foreach ($collection as $comment) {
            echo "Comment #".$comment->getCommentId();
            echo " by ".$comment->getAuthorName();
            echo " in response to ".$comment->getBlogpostTitle();
            echo "<br />";
            echo $comment->getContent();
        }

How to add Javascript to a Magento Admin page (AKA: How to Override Magento Blocks)

Recently I had to add some additional Javascript validation to a core part of the Magento Admin, and I thought I’d share the best way to do this without having to modify core files.

Because I often have to modify small parts of default Magento functionality, I have created a module that exists for the sole purpose of overriding models and blocks. In this post I’ll go through the steps required to override blocks properly, without modifying core code. The process for models is almost identical. I’m going to use as an example the block that I was required to override: Mage_Adminhtml_Block_Promo_Quote_Edit. All I want to do is add some additional Javascript to the page that hijacks the “Save” event and asks the user if they are sure.

First things first: build a custom module (or pick an existing one) to work from.

in {namespace}/{modulename}/etc/config.xml, add the following:

<config>
   ...
   <global>
      ...
      <blocks>
         <adminhtml>
            <rewrite>
               <promo_quote_edit>{namespace}_{modulename}_Block_Adminhtml_Promo_Quote_Edit</promo_quote_edit>
            </rewrite>
         </adminhtml>
      </blocks>
      ...
   </global>
   ...
</config>

What we’ve just done is tell Magento that when it looks for the block identified as “adminhtml/promo_quote_edit“, load this block class: {namespace}_{modulename}_Block_Adminhtml_Promo_Quote_Edit

We are therefore required to define this class. We do so in path that the class suggests. In this case, it’s: app/code/local/{namespace}/{modulename}/Block/Adminhtml/Promo/Quote/Edit.php. Create this file, and write the following:

<?php
    class {namespace}_{modulename}_Block_Adminhtml_Promo_Quote_Edit
        extends Mage_Adminhtml_Block_Promo_Quote_Edit
    {

By using “extends” and giving the class name of the original block, our new class inherits all of the functions and variables of it’s parent class. If we left the file like this, Magento would act no differently from a user’s perspective.

To give that block new functionality, add as many new functions as you like. But to override a function, as I am doing here, redefine that function within your new class. One very important thing to remember, however, is to ensure that any overridden functions perform the same tasks as the parent, or you risk interfering unintentionally with Magento’s core functionality.

I want to add more Javascript, and I happen to know that Javascript is added into the $_formScripts variable that belongs to this block. I also know that Javascript tends to be added on __construct(). To ensure the class acts the same way as it always did, I define the __construct function like this:

<?php
    public function __construct()
    {
        parent::__construct();
       
        $this->_formScripts[] = "
            editForm.secondarySubmit = editForm.submit;
            editForm.submit = function(url) {
                if (document.getElementById('rule_coupon_type').value == 1) {
                    var answer = confirm('WARNING: This price rule has no Coupon Code.
                    Are you sure you want to do this?');
                } else {
                    var answer = true;
                }
                if (answer) {
                    editForm.secondarySubmit(url);
                } else {
                    return false;
                }
            }
        ";
    }
?>

Note the parent::__construct(); call, that will run the __construct() function of Mage_Adminhtml_Block_Promo_Quote_Edit

In this case, the Javascript I added uses the prototype library to redefine what happens when the form is saved.

Pretty simple really!

Programmatically create Shopping Cart Price Rules with Conditions and Actions

Rather than going into detail of creating the Shopping Cart Price Rule from scratch, this post is specifically about conditions and actions.



If you have ever needed to programmatically create Magento Shopping Cart Price Rules, then you may have wondered how you attach conditions and actions.

Prior to saving your Mage_Salesrule_Model_Rule object, you will need to assign the following data:

<?php
    $rule->setData('actions',$actions);       
    $rule->setData('conditions',$conditions);
?>

Where $actions and $conditions are Array’s of a very specific format.

We then call Mage_Salesrule_Model_Rule::loadPost():

<?php
    $rule->loadPost($rule->getData());
?>

The format that is required for conditions and actions is significantly outside Magento’s EAV model, and is not documented as far as I can see. So to find it out we are required to trace it a little further.

Conditions and actions are processed within the Mage_Salesrule_Model_Rule::loadPost() function, and are converted to a recursive format that you find serialized in the database as conditions_serialized and actions_serialized table columns. This is done via Mage_Rule_Model_Rule::_convertFlatToRecursive() which is called within Mage_Salesrule_Model_Rule::loadPost().

But I digress, a little. What this means for us is that we need to put our data in a specific format prior to saving. I’ve established that format for you below. If you hijack Mage_Salesrule_Model_Rule::loadPost() and print_r() the content of a rule as it’s being saved, you’ll see the format:


    [conditions] => Array
        (
            [1] => Array
                (
                    [type] => salesrule/rule_condition_combine
                    [aggregator] => all
                    [value] => 1
                    [new_child] =>
                )
            [1--1] => Array
                (
                    [type] => salesrule/rule_condition_product_found
                    [value] => 1
                    [aggregator] => all
                    [new_child] =>
                )
            [1--1--1] => Array
                (
                    [type] => salesrule/rule_condition_product
                    [attribute] => sku
                    [operator] => ==
                    [value] => SKU123
                )
        )

    [actions] => Array
        (
            [1] => Array
                (
                    [type] => salesrule/rule_condition_product_combine
                    [aggregator] => all
                    [value] => 1
                    [new_child] =>
                )
            [1--1] => Array
                (
                    [type] => salesrule/rule_condition_product
                    [attribute] => sku
                    [operator] => ==
                    [value] => SKU123
                )
        )

In Layman’s terms, this is saying:


    [conditions][1]        
        "If ALL(aggregator) of these conditions are TRUE(value)"
    [conditions][1--1]     
        "If an item is FOUND(type, value) with ALL(aggregator) of these conditions true"
    [conditions][1--1--1]  
        "SKU(attribute) is(operator) SKU123(value)"
   
    [actions][1]           
        "if ALL(aggregator) of these conditions are TRUE(value)"
    [actions][1--1]        
        "SKU(attribute) is(operator) SKU123(value)"

So what are we really looking at? We’re looking at an array of arrays that uses the array keys to establish the heirarchy. The array keys are exploded by “--” in Mage_Rule_Model_Rule::_convertFlatToRecursive() and are converted to recursive arrays before being stored in the database.

This is how we can write it:

<?php
    $rule = Mage::getModel('salesrule/rule')->load($my_rule_id);
    $conditions = array(
        "1"         => array(
                "type"          => "salesrule/rule_condition_combine",
                "aggregator"    => "all",
                "value"         => "1",
                "new_child"     => null
            ),
        "1--1"      => array(
                "type"          => "salesrule/rule_condition_product_found",
                "aggregator"    => "all",
                "value"         => "1",
                "new_child"     => null
            ),
        "1--1--1"   => array(
                "type"          => "salesrule/rule_condition_product",
                "attribute"     => "sku",
                "operator"      => "==",
                "value"         => "SKU123"
            )
    );
    $actions = array(
        "1"         => array(
                "type"          => "salesrule/rule_condition_product",
                "aggregator"    => "all",
                "value"         => "1",
                "new_child"     => false
            ),
        "1--1"      => array(
                "type"          => "salesrule/rule_condition_product",
                "attribute"     => "sku",
                "operator"      => "==",
                "value"         => "SKU123"
            )
    );
    $rule->setData("conditions",$conditions);
    $rule->setData("actions",$actions);
    $rule->loadPost($rule->getData());
    $rule->save();
?>

How to get a grouped product’s associated products in Magento

This is a question that seems to be asked quite often by new Magento developers.

There is no simple Mage_Catalog_Model_Product::getAssociatedProducts() method, or similar to return all simple products assigned to a grouped product. I outline here how Magento gains access to the collection that we need.

In

/magento/app/design/frontend/base/default/template/catalog/product/view/type/grouped.phtml

you’ll see that they use this:

<?php
    $_associatedProducts = $this->getAssociatedProducts();

Since that .phtml file is of type Mage_Catalog_Block_Product_View_Type_Grouped, we can go to

/magento/app/code/core/Mage/Catalog/Block/Product/View/Type/Grouped.php

and see in Mage_Catalog_Block_Product_View_Type_Grouped::getAssociatedProducts() that they have done this:

<?php
    $this->getProduct()->getTypeInstance(true)->getAssociatedProducts($this->getProduct());

So we can safely assume that $this->getProduct() returns a product object, and replace it with your $product variable like so:

<?php
    $associatedProducts = $product->getTypeInstance(true)->getAssociatedProducts($product);

So a total solution would look something like this:

<?php
    $products = Mage::getModel('catalog/product')
        ->getCollection()
        ->addAttributeToFilter('type_id', array('eq' => 'grouped'));
    foreach ($products as $product) {
        $associatedProducts = $product->getTypeInstance(true)->getAssociatedProducts($product);
        // Do something with the $associatedProducts collection
    }

Adding Surcharges in Magento

Recently I needed to add a surcharge to orders using a particular payment type. Surcharges are what is called a “Total”. They need to be created in the same way as Delivery, Discounts, etc. This post assumes knowledge of module creation.

Please note that this post is incomplete! I’m pressed for time and I’ll be back to edit this with more detailed information on WHY we do it.

So first off, create a new Module for Surcharges in magento/app/code/local/<namespace>/Surcharges/ with the usual subfolders. Don’t forget to create the module’s xml file in /app/etc/modules/.

in <namespace>/Surcharges/etc/config.xml:

<?php
    <config>
        ...
        <global>
            ...
            <sales>
                <quote>
                    <totals>
                        <surcharge>
                            <class>surcharges/quote_address_total_surcharge</class>
                            <after>tax</after>
                        </surcharge>
                    </totals>
                </quote>
            </sales>
            <fieldsets>
                <sales_convert_quote>
                    <surcharge><to_order>*</to_order></surcharge>
                    <surcharge_tax><to_order>*</to_order></surcharge_tax>
                </sales_convert_quote>
            </fieldsets>
            ...
        </global>
        ...
    </config>
?>

in <namespace>/Surcharges/sql/surcharges_setup/mysql4-install-0.1.0.php

<?php

    $installer = $this;

    $installer->startSetup();

    $installer->addAttribute(
        'order',
        'surcharge',
        array(
            'type' => 'float',
            'grid' => false
        )
    );
    $installer->addAttribute(
        'order',
        'surcharge_tax',
        array(
            'type' => 'float',
            'grid' => false
        )
    );

    $installer->addAttribute(
        'quote',
        'surcharge',
        array(
            'type' => 'float',
            'grid' => false
        )
    );
    $installer->addAttribute(
        'quote',
        'surcharge_tax',
        array(
            'type' => 'float',
            'grid' => false
        )
    );

    $installer->endSetup();

in <namespace>/Surcharges/Model/Quote/Address/Total/Surcharge.php:

<?php

class {{namespace}}_Surcharges_Model_Quote_Address_Total_Surcharge
    extends Mage_Sales_Model_Quote_Address_Total_Abstract
{
   
    public function __construct()
    {
        $this->setCode('surcharge');
    }

    public function collect(Mage_Sales_Model_Quote_Address $address)
    {       
        $amount = $address->getShippingAmount();
        if ($amount != 0 || $address->getShippingDescription()) {
                       
            $address->setSurchargeAmount($this->getSurchargeAmount());
            $address->setSurchargeTaxAmount($this->getSurchargeTaxAmount());
           
            $address->setSurcharge($this->getSurchargeAmount());
            $address->getQuote()->setData('surcharge', $this->getSurchargeAmount());
            $address->getQuote()->setData('surcharge_tax', $this->getSurchargeTaxAmount());
           
            $address->setTaxAmount($address->getTaxAmount() + $address->getSurchargeTaxAmount());
            $address->setBaseTaxAmount(
                $address->getBaseTaxAmount() + $address->getSurchargeTaxAmount()
            );
            $address->setSubtotal($address->getSubtotal() + $this->getSurchargeAmount(true));
            $address->setBaseSubtotal(
                $address->getBaseSubtotal() + $this->getSurchargeAmount(true)
            );
            $address->setGrandTotal($address->getGrandTotal() + $address->getSurchargeAmount());
            $address->setBaseGrandTotal(
                $address->getBaseGrandTotal() + $address->getSurchargeAmount()
            );
           
        }
        return $this;
    }
   
    public function fetch(Mage_Sales_Model_Quote_Address $address)
    {
        $amount = $address->getShippingAmount();
        if ($amount != 0 || $address->getShippingDescription()) {
            if ($address->getSurchargeAmount()) {
                $address->addTotal(array(
                    'code'  => $this->getCode(),
                    'title' => $this->getSurchargeTitle(),
                    'value' => $address->getSurchargeAmount()
                ));
            }
        }
        return $this;
    }
   
    public function getSurchargeTitle()
    {
        $title = "Surcharges";
        return $title;
    }
   
    public function getSurchargeAmount()
    {
        $amount = (float)10;
        return $amount;
    }
   
    public function getSurchargeTaxAmount()
    {
        $taxpercent = (float)10;
        $tax = ($this->getSurchargeAmount()/100)*$taxpercent;
        return $tax;
    }
   
}

Upgrading Magento Enterprise

Unfortunately there is no magic button you can push to upgrade your version of Enterprise.

If you have enterprise, you’ll be paying for support. I recommend you contact Magento Support before going any further. There’s no documentation on how to do it yourself. Also, if you’re not a System Admin or a Developer, turn back now.

It shouldn’t need to be said, but here I go anyway: Do this on a development server or at least a staging environment first. Do not just upgrade your live site without doing it elsewhere first. Also, for the record this post will be vague. There is a lot of assumed knowledge within. I use examples from an Apache server as I imagine many people will be using Apache. I know I do.

Log in to your enterprise account on www.magentocommerce.com and click on “My Account”. Click “Downloads”, and the latest versions of Magento Enterprise will be listed on the right, among other things such as changelog files. Download your desired version.

Essentially there are only a few key steps to the process:

1) Back up your database.

2) Turn off Cron! You don’t want things re-indexing while Magento modifies database tables.

3) Back up all files from your Magento working directory, and move the files to a different folder (eg: rsync -aPzx var/www/magento var/www/magento_backup).

4) Extract the files from the downloaded version to var/www/magento

5) Make a list of all custom content that needs to be installed on the new version. My list of things generally includes:

    everything in app/code/local,
    files in app/etc/modules,
    app/etc/local.xml
    custom themes & skins in app/design/frontend/enterprise and app/design/adminhtml/default/default, and
    a lot of things in the media, js & skin folders.

If you’ve been a good little developer and haven’t edited any core files, you’ll be patting yourself on the back at this very moment. If not, you’re out of luck, really. Go back and do things properly. Don’t copy across any core files you’ve edited as you’re likely to break lots of things or undo new bug fixes.

6) Copy the things in your list from var/www/magento_backup to var/www/magento

7) Load the site in a browser window. This could take a while. There are a number of things that can go wrong at this point. For example:

    You may get some fatal errors. If this is the case, you’ll need to track them back to their source and find out why they are being thrown. Did you forget to migrate some files? Are you overriding core classes that have now changed? Are you using functionality that has been deprecated? Have you reached this step previously and now cached data is breaking your shit? Get in there and have a look.
    Your mysql server may get stuck in an infinite loop. With the new version will come a lot of new setup files that modify the database. They could be adding new tables, new columns, new keys or simply modifying elements. For instance, if Magento tries to add UNIQUE to an existing field that contains duplicate values, it will fail and repeatedly retry.

8) Once the site loads, and loads with no fatal errors, TEST! Test all of your modules, place test orders, just go nuts! This is by far the most important step and cannot be taken seriously enough.

Finally, when you’re happy with the level that you’re at:

9) Do it all again for your live site, or if this is a staging server, make it live for all to see.

Magento :: get URL paths for skin, media, Js OR base URL

If anyone of you facing problems to fetch the Magento URL paths of  skin, media, Js or simple base URL of Magento while customization/programming, then following lines should be helpful for you:

Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_JS);
//http://magento.demo/js/

Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_LINK);
//http://magento.demo/index.php/

Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA);
//http://magento.demo/media/

Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_SKIN);
//http://magento.demo/skin/

Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB);
//http://magento.demo/

Friday, June 28, 2013

Add Javascript/CSS to page Head from within a Magento Block

This is a pretty easy one, but it’s something that can come in very handy at times.

Say you want to load a particular script on the page, but only if a particular block loads on that page. As it stands, Magento’s core/template blocks don’t support this.

To do it, include this function from within your custom module’s Block file in app/code/local/Namespace/Modulename/Block

public function addItem($type, $path)
{
    $head = $this->getLayout()->getBlock('head');
    return $type == 'css' ? $head->addCss($path) : $type == 'javascript' ? $head->addJs($path) : $this ;
}

Then to use it, just include a call to this function from within your block declaration in the layout:

<block type="modulename/blockname" name="modulename.blockname" as="blockname" template="path/to/template/file.phtml">
    <action method="addItem"><type>css</type><path>css/path/to/file.css</path></action>
    <action method="addItem"><type>javascript</type><path>path/to/file.js</path></action>
</block>

When that block is constructed, it will run the function and your custom scripts will load in the head.

Automatically refresh Magento cache

In Magento, whenever you make changes to products, static blocks, etc, it recognizes that the data in the database is no longer the same as what it has in the cache. Unfortunately, Magento doesn’t realize what cache data is different, just that something is different.

Traditionally, you will need to go into System > Cache Management and refresh the invalidated cache types, but I’ve overcome this by using a cron job that runs every time cron runs on the server, and calls a function to refresh the cache automatically.


Whenever you make changes, magento fires events. There are listeners to these events that invalidate the relevant cache. As for why it does this (and why it doesn’t automatically refresh) this is ultimately a design decision, but probably has something to do with being able to stage content. For example, you could make changes to several products that all relate to one another, and can then refresh the cache.

Before using this functionality, you’ll need to ensure that cron is set up and configured correctly on your server. I’m not the right person to ask regarding this, but I’m sure google has some tutorials relevant to your server configuration.

Create a module (or use an existing module) that you can use to set up a cron job for refreshing the cache.

Create a file: {{namespace}}/{{modulename}}/Model/Observer.php

Inside that file:

  <?php

  class <namespace>_<modulename>_Model_Observer {

    public function refreshCache() {
      try {
        $allTypes = Mage::app()->useCache();
        foreach($allTypes as $type => $blah) {
          Mage::app()->getCacheInstance()->cleanType($type);
        }
      } catch (Exception $e) {
        // do something
        error_log($e->getMessage());
      }
    }

  }

In your module’s etc/config.xml:

  <config>
    ...
    <crontab>
      <jobs>
        <{{modulename}}_refresh_cache>
          <schedule><cron_expr>* * * * *</cron_expr></schedule>
          <run><model>{{modulename}}/observer::refreshCache</model></run>
        </{{modulename}}_refresh_cache>
      </jobs>
    </crontab>
    ...
  </config>

Now as long as cron is configured correctly on your server, the cache will update automatically as often as cron runs.

Tuesday, June 25, 2013

Magento (How to fix): One or more of the Cache Types are invalidated: Blocks HTML output.


Somewhere around Magento 1.5, message from the title of this post begun to pop on every product save.
Although quite anoying, it is quite easy to fix and it seems that’s not a BUG, it is a feature – implemented without automatic block html cache refresh :)
I have tested it on Professional Edition and to be completely honest, I’m not sure if it will actually work on Magento CE,
but there is no reason why not (Please comment if it does).
Ok, what is the catch?!
Here we go:
Add this in your module config.xml:

<global>

<models>

<catalogrule>

    <rewrite>

        <rule>Yourpackage_Yourmodule_Model_Rule</rule>

    </rewrite>

</catalogrule>

</models>

</global>

Create file called Rule.php in YOUR module Model directory.

Add this code in newly created file:

class Yourpackage_Yourmodule_Model_Rule extends Mage_CatalogRule_Model_Rule

{

   /**

     * Apply all price rules to product

     *

     * @param int|Mage_Catalog_Model_Product $product

     * @return Mage_CatalogRule_Model_Rule

     */

    public function applyAllRulesToProduct($product)

    {

        $this->_getResource()->applyAllRulesForDateRange(NULL, NULL, $product);

        $this->_invalidateCache();

        //Notice this little line

    Mage::app()->getCacheInstance()->cleanType('block_html');

        $indexProcess = Mage::getSingleton('index/indexer')->getProcessByCode('catalog_product_price');

        if ($indexProcess) {

            $indexProcess->reindexAll();

        }

    }

}

Well…. that’s it :)

I hope it works for you as it works for me.

How to show product reviews on product page in Magento

Add the below code in the catalog.xml in the product view section

 <block type="review/product_view_list" name="product.info.product_additional_data" as="reviews" template="review/product/view/list.phtml"> 
 <block type="review/form" name="product.review.form" as="review_form"/></block>

And then include the below line in the view.phtml file

<? getChildHtml('reviews') ?>

unable to complete this request attribute set magento

simply delete the files and folder from the var/cache folder and var/sessions folder and then try.It will work.

Magento pages in a drop down (html select box).

below is the code to show magento pages in a drop down box

<select name=”page”>
<?php foreach (Mage::getResourceModel(‘cms/page_collection’) as $page){ ?>
<option value=”<?php echo $page->getId() ?>”><?php echo $page->getTitle() ?></option>
<?php } ?>
</select>

Get cms static block in magento

Here is the code to get the cms block in magento front end.
$this->getLayout()->createBlock(‘cms/block’)->setBlockId(‘blockidentifier’)->toHtml()
In the editor you can simply call to
{{block id=’block_id’}}
Similar reference
{{store direct_url=’mypage.html’}}
{{skin url=’images/media/about_us_img.jpg’}}

Add Category Filter on Product Collection In Magento

Here is the code to add category filter on the product collection
$productcollection = Mage::getModel(‘catalog/product’)->getCollection();
$productcollection = $productcollection->addCategoryFilter(Mage::getModel(‘catalog/category’)->load($currcategory),true);
$productcollection = $productcollection->addAttributeToFilter(‘special_price’, array(‘gt’ => 0));
echo $productcollection->getSize();

Current page variable in magento

Get title
<?=Mage::getSingleton(‘cms/page’)->getTitle()?>

Get Identifier
<? echo Mage::getBlockSingleton(‘cms/page’)->getPage()->getIdentifier()?>

Get Page ID
<? echo Mage::getBlockSingleton(‘cms/page’)->getPage()->getId()?>

Fetch configurable product attributes values

Getting all options of a specific magento configurable product attribute is fairly easy:



getAttribute('catalog_product', 'color');
foreach ($attribute->getSource()->getAllOptions(true) as $option) {
echo $option['value'] . ' ' . $option['label'] . "\n";
}
?>




get options and their values which are applicable to a particular configurable product



getTypeInstance(true)->getConfigurableAttributesAsArray($product);
$attributeOptions = array();
foreach ($productAttributeOptions as $productAttribute) {
foreach ($productAttribute['values'] as $attribute) {
$attributeOptions[$productAttribute['label']][$attribute['value_index']] = $attribute['store_label'];
}
}
?>

Magento : Product count in a category.

Below are the 2 different way to display the product count in the category in magento.
<?php
$catObj = Mage::getModel(‘catalog/category’)->load($_category->getID());
$prodObj = $catObj->getProductCollection()->getData();
echo count($prodObj);
———————-OR————————–
$prodCollection = Mage::getResourceModel(‘catalog/product_collection’)->addCategoryFilter($_category);
echo $prodCollection->count();
?>

Delete Orders From Magento and Reset The Order Id

1. Take the backup of your current database
2. Run the below queries
3. I have not fully tested that what will be the effect of these queries on the database, but as much i tested it does not have any negative effect on the Magento Database
4. If you find any wrong effect then your comment are welcome
These are the queries to delete the orders on the magento and reset the Id
—————————————————————-
SET FOREIGN_KEY_CHECKS=0;

TRUNCATE `sales_flat_order`;
TRUNCATE `sales_flat_order_address`;
TRUNCATE `sales_flat_order_grid`;
TRUNCATE `sales_flat_order_item`;
TRUNCATE `sales_flat_order_payment`;
TRUNCATE `sales_flat_order_status_history`;

TRUNCATE `sales_flat_creditmemo`;
TRUNCATE `sales_flat_creditmemo_comment`;
TRUNCATE `sales_flat_creditmemo_grid`;
TRUNCATE `sales_flat_creditmemo_item`;

TRUNCATE `sales_flat_invoice`;
TRUNCATE `sales_flat_invoice`;
TRUNCATE `sales_flat_invoice_grid`;
TRUNCATE `sales_flat_invoice_item`;

TRUNCATE `sales_flat_quote`;
TRUNCATE `sales_flat_quote_address`;
TRUNCATE `sales_flat_quote_address_item`;
TRUNCATE `sales_flat_quote_item`;
TRUNCATE `sales_flat_quote_item_option`;
TRUNCATE `sales_flat_order_item`;

TRUNCATE `sales_flat_shipment`;
TRUNCATE `sales_flat_shipment_comment`;
TRUNCATE `sales_flat_shipment_grid`;
TRUNCATE `sales_flat_shipment_item`;
TRUNCATE `sales_flat_shipment_item`;
TRUNCATE `sales_flat_shipment_track`;

TRUNCATE `sendfriend_log`;
TRUNCATE `tag`;
TRUNCATE `tag_relation`;
TRUNCATE `tag_summary`;
TRUNCATE `wishlist`;
TRUNCATE `log_quote`;
TRUNCATE `report_event`;

ALTER TABLE `sales_flat_order` AUTO_INCREMENT=0;
ALTER TABLE `sales_flat_order_address` AUTO_INCREMENT=0;
ALTER TABLE `sales_flat_order_grid` AUTO_INCREMENT=0;
ALTER TABLE `sales_flat_order_item` AUTO_INCREMENT=0;
ALTER TABLE `sales_flat_order_payment` AUTO_INCREMENT=0;
ALTER TABLE `sales_flat_order_status_history` AUTO_INCREMENT=0;

ALTER TABLE `sales_flat_creditmemo` AUTO_INCREMENT=0;
ALTER TABLE `sales_flat_creditmemo_comment` AUTO_INCREMENT=0;
ALTER TABLE `sales_flat_creditmemo_grid` AUTO_INCREMENT=0;
ALTER TABLE `sales_flat_creditmemo_item` AUTO_INCREMENT=0;

ALTER TABLE `sales_flat_invoice` AUTO_INCREMENT=0;
ALTER TABLE `sales_flat_invoice` AUTO_INCREMENT=0;
ALTER TABLE `sales_flat_invoice_grid` AUTO_INCREMENT=0;
ALTER TABLE `sales_flat_invoice_item` AUTO_INCREMENT=0;

ALTER TABLE `sales_flat_quote` AUTO_INCREMENT=0;
ALTER TABLE `sales_flat_quote_address` AUTO_INCREMENT=0;
ALTER TABLE `sales_flat_quote_address_item` AUTO_INCREMENT=0;
ALTER TABLE `sales_flat_quote_item` AUTO_INCREMENT=0;
ALTER TABLE `sales_flat_quote_item_option` AUTO_INCREMENT=0;
ALTER TABLE `sales_flat_order_item` AUTO_INCREMENT=0;

ALTER TABLE `sales_flat_shipment` AUTO_INCREMENT=0;
ALTER TABLE `sales_flat_shipment_comment` AUTO_INCREMENT=0;
ALTER TABLE `sales_flat_shipment_grid` AUTO_INCREMENT=0;
ALTER TABLE `sales_flat_shipment_item` AUTO_INCREMENT=0;
ALTER TABLE `sales_flat_shipment_item` AUTO_INCREMENT=0;
ALTER TABLE `sales_flat_shipment_track` AUTO_INCREMENT=0;

ALTER TABLE `sendfriend_log` AUTO_INCREMENT=0;
ALTER TABLE `tag` AUTO_INCREMENT=0;
ALTER TABLE `tag_relation` AUTO_INCREMENT=0;
ALTER TABLE `tag_summary` AUTO_INCREMENT=0;
ALTER TABLE `wishlist` AUTO_INCREMENT=0;
ALTER TABLE `log_quote` AUTO_INCREMENT=0;
ALTER TABLE `report_event` AUTO_INCREMENT=0;

TRUNCATE `eav_entity_store`;
ALTER TABLE `eav_entity_store` AUTO_INCREMENT=0;

SET FOREIGN_KEY_CHECKS=1;

----------------------------------------------------------

Fetch Subcategory of a category in magento in select box dropdown

<select name="" style="width:220px;" onchange="location.href=this.value">
  <?php $children  = Mage::getModel('catalog/category')->getCategories(YOUR_CAT_ID); ?>

 <?php foreach ($children as $category) {  $i++;
 $cat = Mage::getModel('catalog/category')->load($category->getID()); ?>
  <option value="<?php echo $cat->geturl(); ?>"  <? if(Mage::registry('current_category')->getId()==$category->getID()) echo 'selected';?>><?php echo $category->getName(); ?></option>
 <?php } ?>

 </select>

Fetch configurable attribute from CRE Loaded database to Magento database

Here is the code to fetch the attribute (that should be configurable in magento database) from the CRE Loaded database to magento database
///////////////////////////////CODE/////////////////////////////////
require_once ‘/app/Mage.php’;
umask(0);
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
/////////////////////Create Configurable Attribute From CRE Loaded Database///////////////////////
function createAttribute($code, $label, $attribute_type, $product_type)
{
$_attribute_data = array(
‘attribute_code’ => $code,
‘is_global’ => ’1′,
‘frontend_input’ => $attribute_type, //’boolean’,
‘default_value_text’ => ”,
‘default_value_yesno’ => ’0′,
‘default_value_date’ => ”,
‘default_value_textarea’ => ”,
‘is_unique’ => ’0′,
‘is_required’ => ’0′,
‘apply_to’ => array($product_type), //array(‘grouped’)
‘is_configurable’ => ’1′,
‘is_searchable’ => ’0′,
‘is_visible_in_advanced_search’ => ’0′,
‘is_comparable’ => ’0′,
‘is_used_for_price_rules’ => ’0′,
‘is_wysiwyg_enabled’ => ’0′,
‘is_html_allowed_on_front’ => ’1′,
‘is_visible_on_front’ => ’0′,
‘used_in_product_listing’ => ’0′,
‘used_for_sort_by’ => ’0′,
‘frontend_label’ => $label
);
$model = Mage::getModel(‘catalog/resource_eav_attribute’);
if (!isset($_attribute_data['is_configurable'])) {
$_attribute_data['is_configurable'] = 0;
}
if (!isset($_attribute_data['is_filterable'])) {
$_attribute_data['is_filterable'] = 0;
}
if (!isset($_attribute_data['is_filterable_in_search'])) {
$_attribute_data['is_filterable_in_search'] = 0;
}
if (is_null($model->getIsUserDefined()) || $model->getIsUserDefined() != 0) {
$_attribute_data['backend_type'] = $model->getBackendTypeByInput($_attribute_data['frontend_input']);
}
$defaultValueField = $model->getDefaultValueByInput($_attribute_data['frontend_input']);
if ($defaultValueField) {
$_attribute_data['default_value'] = $this->getRequest()->getParam($defaultValueField);
}
$model->addData($_attribute_data);
$model->setEntityTypeId(Mage::getModel(‘eav/entity’)->setType(‘catalog_product’)->getTypeId());
$model->setIsUserDefined(1);
try {
$model->save();
} catch (Exception $e) { echo ‘
Sorry, error occured while trying to save the attribute. Error: ‘.$e->getMessage().’
‘; }
}
////////////////your cre loaded database connection/////////////
$conn = mysql_connect(‘localhost’,'root’,”) ;
mysql_select_db(‘shnoop_cre’,$conn);
//////////////////////////////////////////////////////////////
$select_attributes = @mysql_query(“select * from products_options order by products_options_id”);
while($fetch_attribute = @mysql_fetch_object($select_attributes))
{
if($fetch_attribute->options_type==0)
$input_type=’select’;
elseif($fetch_attribute->options_type==1)
$input_type=’text’;
elseif($fetch_attribute->options_type==2)
$input_type=’radio’;
elseif($fetch_attribute->options_type==3)
$input_type=’checkbox’;
elseif($fetch_attribute->options_type==4)
$input_type=’textarea’;
$Attr_label = $fetch_attribute->products_options_name;
$fetch_attribute->products_options_name = str_replace(‘ ‘,”,$fetch_attribute->products_options_name);
$fetch_attribute->products_options_name = str_replace(‘/’,'_’,$fetch_attribute->products_options_name);
$fetch_attribute->products_options_name = strtolower($fetch_attribute->products_options_name);
createAttribute($fetch_attribute->products_options_name,$Attr_label,$input_type, “configurable”);
}
//////////////////////////////////////////////////////////////////////
//////////////////////Fetch Configurable Attribute Options From CRE Loaded Database To Magento Database/////////////////////////////////
////////////////your cre loaded database connection/////////////
$conn = mysql_connect(‘localhost’,'root’,”) ;
mysql_select_db(‘shnoop_cre’,$conn);
//////////////////////////////////////////////////////////////
$select_attributes = @mysql_query(“select * from products_options order by products_options_id”);
while($fetch_attribute = @mysql_fetch_object($select_attributes))
{
$fetch_attribute->products_options_name = str_replace(‘ ‘,”,$fetch_attribute->products_options_name);
$fetch_attribute->products_options_name = str_replace(‘/’,'_’,$fetch_attribute->products_options_name);
$fetch_attribute->products_options_name = strtolower($fetch_attribute->products_options_name);
$_newOptions = Array();
$select_attribut_options = @mysql_query(“select * from products_options_values_to_products_options where products_options_id=’$fetch_attribute->products_options_id’”);
while($fetch_attribut_option=@mysql_fetch_object($select_attribut_options))
{
$fetch_attribut_option_value = @mysql_fetch_object(mysql_query(“select * from products_options_values where products_options_values_id=’$fetch_attribut_option->products_options_values_id’”));
if(!in_array($fetch_attribut_option_value->products_options_values_name,$_newOptions))
array_push($_newOptions,$fetch_attribut_option_value->products_options_values_name);
}
//Array of values that will become the list of colours
$_attribute = Mage::getModel(‘eav/entity_attribute’)->loadByCode(‘catalog_product’, $fetch_attribute->products_options_name); //change ‘primarycolour’ to any attribute
$_oldOptionArr = array(‘value’=>array(), ‘order’=>array(), ‘delete’=>array());
foreach ( $_attribute->getSource()->getAllOptions(true, true) as $option){
$_oldOptionArr['value'][$option['value']] = array($option['label']);
}
$_newOptionArr = array(‘value’=>array(), ‘order’=>array(), ‘delete’=>array());
$i = 0;
foreach ($_newOptions as $_newOption)
{
$i++;
echo $_newOption;
if(!in_array(Array($_newOption), $_oldOptionArr['value']) && $_newOption != ”) //If the option doesn’t exist already in Magento…
{
$_newOptionArr['value']['option_' . $i] = array($_newOption); //Add the option to the new array
}
}
$_attribute->setOption($_newOptionArr);
$_attribute->save();
}
//////////////////////////////////////////////////////////////

Magento: How to change order status programmatically?

Here, I will show you, how you can change your order status programmatically (with PHP coding).
First, you need to load your order.
If you have order id, you can load order in the following way:-
$orderId = YOUR_ORDER_ID;
$order = Mage::getModel(‘sales/order’)
->load($orderId);
If you have order increment id, you can load order in the following way:-
$orderIncrementId = YOUR_ORDER_INCREMENT_ID;
$order = Mage::getModel(‘sales/order’)
->loadByIncrementId($orderIncrementId);
Now, here is the code to change order status:-
/**
* change order status to ‘Completed’
*/
$order->setState(Mage_Sales_Model_Order::STATE_COMPLETE, true)->save();
Similarly, you can change the order status to pending, processing, canceled, closed, holded, etc.
/**
* change order status to ‘Pending’
*/
$order->setState(Mage_Sales_Model_Order::STATE_NEW, true)->save();
/**
* change order status to ‘Pending Paypal’
*/
$order->setState(Mage_Sales_Model_Order::STATE_PENDING_PAYMENT, true)->save();
/**
* change order status to ‘Processing’
*/
$order->setState(Mage_Sales_Model_Order::STATE_PROCESSING, true)->save();
/**
* change order status to ‘Completed’
*/
$order->setState(Mage_Sales_Model_Order::STATE_COMPLETE, true)->save();
/**
* change order status to ‘Closed’
*/
$order->setState(Mage_Sales_Model_Order::STATE_CLOSED, true)->save();
/**
* change order status to ‘Canceled’
*/
$order->setState(Mage_Sales_Model_Order::STATE_CANCELED, true)->save();
/**
* change order status to ‘Holded’
*/
$order->setState(Mage_Sales_Model_Order::STATE_HOLDED, true)->save();
You can also cancel an order in the following way:-
if($order->canCancel()) {
$order->cancel()->save();
}
Hold an order:-
if($order->canHold()) {
$order->hold()->save();
}
Unhold an order:-
if($order->canUnhold()) {
$order->unhold()->save();
}

How to import CRE Loaded Categories to Magento Database

Transferring one opensource database to other is a common headache.Recently i faced this problem when i need to move the CRE Loaded database to Magento Database.
Here i am giving the code by that you can load the CRE Loaded categories to Magento Database.
//define(‘MAGENTO’, realpath(dirname(__FILE__)));
require_once ‘/app/Mage.php’;
umask(0);
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$count = 0;
/////Cre Loaded Data Base Connection////////////
$conn = mysql_connect(‘localhost’,'root’,”) ;
mysql_select_db(‘shnoop_cre’,$conn);
//////////////////////////////////
$select_categories = @mysql_query(“select * from categories where categories_id=1 or parent_id=1 order by parent_id,categories_id”);
while($fetch_category = @mysql_fetch_object($select_categories))
{
/////Cre Loaded Data Base Connection////////////
$conn = mysql_connect(‘localhost’,'root’,”) ;
mysql_select_db(‘shnoop_cre’,$conn);
////////////////////////////////
$fetch_category_description = @mysql_fetch_object(mysql_query(“select * from categories_description where categories_id=”.$fetch_category->categories_id));
$uri_key = createPageName($fetch_category_description->categories_name);
$data['general']['path'] = ”;
$data['general']['name'] = $fetch_category_description->categories_name;
$data['general']['meta_title'] = “”;
$data['general']['meta_description'] = “”;
$data['general']['is_active'] = 1;
$data['general']['url_key'] = $uri_key;
$data['general']['display_mode'] = “PRODUCTS”;
$data['general']['is_anchor'] = 0;
if($fetch_category->parent_id==0)
$data['category']['parent'] = 4;//$line[0]; // 3 top level
else
$data['category']['parent'] = creLoadedCategoryName($fetch_category->parent_id);
$storeId = 0;
createCategory($data,$storeId);
sleep(0.5);
unset($data);
//}
//}
}
function createCategory($data,$storeId) {
echo “Starting {$data['general']['name']} [{$data['category']['parent']}] …”;
$category = Mage::getModel(‘catalog/category’);
$category->setStoreId($storeId);
# Fix must be applied to run script
#http://www.magentocommerce.com/boards/appserv/main.php/viewreply/157328/
if (is_array($data)) {
$category->addData($data['general']);
if (!$category->getId()) {
$parentId = $data['category']['parent'];
if (!$parentId) {
if ($storeId) {
$parentId = Mage::app()->getStore($storeId)->getRootCategoryId();
}
else {
$parentId = Mage_Catalog_Model_Category::TREE_ROOT_ID;
}
}
if(!is_int($parentId))
$parentId = getMagentoCateogryParentId($parentId);
$parentCategory = Mage::getModel(‘catalog/category’)->load($parentId);
$category->setPath($parentCategory->getPath());
}
/**
* Check “Use Default Value” checkboxes values
*/
if ($useDefaults = $data['use_default']) {
foreach ($useDefaults as $attributeCode) {
$category->setData($attributeCode, null);
}
}
$category->setAttributeSetId($category->getDefaultAttributeSetId());
if (isset($data['category_products']) &&
!$category->getProductsReadonly()) {
$products = array();
parse_str($data['category_products'], $products);
$category->setPostedProducts($products);
}
try {
$category->setIsActive(true);
$category->save();
echo “Suceeded
“;
}
catch (Exception $e){
echo “Failed
“;
}
}
}
function createPageName($Title)
{
$Title = str_split(strtolower($Title));
$allowableArr = array(’0′,’1′,’2′,’3′,’4′,’5′,’6′,’7′,’8′,’9′,’a',’b',’c',’d',’e',’f',’g',’h',’i',’j',’k',’l',’m',’n',’o',’p',’q',’r',’s',’t',’u',’v',’w',’x',’y',’z',’-',’ ‘);
$pagename = ”;
for($ii=0;$iicategories_name;
}
function getMagentoCateogryParentId($parname)
{
/////Magento Data Base Connection////////////
$conn2 = mysql_connect(‘localhost’,'root’,”) ;
mysql_select_db(‘mage_maint_151′,$conn2);
//////////////////////////////////
$tableName = Mage::getSingleton(‘core/resource’)->getTableName(‘catalog_category_entity_varchar’);
$fetch_mage_category_details = @mysql_fetch_object(mysql_query(“select * from $tableName where value=’”.addslashes($parname).”‘”));
mysql_close($conn2);
return $fetch_mage_category_details->entity_id;
}
THANKS

List magento categories and subcategories in different way.

Display Top Level Categories Only
<?php $_helper = Mage::helper(‘catalog/category’) ?>
<?php $_categories = $_helper->getStoreCategories() ?>
<?php if (count($_categories) > 0): ?>
<ul>
<?php foreach($_categories as $_category): ?>
<li>
<a href=”<?php echo $_helper->getCategoryUrl($_category) ?>”>
<?php echo $_category->getName() ?>
</a>
</li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
Display Top Level Categories and ALL Subcategories
<?php $_helper = Mage::helper(‘catalog/category’) ?>
<?php $_categories = $_helper->getStoreCategories() ?>
<?php $currentCategory = Mage::registry(‘current_category’) ?>
<?php if (count($_categories) > 0): ?>
<ul>
<?php foreach($_categories as $_category): ?>
<li>
<a href=”<?php echo $_helper->getCategoryUrl($_category) ?>”>
<?php echo $_category->getName() ?>
</a>
<?php $_category = Mage::getModel(‘catalog/category’)->load($_category->getId()) ?>
<?php $_subcategories = $_category->getChildrenCategories() ?>
<?php if (count($_subcategories) > 0): ?>
<ul>
<?php foreach($_subcategories as $_subcategory): ?>
<li>
<a href=”<?php echo $_helper->getCategoryUrl($_subcategory) ?>”>
<?php echo $_subcategory->getName() ?>
</a>
</li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
</li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
Display Top Level Categories and Current Categories SubCategories
<?php $_helper = Mage::helper(‘catalog/category’) ?>
<?php $_categories = $_helper->getStoreCategories() ?>
<?php $currentCategory = Mage::registry(‘current_category’) ?>
<?php if (count($_categories) > 0): ?>
<ul>
<?php foreach($_categories as $_category): ?>
<li>
<a href=”<?php echo $_helper->getCategoryUrl($_category) ?>”>
<?php echo $_category->getName() ?>
</a>
<?php if ($currentCategory &amp;&amp; $currentCategory->getId() == $_category->getId()): ?>
<?php $_category = Mage::getModel(‘catalog/category’)->load($_category->getId()) ?>
<?php $_subcategories = $_category->getChildrenCategories() ?>
<?php if (count($_subcategories) > 0): ?>
<ul>
<?php foreach($_subcategories as $_subcategory): ?>
<li>
<a href=”<?php echo $_helper->getCategoryUrl($_subcategory) ?>”>
<?php echo $_subcategory->getName() ?>
</a>
</li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
<?php endif; ?>
</li>
<?php endforeach; ?>
</ul>
<?php endif; ?>

Get original image url/path in magento

$productId = 'SOME_PRODUCT_ID';
$product = Mage::getModel('catalog/product')->load($productId);
$productMediaConfig = Mage::getModel('catalog/product_media_config');
$baseImageUrl = $productMediaConfig->getMediaUrl($product->getImage());
$smallImageUrl = $productMediaConfig->getMediaUrl($product->getSmallImage());
$thumbnailUrl = $productMediaConfig->getMediaUrl($product->getThumbnail());

Get all attributes from an attribute set in magento.

$entityTypeId = Mage::getModel(‘eav/entity’)
->setType(‘catalog_product’)
->getTypeId();
$attributeSetName = ‘Default’; //Edit with your required Attribute Set Name
$attributeSetId = Mage::getModel(‘eav/entity_attribute_set’)
->getCollection()
->setEntityTypeFilter($entityTypeId)
->addFieldToFilter(‘attribute_set_name’, $attributeSetName)
->getFirstItem()
->getAttributeSetId();
$attributesInfo = Mage::getResourceModel(‘eav/entity_attribute_collection’)
->setEntityTypeFilter($attributeSetId) //4 = product entities
->addSetInfo()
->getData();
foreach($attributesInfo as $attribute):
$attributeObj = Mage::getModel(‘eav/entity_attribute’)->load($attribute['attribute_id']);
echo $attribute['frontend_input'];echo ‘<br/>’;
echo ‘label = ‘.$attributeObj->getFrontendLabel().’<br/>’;
echo ‘code = ‘.$attributeObj->getAttributeCode().’<br/><br/>’;
endforeach;

how to enable error printing in magento?

here is the process to enable the error printing in magento
1. go to magentoRoot/errors folder and make the copy of local.xml.sample
2. then rename the local.xml.sample to local.xml
Now you can see the erros thrown and can easily debug the system

Create custom event in magento.

Use below 2 magneto event to dispatch event in magento
<controller_action_predispatch>
<observers>
<pioc_backoffice_shipping_observer>
<class>PIOC_Backoffice_Model_Shipping_Observer</class>
<method>hookToControllerActionPreDispatch</method>
</pioc_backoffice_shipping_observer>
</observers>
</controller_action_predispatch>
<controller_action_postdispatch>
<observers>
<pioc_backoffice_shipping_observer>
<class>PIOC_Backoffice_Model_Shipping_Observer</class>
<method>hookToControllerActionPostDispatch</method>
</pioc_backoffice_shipping_observer>
</observers>
</controller_action_postdispatch>
The below are 2 custom event that we have dispathced at particular point of execution
<pioc_backoffice_shipping_save_before>
<observers>
<pioc_backoffice_shipping_observer>
<type>singleton</type>
<class>PIOC_Backoffice_Model_Shipping_Observer</class>
<method>pioc_shipping_save_before</method>
</pioc_backoffice_shipping_observer>
</observers>
</pioc_backoffice_shipping_save_before>
<pioc_backoffice_shipping_save_after>
<observers>
<pioc_backoffice_shipping_observer>
<type>singleton</type>
<class>PIOC_Backoffice_Model_Shipping_Observer</class>
<method>pioc_shipping_save_after</method>
</pioc_backoffice_shipping_observer>
</observers>
</pioc_backoffice_shipping_save_after>
———Function in observer class to dispatch events——————–
public function hookToControllerActionPreDispatch($observer)
{
//we compare action name to see if that’s action for which we want to add our own event
if($observer->getEvent()->getControllerAction()->getFullActionName() == ‘canvassizecat_adminhtml_myform_post’)
{
//We are dispatching our own event before action ADD is run and sending parameters we need
Mage::dispatchEvent(“pioc_backoffice_shipping_save_before”, array(‘request’ => $observer->getControllerAction()->getRequest()));
}
}
public function hookToControllerActionPostDispatch($observer)
{
if($observer->getEvent()->getControllerAction()->getFullActionName() == ‘canvassizecat_adminhtml_myform_post’)
{
//We are dispatching our own event before action ADD is run and sending parameters we need
Mage::dispatchEvent(“pioc_backoffice_shipping_save_after”, array(‘request’ => $observer->getControllerAction()->getRequest()));
}
}

Convert Magento Database to Innodb

ALTER TABLE `admin_assert` ENGINE=InnoDB;
ALTER TABLE `admin_role` ENGINE=InnoDB;
ALTER TABLE `admin_rule` ENGINE=InnoDB;
ALTER TABLE `admin_user` ENGINE=InnoDB;
ALTER TABLE `adminnotification_inbox` ENGINE=InnoDB;
ALTER TABLE `api_assert` ENGINE=InnoDB;
ALTER TABLE `api_role` ENGINE=InnoDB;
ALTER TABLE `api_rule` ENGINE=InnoDB;
ALTER TABLE `api_user` ENGINE=InnoDB;
ALTER TABLE `catalog_category_entity` ENGINE=InnoDB;
ALTER TABLE `catalog_category_entity_datetime` ENGINE=InnoDB;
ALTER TABLE `catalog_category_entity_decimal` ENGINE=InnoDB;
ALTER TABLE `catalog_category_entity_int` ENGINE=InnoDB;
ALTER TABLE `catalog_category_entity_text` ENGINE=InnoDB;
ALTER TABLE `catalog_category_entity_varchar` ENGINE=InnoDB;
ALTER TABLE `catalog_category_product` ENGINE=InnoDB;
ALTER TABLE `catalog_category_product_index` ENGINE=InnoDB;
ALTER TABLE `catalog_compare_item` ENGINE=InnoDB;
ALTER TABLE `catalog_product_bundle_option` ENGINE=InnoDB;
ALTER TABLE `catalog_product_bundle_option_value` ENGINE=InnoDB;
ALTER TABLE `catalog_product_bundle_selection` ENGINE=InnoDB;
ALTER TABLE `catalog_product_enabled_index` ENGINE=InnoDB;
ALTER TABLE `catalog_product_entity` ENGINE=InnoDB;
ALTER TABLE `catalog_product_entity_datetime` ENGINE=InnoDB;
ALTER TABLE `catalog_product_entity_decimal` ENGINE=InnoDB;
ALTER TABLE `catalog_product_entity_gallery` ENGINE=InnoDB;
ALTER TABLE `catalog_product_entity_int` ENGINE=InnoDB;
ALTER TABLE `catalog_product_entity_media_gallery` ENGINE=InnoDB;
ALTER TABLE `catalog_product_entity_media_gallery_value` ENGINE=InnoDB;
ALTER TABLE `catalog_product_entity_text` ENGINE=InnoDB;
ALTER TABLE `catalog_product_entity_tier_price` ENGINE=InnoDB;
ALTER TABLE `catalog_product_entity_varchar` ENGINE=InnoDB;
ALTER TABLE `catalog_product_link` ENGINE=InnoDB;
ALTER TABLE `catalog_product_link_attribute` ENGINE=InnoDB;
ALTER TABLE `catalog_product_link_attribute_decimal` ENGINE=InnoDB;
ALTER TABLE `catalog_product_link_attribute_int` ENGINE=InnoDB;
ALTER TABLE `catalog_product_link_attribute_varchar` ENGINE=InnoDB;
ALTER TABLE `catalog_product_link_type` ENGINE=InnoDB;
ALTER TABLE `catalog_product_option` ENGINE=InnoDB;
ALTER TABLE `catalog_product_option_price` ENGINE=InnoDB;
ALTER TABLE `catalog_product_option_title` ENGINE=InnoDB;
ALTER TABLE `catalog_product_option_type_price` ENGINE=InnoDB;
ALTER TABLE `catalog_product_option_type_title` ENGINE=InnoDB;
ALTER TABLE `catalog_product_option_type_value` ENGINE=InnoDB;
ALTER TABLE `catalog_product_super_attribute` ENGINE=InnoDB;
ALTER TABLE `catalog_product_super_attribute_label` ENGINE=InnoDB;
ALTER TABLE `catalog_product_super_attribute_pricing` ENGINE=InnoDB;
ALTER TABLE `catalog_product_super_link` ENGINE=InnoDB;
ALTER TABLE `catalog_product_website` ENGINE=InnoDB;
ALTER TABLE `catalogindex_aggregation` ENGINE=InnoDB;
ALTER TABLE `catalogindex_aggregation_tag` ENGINE=InnoDB;
ALTER TABLE `catalogindex_aggregation_to_tag` ENGINE=InnoDB;
ALTER TABLE `catalogindex_eav` ENGINE=InnoDB;
ALTER TABLE `catalogindex_minimal_price` ENGINE=InnoDB;
ALTER TABLE `catalogindex_price` ENGINE=InnoDB;
ALTER TABLE `cataloginventory_stock` ENGINE=InnoDB;
ALTER TABLE `cataloginventory_stock_item` ENGINE=InnoDB;
ALTER TABLE `catalogrule` ENGINE=InnoDB;
ALTER TABLE `catalogrule_affected_product` ENGINE=InnoDB;
ALTER TABLE `catalogrule_product` ENGINE=InnoDB;
ALTER TABLE `catalogrule_product_price` ENGINE=InnoDB;
ALTER TABLE `catalogsearch_fulltext` ENGINE=MyISAM;
ALTER TABLE `catalogsearch_query` ENGINE=InnoDB;
ALTER TABLE `catalogsearch_result` ENGINE=InnoDB;
ALTER TABLE `checkout_agreement` ENGINE=InnoDB;
ALTER TABLE `checkout_agreement_store` ENGINE=InnoDB;
ALTER TABLE `cms_block` ENGINE=InnoDB;
ALTER TABLE `cms_block_store` ENGINE=InnoDB;
ALTER TABLE `cms_page` ENGINE=InnoDB;
ALTER TABLE `cms_page_store` ENGINE=InnoDB;
ALTER TABLE `core_config_data` ENGINE=InnoDB;
ALTER TABLE `core_email_template` ENGINE=InnoDB;
ALTER TABLE `core_flag` ENGINE=InnoDB;
ALTER TABLE `core_layout_link` ENGINE=InnoDB;
ALTER TABLE `core_layout_update` ENGINE=InnoDB;
ALTER TABLE `core_resource` ENGINE=InnoDB;
ALTER TABLE `core_session` ENGINE=InnoDB;
ALTER TABLE `core_store` ENGINE=InnoDB;
ALTER TABLE `core_store_group` ENGINE=InnoDB;
ALTER TABLE `core_translate` ENGINE=InnoDB;
ALTER TABLE `core_url_rewrite` ENGINE=InnoDB;
ALTER TABLE `core_website` ENGINE=InnoDB;
ALTER TABLE `cron_schedule` ENGINE=InnoDB;
ALTER TABLE `customer_address_entity` ENGINE=InnoDB;
ALTER TABLE `customer_address_entity_datetime` ENGINE=InnoDB;
ALTER TABLE `customer_address_entity_decimal` ENGINE=InnoDB;
ALTER TABLE `customer_address_entity_int` ENGINE=InnoDB;
ALTER TABLE `customer_address_entity_text` ENGINE=InnoDB;
ALTER TABLE `customer_address_entity_varchar` ENGINE=InnoDB;
ALTER TABLE `customer_entity` ENGINE=InnoDB;
ALTER TABLE `customer_entity_datetime` ENGINE=InnoDB;
ALTER TABLE `customer_entity_decimal` ENGINE=InnoDB;
ALTER TABLE `customer_entity_int` ENGINE=InnoDB;
ALTER TABLE `customer_entity_text` ENGINE=InnoDB;
ALTER TABLE `customer_entity_varchar` ENGINE=InnoDB;
ALTER TABLE `customer_group` ENGINE=InnoDB;
ALTER TABLE `dataflow_batch` ENGINE=InnoDB;
ALTER TABLE `dataflow_batch_export` ENGINE=InnoDB;
ALTER TABLE `dataflow_batch_import` ENGINE=InnoDB;
ALTER TABLE `dataflow_import_data` ENGINE=InnoDB;
ALTER TABLE `dataflow_profile` ENGINE=InnoDB;
ALTER TABLE `dataflow_profile_history` ENGINE=InnoDB;
ALTER TABLE `dataflow_session` ENGINE=InnoDB;
ALTER TABLE `design_change` ENGINE=InnoDB;
ALTER TABLE `directory_country` ENGINE=InnoDB;
ALTER TABLE `directory_country_format` ENGINE=InnoDB;
ALTER TABLE `directory_country_region` ENGINE=InnoDB;
ALTER TABLE `directory_country_region_name` ENGINE=InnoDB;
ALTER TABLE `directory_currency_rate` ENGINE=InnoDB;
ALTER TABLE `downloadable_link` ENGINE=InnoDB;
ALTER TABLE `downloadable_link_price` ENGINE=InnoDB;
ALTER TABLE `downloadable_link_purchased` ENGINE=InnoDB;
ALTER TABLE `downloadable_link_purchased_item` ENGINE=InnoDB;
ALTER TABLE `downloadable_link_title` ENGINE=InnoDB;
ALTER TABLE `downloadable_sample` ENGINE=InnoDB;
ALTER TABLE `downloadable_sample_title` ENGINE=InnoDB;
ALTER TABLE `eav_attribute` ENGINE=InnoDB;
ALTER TABLE `eav_attribute_group` ENGINE=InnoDB;
ALTER TABLE `eav_attribute_option` ENGINE=InnoDB;
ALTER TABLE `eav_attribute_option_value` ENGINE=InnoDB;
ALTER TABLE `eav_attribute_set` ENGINE=InnoDB;
ALTER TABLE `eav_entity` ENGINE=InnoDB;
ALTER TABLE `eav_entity_attribute` ENGINE=InnoDB;
ALTER TABLE `eav_entity_datetime` ENGINE=InnoDB;
ALTER TABLE `eav_entity_decimal` ENGINE=InnoDB;
ALTER TABLE `eav_entity_int` ENGINE=InnoDB;
ALTER TABLE `eav_entity_store` ENGINE=InnoDB;
ALTER TABLE `eav_entity_text` ENGINE=InnoDB;
ALTER TABLE `eav_entity_type` ENGINE=InnoDB;
ALTER TABLE `eav_entity_varchar` ENGINE=InnoDB;
ALTER TABLE `gift_message` ENGINE=InnoDB;
ALTER TABLE `googlebase_attributes` ENGINE=InnoDB;
ALTER TABLE `googlebase_items` ENGINE=InnoDB;
ALTER TABLE `googlebase_types` ENGINE=InnoDB;
ALTER TABLE `googlecheckout_api_debug` ENGINE=InnoDB;
ALTER TABLE `googleoptimizer_code` ENGINE=InnoDB;
ALTER TABLE `log_customer` ENGINE=MyISAM;
ALTER TABLE `log_quote` ENGINE=MyISAM;
ALTER TABLE `log_summary` ENGINE=MyISAM;
ALTER TABLE `log_summary_type` ENGINE=MyISAM;
ALTER TABLE `log_url` ENGINE=MyISAM;
ALTER TABLE `log_url_info` ENGINE=MyISAM;
ALTER TABLE `log_visitor` ENGINE=MyISAM;
ALTER TABLE `log_visitor_info` ENGINE=MyISAM;
ALTER TABLE `newsletter_problem` ENGINE=InnoDB;
ALTER TABLE `newsletter_queue` ENGINE=InnoDB;
ALTER TABLE `newsletter_queue_link` ENGINE=InnoDB;
ALTER TABLE `newsletter_queue_store_link` ENGINE=InnoDB;
ALTER TABLE `newsletter_subscriber` ENGINE=InnoDB;
ALTER TABLE `newsletter_template` ENGINE=InnoDB;
#ALTER TABLE `oscommerce_import` ENGINE=InnoDB;
#ALTER TABLE `oscommerce_import_type` ENGINE=InnoDB;
#ALTER TABLE `oscommerce_orders` ENGINE=MyISAM;
#ALTER TABLE `oscommerce_orders_products` ENGINE=MyISAM;
#ALTER TABLE `oscommerce_orders_status_history` ENGINE=MyISAM;
#ALTER TABLE `oscommerce_orders_total` ENGINE=MyISAM;
#ALTER TABLE `oscommerce_ref` ENGINE=InnoDB;
#ALTER TABLE `paybox_api_debug` ENGINE=InnoDB;
#ALTER TABLE `paybox_question_number` ENGINE=InnoDB;
ALTER TABLE `paygate_authorizenet_debug` ENGINE=MyISAM;
ALTER TABLE `paypal_api_debug` ENGINE=MyISAM;
ALTER TABLE `paypaluk_api_debug` ENGINE=InnoDB;
ALTER TABLE `poll` ENGINE=InnoDB;
ALTER TABLE `poll_answer` ENGINE=InnoDB;
ALTER TABLE `poll_store` ENGINE=InnoDB;
ALTER TABLE `poll_vote` ENGINE=InnoDB;
ALTER TABLE `product_alert_price` ENGINE=InnoDB;
ALTER TABLE `product_alert_stock` ENGINE=MyISAM;
ALTER TABLE `rating` ENGINE=InnoDB;
ALTER TABLE `rating_entity` ENGINE=InnoDB;
ALTER TABLE `rating_option` ENGINE=InnoDB;
ALTER TABLE `rating_option_vote` ENGINE=InnoDB;
ALTER TABLE `rating_option_vote_aggregated` ENGINE=InnoDB;
ALTER TABLE `rating_store` ENGINE=InnoDB;
ALTER TABLE `rating_title` ENGINE=InnoDB;
ALTER TABLE `report_event` ENGINE=InnoDB;
ALTER TABLE `report_event_types` ENGINE=InnoDB;
ALTER TABLE `review` ENGINE=InnoDB;
ALTER TABLE `review_detail` ENGINE=InnoDB;
ALTER TABLE `review_entity` ENGINE=InnoDB;
ALTER TABLE `review_entity_summary` ENGINE=InnoDB;
ALTER TABLE `review_status` ENGINE=InnoDB;
ALTER TABLE `review_store` ENGINE=InnoDB;
ALTER TABLE `sales_bestsellers_aggregated_daily` ENGINE=InnoDB;
ALTER TABLE `sales_bestsellers_aggregated_monthly` ENGINE=InnoDB;
ALTER TABLE `sales_bestsellers_aggregated_yearly` ENGINE=InnoDB;
ALTER TABLE `sales_billing_agreement` ENGINE=InnoDB;
ALTER TABLE `sales_billing_agreement_order` ENGINE=InnoDB;
ALTER TABLE `sales_flat_creditmemo` ENGINE=InnoDB;
ALTER TABLE `sales_flat_creditmemo_comment` ENGINE=InnoDB;
ALTER TABLE `sales_flat_creditmemo_grid` ENGINE=InnoDB;
ALTER TABLE `sales_flat_creditmemo_item` ENGINE=InnoDB;
ALTER TABLE `sales_flat_invoice` ENGINE=InnoDB;
ALTER TABLE `sales_flat_invoice_comment` ENGINE=InnoDB;
ALTER TABLE `sales_flat_invoice_grid` ENGINE=InnoDB;
ALTER TABLE `sales_flat_invoice_item` ENGINE=InnoDB;
ALTER TABLE `sales_flat_order` ENGINE=InnoDB;
ALTER TABLE `sales_flat_order_address` ENGINE=InnoDB;
ALTER TABLE `sales_flat_order_grid` ENGINE=InnoDB;
ALTER TABLE `sales_flat_order_item` ENGINE=InnoDB;
ALTER TABLE `sales_flat_order_payment` ENGINE=InnoDB;
ALTER TABLE `sales_flat_order_shipping_rate` ENGINE=InnoDB;
ALTER TABLE `sales_flat_order_status_history` ENGINE=InnoDB;
ALTER TABLE `sales_flat_quote` ENGINE=InnoDB;
ALTER TABLE `sales_flat_quote_address` ENGINE=InnoDB;
ALTER TABLE `sales_flat_quote_address_item` ENGINE=InnoDB;
ALTER TABLE `sales_flat_quote_item` ENGINE=InnoDB;
ALTER TABLE `sales_flat_quote_item_option` ENGINE=InnoDB;
ALTER TABLE `sales_flat_quote_payment` ENGINE=InnoDB;
ALTER TABLE `sales_flat_quote_shipping_rate` ENGINE=InnoDB;
ALTER TABLE `sales_flat_shipment` ENGINE=InnoDB;
ALTER TABLE `sales_flat_shipment_comment` ENGINE=InnoDB;
ALTER TABLE `sales_flat_shipment_grid` ENGINE=InnoDB;
ALTER TABLE `sales_flat_shipment_item` ENGINE=InnoDB;
ALTER TABLE `sales_flat_shipment_track` ENGINE=InnoDB;
ALTER TABLE `sales_invoiced_aggregated` ENGINE=InnoDB;
ALTER TABLE `sales_invoiced_aggregated_order` ENGINE=InnoDB;
ALTER TABLE `sales_order_aggregated_created` ENGINE=InnoDB;
ALTER TABLE `sales_order_tax` ENGINE=InnoDB;
ALTER TABLE `sales_payment_transaction` ENGINE=InnoDB;
ALTER TABLE `sales_recurring_profile` ENGINE=InnoDB;
ALTER TABLE `sales_recurring_profile_order` ENGINE=InnoDB;
ALTER TABLE `sales_refunded_aggregated` ENGINE=InnoDB;
ALTER TABLE `sales_refunded_aggregated_order` ENGINE=InnoDB;
ALTER TABLE `sales_shipping_aggregated` ENGINE=InnoDB;
ALTER TABLE `sales_shipping_aggregated_order` ENGINE=InnoDB;
ALTER TABLE `salesrule` ENGINE=InnoDB;
ALTER TABLE `salesrule_coupon` ENGINE=InnoDB;
ALTER TABLE `salesrule_coupon_usage` ENGINE=InnoDB;
ALTER TABLE `salesrule_customer` ENGINE=InnoDB;
ALTER TABLE `salesrule_label` ENGINE=InnoDB;
ALTER TABLE `sendfriend_log` ENGINE=MyISAM;
ALTER TABLE `shipping_tablerate` ENGINE=InnoDB;
ALTER TABLE `sitemap` ENGINE=InnoDB;
ALTER TABLE `tag` ENGINE=InnoDB;
ALTER TABLE `tag_relation` ENGINE=InnoDB;
ALTER TABLE `tag_summary` ENGINE=InnoDB;
ALTER TABLE `tax_calculation` ENGINE=InnoDB;
ALTER TABLE `tax_calculation_rate` ENGINE=InnoDB;
ALTER TABLE `tax_calculation_rate_title` ENGINE=InnoDB;
ALTER TABLE `tax_calculation_rule` ENGINE=InnoDB;
ALTER TABLE `tax_class` ENGINE=InnoDB;
ALTER TABLE `weee_discount` ENGINE=InnoDB;
ALTER TABLE `weee_tax` ENGINE=InnoDB;
ALTER TABLE `wishlist` ENGINE=InnoDB;
ALTER TABLE `wishlist_item` ENGINE=InnoDB;

Different kind of catalog sorting (top selling,top rated, new products, special products) in magento

////////////////////////////////////
template/catalog/product/list/toolbar.phtml
<div class=”demoTarget toolbar”>
<span class=”pagingTotal”>Order:</span>
<?php /*?><select onchange=”setLocation(this.value)” id=”default-usage-selectdate”>
<?php foreach($this->getAvailableOrders() as $_key=>$_order): ?>
<option value=”<?php echo $this->getOrderUrl($_key, ‘asc’) ?>”<?php if($this->isOrderCurrent($_key)): ?> selected=”selected”<?php endif; ?>>
<?php echo $this->__($_order) ?>
</option>
<?php endforeach; ?>
</select><?php */?>
<?php $orderDir = $this->getRequest()->getParam(‘dir’);?>
<select onchange=”setLocation(this.value)” id=”default-usage-selectdate”>
<option value=”<?php echo $this->getOrderUrl(‘topsellings’, ‘desc’) ?>”<?php if($this->isOrderCurrent(‘topsellings’)): ?> selected=”selected”<?php endif; ?>>
Top Selling
</option>
<option value=”<?php echo $this->getOrderUrl(‘special_price’, ‘desc’) ?>”<?php if($this->isOrderCurrent(‘special_price’)): ?> selected=”selected”<?php endif; ?>>
Special Orice
</option>
<option value=”<?php echo $this->getOrderUrl(‘newest’, ‘desc’) ?>”<?php if($this->isOrderCurrent(‘newest’)): ?> selected=”selected”<?php endif; ?>>
New Products
</option>
<option value=”<?php echo $this->getOrderUrl(‘popularity’, ‘desc’) ?>”<?php if($this->isOrderCurrent(‘popularity’)): ?> selected=”selected”<?php endif; ?>>
Popularity (Most Rated)
</option>
</select>
<div class=”clr”></div>
</div>
——————————————————————————–
D:\xampp\htdocs\lamemo\live\app\code\core\Mage\Catalog\Block\Product\List\Toolbar.php
in function setCollection() put below code
————————————————-
<?php
if($this->getCurrentOrder() == ‘popularity’){
$this->_collection->joinField(‘rating_score’,
‘lamemoreview_entity_summary’,
‘rating_summary’,
‘entity_pk_value=entity_id’,
array(‘entity_type’=>1, ‘store_id’=> Mage::app()->getStore()->getId()),
‘left’
)->setOrder(‘rating_score’, $this->getCurrentDirection());
}
elseif($this->getCurrentOrder() ==’special_price’)
{
$todayDate = Mage::app()->getLocale()->date()->toString(Varien_Date::DATETIME_INTERNAL_FORMAT);
/*$this->_collection->addAttributeToFilter(‘special_from_date’, array(‘or’=> array(
0 => array(‘date’ => true, ‘to’ => $todayDate),
1 => array(‘is’ => new Zend_Db_Expr(‘null’)))
))->addAttributeToFilter(‘special_to_date’, array(‘or’=> array(
0 => array(‘date’ => true, ‘from’ => $todayDate),
1 => array(‘is’ => new Zend_Db_Expr(‘null’)))
))->addAttributeToSort(‘special_price’, ‘DESC’);*/
/*$this->_collection->joinTable(‘lamemocatalog_product_flat_1′,’entity_id=entity_id’,array(‘goodcustom’=>”abs (lamemocatalog_product_flat_1.special_from_date <= ‘”.$todayDate.”‘ and (lamemocatalog_product_flat_1.special_to_date >= ‘”.$todayDate.”‘ or lamemocatalog_product_flat_1.special_to_date = NULL))”),NULL,’left’)->getSelect()->order(“goodcustom desc”);
echo $this->_collection->getSelect();*/
$this->_collection->joinTable(‘lamemocatalog_product_flat_1′,’entity_id=entity_id’,array(‘cust_ord_field’=>”IF((special_from_date <= ‘”.$todayDate.”‘ &&
(special_to_date >= ‘”.$todayDate.”‘ || isnull(special_to_date))),’yes’,'no’)”),NULL,’left’);
$this->_collection->getSelect()->order(“cust_ord_field desc”);
$this->_collection->getSelect()->order(“final_price asc”);
//echo $this->_collection->getSelect();
/*$this->_collection->addAttributeToFilter(‘special_from_date’, array(‘date’ => true, ‘to’ => $todayDate))
->addAttributeToFilter(‘special_to_date’, array(‘or’=> array(
0 => array(‘date’ => true, ‘from’ => $todayDate),
1 => array(‘is’ => new Zend_Db_Expr(‘null’)))
), ‘left’)->addAttributeToSort(‘special_price’, ‘ASC’);*/
}
elseif($this->getCurrentOrder() == ‘newest’){
$todayDate = Mage::app()->getLocale()->date()->toString(Varien_Date::DATETIME_INTERNAL_FORMAT);
/*$this->_collection->addAttributeToFilter(‘news_from_date’, array(‘date’ => true, ‘to’ => $todayDate))
->addAttributeToFilter(‘news_to_date’, array(‘or’=> array(
0 => array(‘date’ => true, ‘from’ => $todayDate),
1 => array(‘is’ => new Zend_Db_Expr(‘null’)))
), ‘left’)->setOrder(‘news_to_date’, $this->getCurrentDirection());;*/
/*$this->_collection->joinTable(‘lamemocatalog_product_flat_1′,’entity_id=entity_id’,array(‘goodcustom’=>”abs (lamemocatalog_product_flat_1.news_from_date <= ‘”.$todayDate.”‘ and lamemocatalog_product_flat_1.news_to_date >= ‘”.$todayDate.”‘)”),NULL,’left’)->getSelect()->order(“goodcustom desc”);
echo $this->_collection->getSelect();*/
$this->_collection->joinTable(‘lamemocatalog_product_flat_1′,’entity_id=entity_id’,array(‘cust_ord_field’=>”if(news_from_date <= ‘”.$todayDate.”‘ and
(news_to_date >= ‘”.$todayDate.”‘ || isnull(news_to_date)) ,’yes’,'no’)”),NULL,’left’);
$this->_collection->getSelect()->order(“cust_ord_field desc”);;
$this->_collection->getSelect()->order(“final_price desc”);;
//”news_from_date <= ‘”.$todayDate.”‘ and news_to_date >= ‘”.$todayDate.”‘ desc”
// echo $this->_collection->getSelect();
}
elseif($this->getCurrentOrder() == ‘topsellings’){
/* $this->_collection->getSelect()->
joinLeft(‘lamemosales_flat_order_item AS sfoi’,
‘e.entity_id = sfoi.product_id’,
‘SUM(sfoi.qty_ordered) AS ordered_qty’)->
group(‘e.entity_id’)->order(‘ordered_qty DESC’); */
create view
CREATE  VIEW `salesitemsqty` AS select `lamemosales_flat_order_item`.`product_id` AS `product_id`,count(0) AS `ord_qty` from `lamemosales_flat_order_item` group by `lamemosales_flat_order_item`.`product_id`
$this->_collection->joinTable(‘salesitemsqty’,'product_id=entity_id’,array(‘tqty_ordered’=>’ord_qty’),NULL,’left’)->setOrder(‘tqty_ordered’, $this->getCurrentDirection());
/*$this->_collection->joinField(‘ordered_qty’,
‘lamemosales_flat_order_item’,
‘SUM(qty_ordered) AS ordered_qty’,
‘product_id = entity_id’,
array(‘store_id’=> Mage::app()->getStore()->getId()),
‘left’
)->setOrder(‘ordered_qty’, $this->getCurrentDirection()); */
/*$storeId = Mage::app()->getStore()->getId();
$products = Mage::getResourceModel(‘reports/product_collection’)
->addOrderedQty()
->addAttributeToSelect(‘*’) //Need this so products show up correctly in product listing
->setStoreId($storeId)
->addStoreFilter($storeId);
Mage::getSingleton(‘catalog/product_status’)->addVisibleFilterToCollection($products);
Mage::getSingleton(‘catalog/product_visibility’)->addVisibleInCatalogFilterToCollection($products);*/
}
?>