Magento – Category tree view listing in drop-down

It took bit time to complete this task. After a big fight with the code, finally I am done with the category drop-down with subcategories parent and child tree view.

dropdown post

Here is the code, You can just create bellow function under the block or helper with your module.

function getCategoriesTreeView() {
    // Get category collection
    $categories = Mage::getModel('catalog/category')
        ->getCollection()
        ->addAttributeToSelect('name')
        ->addAttributeToSort('path', 'asc')
        ->addFieldToFilter('is_active', array('eq'=>'1'))
        ->load()
        ->toArray();

    // Arrange categories in required array
    $categoryList = array();
    foreach ($categories as $catId => $category) {
        if (isset($category['name'])) {
            $categoryList[] = array(
                'label' => $category['name'],
                'level'  =>$category['level'],
                'value' => $catId
            );
        }
    }
    return $categoryList;
}

Now its time for design, bellow is the code which will give you the category drop down.

<select id="categorylist" name="categorylist">
<option value="">Select Category</option>
<?php
    $categoriesTreeView = getCategoriesTreeView();

    foreach($categoriesTreeView as $value)
    {
        $catName    = $value['label'];
        $catId      = $value['value'];
        $catLevel    = $value['level'];

        $space = '&nbsp;';
        for($i=1; $i<$catLevel; $i++){
            $space = $space."&nbsp;";
        }
        $catName = $space.$catName;

?>
     <option value="<?php echo $catIdIs; ?>"><?php echo $catName ?></option>
 <?php
    }
?>
</select>

With the same code you can create category switcher / category changer. Just you need to get the category’s URL with the category collection and redirect to that category with on change event of drop-down.

Magento query master

This post is collection of mysql query to perform particular task, this will make you life easy.

NOTE : Basically this is not good practis to work with database directlly for live project. Make sure that you have database back up before run query.

Update customer group of all subscriber customer using query – Magento

UPDATE
    customer_entity,
    newsletter_subscriber
SET
    customer_entity.`group_id` = 5
WHERE
    customer_entity.`entity_id` = newsletter_subscriber.`customer_id`
AND
    newsletter_subscriber.`subscriber_status` = 1;

Turn template hints on/off using query – Magento

UPDATE
   core_config_data
SET
   value = 0
WHERE
   path = "dev/debug/template_hints"
OR
   path = "dev/debug/template_hints_blocks";

Change admin user password using query – magento

UPDATE admin_user SET password=CONCAT(MD5('qXpassword'), ':qX') WHERE username='admin';

Delete particular order using query – Magento

SET @increment_id='43290';
SELECT @order_id:=entity_id FROM sales_order_entity WHERE increment_id=@increment_id;
DELETE FROM sales_order_entity WHERE entity_id=@order_id OR parent_id=@order_id;
DELETE FROM sales_order WHERE increment_id=@increment_id;

Mass Exclude/Unexclude Images using query – Magento

//Mass Unexclude
UPDATE`catalog_product_entity_media_gallery_value` SET `disabled` = '0' WHERE `disabled` = '1';
//Mass Exclude
UPDATE`catalog_product_entity_media_gallery_value` SET `disabled` = '1' WHERE `disabled` = '0';

Delete all products using query – Magento

TRUNCATE TABLE `catalog_product_bundle_option`;
TRUNCATE TABLE `catalog_product_bundle_option_value`;
TRUNCATE TABLE `catalog_product_bundle_selection`;
TRUNCATE TABLE `catalog_product_entity_datetime`;
TRUNCATE TABLE `catalog_product_entity_decimal`;
TRUNCATE TABLE `catalog_product_entity_gallery`;
TRUNCATE TABLE `catalog_product_entity_int`;
TRUNCATE TABLE `catalog_product_entity_media_gallery`;
TRUNCATE TABLE `catalog_product_entity_media_gallery_value`;
TRUNCATE TABLE `catalog_product_entity_text`;
TRUNCATE TABLE `catalog_product_entity_tier_price`;
TRUNCATE TABLE `catalog_product_entity_varchar`;
TRUNCATE TABLE `catalog_product_link`;
TRUNCATE TABLE `catalog_product_link_attribute_decimal`;
TRUNCATE TABLE `catalog_product_link_attribute_int`;
TRUNCATE TABLE `catalog_product_link_attribute_varchar`;
TRUNCATE TABLE `catalog_product_option`;
TRUNCATE TABLE `catalog_product_option_price`;
TRUNCATE TABLE `catalog_product_option_title`;
TRUNCATE TABLE `catalog_product_option_type_price`;
TRUNCATE TABLE `catalog_product_option_type_title`;
TRUNCATE TABLE `catalog_product_option_type_value`;
TRUNCATE TABLE `catalog_product_super_attribute`;
TRUNCATE TABLE `catalog_product_super_attribute_label`;
TRUNCATE TABLE `catalog_product_super_attribute_pricing`;
TRUNCATE TABLE `catalog_product_super_link`;
TRUNCATE TABLE `catalog_product_enabled_index`;
TRUNCATE TABLE `catalog_product_website`;
TRUNCATE TABLE `catalog_product_entity`;
TRUNCATE TABLE `cataloginventory_stock_item`;
TRUNCATE TABLE `cataloginventory_stock_status`;

Magento – Filter product collection by multiple categories

Magento providing verious type of filter that can be used directly from product collection. Including category filter,

$_category = Mage::getModel('catalog/category')->load($category_id);
$collection= Mage::getResourceModel('catalog/product')->getCollection()->addCategoryFilter($_category);

But the issue is with multiple categories to filter. You can use bellow code to overcome this problem,

$collection = Mage::getModel('catalog/product')->getCollection()
             ->addAttributeToSelect('*')
             ->addFieldToFilter('is_saleable',1)
             ->joinField('category_id', 'catalog/category_product', 'category_id', 'product_id = entity_id', null, 'left')
             ->addAttributeToFilter('category_id', array(
                 array('finset' => '4'),
                 array('finset' => '8'))
               )
             ->addAttributeToSort('created_at', 'desc');

How magento store password and validate password – Magento

Magento uses MD5 and salt algorithems to store password for customer as well admin user.

How magento create encrypted password

Magento create encrypted password with,

Mage::getModel('core/encryption')->decrypt($password);

Here is the logic of decrypt($password) function,

 $password = "12345678";
 $salt = "at";
 $encyPasswod = md5($salt.$pass).":".$salt;

In above function, $salt is randomly generated string of two alphanumeric character.

How magento validate password

Bellow functiona will validate the user password,

Mage::getModel('customer/customer')->authenticate($email, $password);

Logic behind above function is,

 $email = "techbandhus@gmail.com";
 $password = "123456";

 //Load a customer by email address
 $customer = Mage::getModel('customer/customer')
 ->setWebsiteId(Mage::app()->getStore()->getWebsiteId())
 ->loadByEmail($email);

 // if loaded! get stored password from database
 $hash = $customer->getData("password_hash");

 // Get last two digits separate by :";
 $hashArr = explode(':', $hash);

 public function validateHash($password, $hash)
 {
     $hashArr = explode(':', $hash);
     switch (count($hashArr)) {
         case 1:
             return $this->hash($password) === $hash;
         case 2:
             return $this->hash($hashArr[1] . $password) === $hashArr[0];
     }
     Mage::throwException('Invalid hash.');
  }

So, it simply means that even if you have not added salt key and only MD5 text as password, login will work.

Magento – Show Product Reviews on Product detail Page

Product review is one of the good feature of magento but with default magento theme product review listed on separate page. Usually  customer like to see all detail on same page instead redirect to another page. With this though we would like to show the product reviews  on product detail page only.

Bellow are steps which can help you to show product reviews on product detail page.

Step-1
Call product review block on product detail page, you can add bellow code to local.xml

<catalog_product_view>
    <reference name="content">
        <block type="review/product_view_list" name="product.info.product_additional_data" as="reviews" template="review/product/view/review_summary.phtml" />
    </reference name="content">
</catalog_product_view>

step-2
Create new template file review_summary.phtml, under template/review/product/view/ folder

<?php 
    $_items = $this->getReviewsCollection()->getItems();
    if( count( $_items ) )
    {
        foreach( $_items as $_review ){
        // Get the Review Title
        echo $this->htmlEscape( $_review->getTitle() );
        // Get the Review Content
        echo $this->htmlEscape( $_review->getDetail() );
        // Get the Review Author
        echo $this->htmlEscape( $_review->getNickname() );
        } 
    } 
?>

Step-3
Call review block on view.phtml, where you need the block to be show based on your design.

<?php echo $this->getChildHtml('reviews') ?>

Magento – Get current module name, route name, controller name and action name

Many time we required to get current controller or action name or module name. Its very easy job to get get route name, module name, controller and action name for magento from current URL, anywhere in controller or even with template files.

Mage::app()->getRequest()->getControllerName(); // return controller name

Mage::app()->getRequest()->getActionName(); // return action name

Mage::app()->getRequest()->getRouteName(); // return routes name

Mage::app()->getRequest()->getModuleName(); // return module name

Magento – Delete all cancelled magento orders

There are many plug-ins are available that would add option to delete order in grid actions drop-down. But I had some requirement toset a cron job that would delete all canceled orders. We know well how to create cron job, if not this post will help you to create cron job in magento.

You can add bellow code to your model funtion that would be run by the cron job,

$collection = Mage::getResourceModel('sales/order_collection')
            ->addAttributeToSelect('*')
            ->setPageSize(1000)
            ->addFieldToFilter('status', 'canceled')
	    ->load();

foreach ($collection as $col) {
  Mage::log($col->getIncrementId() . ' order deleted ');
    try {
         $col->delete();
    } catch (Exception $e) {
        throw $e;
    }
}

Magento – Find customer who have purchased only one time

Once I had to find out the list of all costume who have purchased one one or have only one order placed.
Bellow query would be that list,

SELECT * FROM sales_flat_order GROUP BY customer_id HAVING COUNT(customer_id) = 1

One of my friend need the same with magento module only, I had given bellow solution.

$collection = Mage::getModel('customer/customer')->getCollection();
foreach ($collection as $user){
    $orders = Mage::getModel('sales/order')
                ->getCollection()
                ->addFieldToSelect('increment_id')
                ->addFieldToFilter('customer_id',$user->getId());
    if($orders->getSize() == 1){
        echo $user->getId();
    }
}

If you found some alternate solution you can suggest me, post your valuable comments.

Magento – Get all the velues of EAV attribute from attribute code

Many time we do required to get the all values of attribute or lets sey all option values of EAV attribue, while code a custom module or functionality. Bellow code would help you get all option values of EAV attribue,

// get the list of all gender type
public function getGenderList()
{
      $genders = array();
      $attribute = Mage::getModel('eav/config')->getAttribute('catalog_product', 'gender'); // "gender" is attribute_code
      $allOptions = $attribute->getSource()->getAllOptions(true, true);
      foreach ($allOptions as $instance) {
           $genders[$instance['value']] = $instance['label'];
      }
      return $genders;
}

above function will returns array of gender type, gender is attribute of catalog_product.

Magento: get current CMS page identifier

Below function will returns page identifier, if the current page is CMS page.

public function getCurrentCmsPage() {
    $dataCurrentPage = $this->getHelper('cms/page')->getPage()->getData();
    if ($dataCurrentPage) {
        $identifierCurrentPage = $dataCurrentPage['identifier'];
        return $identifierCurrentPage;  
    } 
    return;     
}