January 12, 2010

Fetching all the options values of attribute.

The below post show he syntax of  fetching values of attribute furniturebrand.
“furniturebrand” attribute type is combo.
Syntax ::
$product = Mage::getModel(“catalog/product”);
$attributes = Mage::getResourceModel(“eav/entity_attribute_collection”)
->setEntityTypeFilter($product->getResource()->getTypeId())
->addFieldToFilter(“attribute_code”, “furniturebrand”) // This can be changed to any attribute code
->load(false);
$attribute = $attributes->getFirstItem()->setEntity($product->getResource()); /* @var $attribute Mage_Eav_Model_Entity_Attribute */
$sortby = $attribute->getSource()->getAllOptions(false);
foreach($sortby as $sort_attribute) {
echo $sort_attribute['value'];
}
The above foreach loop is to display all the values of attribute furniturebrand.

To get all level categories name and url…

<?php
require_once ‘app/Mage.php’;
Mage::app();
$category = Mage::getModel(‘catalog/category’);
$tree = $category->getTreeModel();
$tree->load();
$ids = $tree->getCollection()->getAllIds();   // we can get all level categories id
if ($ids):
foreach ($ids as $id){
$cat = Mage::getModel(‘catalog/category’);
$cat->load($id);
if($id != 3): // if  category id is not “root catalog” id – here root catalog id is 3
if($cat->getIsActive()): // if category is active
$catName[] =  $cat->getName(); //  To get name of the category
$path[] = $cat->getUrl(); // to get url of category
endif;
endif;
}
?>

SQL to delete all orders

This query is very helpful to delete all records of orders from the database.
Please replace “YOUR_DB_NAME” with your database name
– Reset Magento TEST Data
SET FOREIGN_KEY_CHECKS=0;
– reset dashboard search queries
TRUNCATE `catalogsearch_query`;
ALTER TABLE `catalogsearch_query` AUTO_INCREMENT=1;
– reset sales order info
TRUNCATE `sales_order`;
TRUNCATE `sales_order_datetime`;
TRUNCATE `sales_order_decimal`;
TRUNCATE `sales_order_entity`;
TRUNCATE `sales_order_entity_datetime`;
TRUNCATE `sales_order_entity_decimal`;
TRUNCATE `sales_order_entity_int`;
TRUNCATE `sales_order_entity_text`;
TRUNCATE `sales_order_entity_varchar`;
TRUNCATE `sales_order_int`;
TRUNCATE `sales_order_text`;
TRUNCATE `sales_order_varchar`;
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 `sendfriend_log`;
TRUNCATE `tag`;
TRUNCATE `tag_relation`;
TRUNCATE `tag_summary`;
TRUNCATE `wishlist`;
TRUNCATE `log_quote`;
TRUNCATE `report_event`;
ALTER TABLE `sales_order` AUTO_INCREMENT=1;
ALTER TABLE `sales_order_datetime` AUTO_INCREMENT=1;
ALTER TABLE `sales_order_decimal` AUTO_INCREMENT=1;
ALTER TABLE `sales_order_entity` AUTO_INCREMENT=1;
ALTER TABLE `sales_order_entity_datetime` AUTO_INCREMENT=1;
ALTER TABLE `sales_order_entity_decimal` AUTO_INCREMENT=1;
ALTER TABLE `sales_order_entity_int` AUTO_INCREMENT=1;
ALTER TABLE `sales_order_entity_text` AUTO_INCREMENT=1;
ALTER TABLE `sales_order_entity_varchar` AUTO_INCREMENT=1;
ALTER TABLE `sales_order_int` AUTO_INCREMENT=1;
ALTER TABLE `sales_order_text` AUTO_INCREMENT=1;
ALTER TABLE `sales_order_varchar` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_quote` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_quote_address` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_quote_address_item` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_quote_item` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_quote_item_option` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_order_item` AUTO_INCREMENT=1;
ALTER TABLE `sendfriend_log` AUTO_INCREMENT=1;
ALTER TABLE `tag` AUTO_INCREMENT=1;
ALTER TABLE `tag_relation` AUTO_INCREMENT=1;
ALTER TABLE `tag_summary` AUTO_INCREMENT=1;
ALTER TABLE `wishlist` AUTO_INCREMENT=1;
ALTER TABLE `log_quote` AUTO_INCREMENT=1;
ALTER TABLE `report_event` AUTO_INCREMENT=1;
– Reset all ID counters
TRUNCATE `eav_entity_store`;
ALTER TABLE  `eav_entity_store` AUTO_INCREMENT=1;
SET FOREIGN_KEY_CHECKS=1;
– set appropriate prefixes for orders, invoices, shipments, credit memos
INSERT INTO  `YOUR_DB_NAME`.`eav_entity_store` (`entity_store_id` ,`entity_type_id` ,`store_id` ,`increment_prefix` ,`increment_last_id`) VALUES (‘1′,  ‘11′,  ‘1′,  ‘1′,  ‘000000000′);
update `eav_entity_store` set `increment_prefix`= 1 where `entity_type_id`=’4′ and `store_id`=’1′;
update `eav_entity_store` set `increment_last_id`= ‘000000000′ where `entity_type_id`=’4′ and `store_id`=’1′;
INSERT INTO  `YOUR_DB_NAME`.`eav_entity_store` (`entity_store_id` ,`entity_type_id` ,`store_id` ,`increment_prefix` ,`increment_last_id`) VALUES (‘2′,  ‘16′,  ‘1′,  ‘2′,  ‘000000000′);
update `eav_entity_store` set `increment_prefix`= 2 where `entity_type_id`=’18′ and `store_id`=’1′;
update `eav_entity_store` set `increment_last_id`= ‘000000000′ where `entity_type_id`=’18′ and `store_id`=’1′;
INSERT INTO  `YOUR_DB_NAME`.`eav_entity_store` (`entity_store_id` ,`entity_type_id` ,`store_id` ,`increment_prefix` ,`increment_last_id`) VALUES (‘3′,  ‘19′,  ‘1′,  ‘3′,  ‘000000000′);
update `eav_entity_store` set `increment_prefix`= 3 where `entity_type_id`=’24′ and `store_id`=’1′;
update `eav_entity_store` set `increment_last_id`= ‘000000000′ where `entity_type_id`=’24′ and `store_id`=’1′;
INSERT INTO  `YOUR_DB_NAME`.`eav_entity_store` (`entity_store_id` ,`entity_type_id` ,`store_id` ,`increment_prefix` ,`increment_last_id`) VALUES (‘4′,  ‘23′,  ‘1′,  ‘4′,  ‘000000000′);
update `eav_entity_store` set `increment_prefix`= 4 where `entity_type_id`=’28′ and `store_id`=’1′;
update `eav_entity_store` set `increment_last_id`= ‘000000000′ where `entity_type_id`=’28′ and `store_id`=’1′;

How to get different URLs?

* Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_JS);
http://magesite.extension/js/
* Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_LINK);
http://magesite.extension/index.php/
* Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA);
http://magesite.extension/media/
* Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_SKIN);
http://magesite.extension/skin/
* Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB);

To add custom date field in custom module of admin panel

You can see the below code to add start date and end date field in admin custom module(Which is created using module creator).
Create two fields “start_date” and “end_date” in database table of your custom module.
$dateFormatIso = Mage::app()->getLocale() ->getDateFormat(Mage_Core_Model_Locale::FORMAT_TYPE_SHORT);
$fieldset->addField(’start_date’, ‘date’, array(
‘label’ => Mage::helper(‘banner’)->__(‘Start Date’),
‘title’ => Mage::helper(‘banner’)->__(‘Start Date’),
‘name’ => ’start_date’,
‘image’ => $this->getSkinUrl(‘images/grid-cal.gif’),
‘format’ => $dateFormatIso,
‘value’ => ’start_date’,
//’required’ => true,
));
$fieldset->addField(‘end_date’, ‘date’, array(
‘label’ => Mage::helper(‘banner’)->__(‘End Date’),
‘title’ => Mage::helper(‘banner’)->__(‘End Date’),
‘name’ => ‘end_date’,
‘image’ => $this->getSkinUrl(‘images/grid-cal.gif’),
‘format’ => $dateFormatIso,
‘value’ => ‘end_date’,
//’required’ => true,
));
Copy and paste the above code to your custom_module/block/adminhtml/custom_module/Edit/Tab/Form.php file
and than open controller of the same module
Path :: custom_module/controllers/adminhtml/custommoduleController.php
Add below lines before $model->save() to save dates in
function saveAction().
if($data['start_date'] != NULL )
{
$date = Mage::app()->getLocale()->date($data['start_date'], Zend_Date::DATE_SHORT);
$model->setStartDate($date->toString(‘YYYY-MM-dd HH:mm:ss’));
}
if($data['end_date'] != NULL)
{
$date1 = Mage::app()->getLocale()->date($data['end_date'], Zend_Date::DATE_SHORT);
$model->setEndDate($date1->toString(‘YYYY-MM-dd HH:mm:ss’));
}

Subscriptions and Recurring Payments – new version and new user guide!

Today we are ready to announce 2 pieces of good news about the Subscriptions and Recurring Payments extension!
The first one is that User Guide is available to download from the extension page. The guide will make the work with Subscriptions and Recurring Payments much easier. In addition to covering all moments of the extension functioning – module configuration, managing subscriptions, subscribers and subscription products, etc. – you will find out how to manage subscriptions for customer’s part.
The next important point is the release of new version. The extension works more stable now as the following bugs were fixed:
  • It’s available to add product to cart from grid view even if product requires subscription options
  • Magento clears quotes after N days and subscription losts billing and shipping addresses
  • ePay 0.00 transaction payment fee is displayed on order page for recurring orders
  • Subscribers list exporting error
You can find the complete changelog and download the User Guide from the extension page.

January 8, 2010

Add a tree like left menu in Magento.

Magento in common has no left menu.
So i edit some core and design code to implement a left tree like menu.
Here i give the example of my code.
Step 1:Edit core code in app/code/core/mage/catalog/Block/Navigation.php and add these code in LeftNav.php in same place


<?php
/**
 * Magento
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Open Software License (OSL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/osl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magentocommerce.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magentocommerce.com for more information.
 *
 * @category   Mage
 * @package    Mage_Catalog
 * @copyright  Copyright (c) 2008 Irubin Consulting Inc. DBA Varien (http://www.varien.com)
 * @license    http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
 */

/**
 * Catalog navigation
 *
 * @category   Mage
 * @package    Mage_Catalog
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Mage_Catalog_Block_LeftNav extends Mage_Core_Block_Template
{
    protected $_categoryInstance = null;

    protected function _construct()
    {
        $this->addData(array(
            'cache_lifetime'    => false,
            'cache_tags'        => array(Mage_Catalog_Model_Category::CACHE_TAG, Mage_Core_Model_Store_Group::CACHE_TAG),
        ));
    }

    /**
     * Retrieve Key for caching block content
     *
     * @return string
     */
    public function getCacheKey()
    {
        return 'CATALOG_NAVIGATION_' . Mage::app()->getStore()->getId()
            . '_' . Mage::getDesign()->getPackageName()
            . '_' . Mage::getDesign()->getTheme('template')
            . '_' . Mage::getSingleton('customer/session')->getCustomerGroupId()
            . '_' . md5($this->getTemplate() . $this->getCurrenCategoryKey());
    }

    public function getCurrenCategoryKey()
    {
        if ($category = Mage::registry('current_category')) {
            return $category->getPath();
        } else {
            return Mage::app()->getStore()->getRootCategoryId();
        }
    }

    /**
     * Get catagories of current store
     *
     * @return Varien_Data_Tree_Node_Collection
     */
    public function getStoreCategories()
    {
        $helper = Mage::helper('catalog/category');
        return $helper->getStoreCategories();
    }

    /**
     * Retrieve child categories of current category
     *
     * @return Varien_Data_Tree_Node_Collection
     */
    public function getCurrentChildCategories()
    {
        $layer = Mage::getSingleton('catalog/layer');
        $category   = $layer->getCurrentCategory();
        /* @var $category Mage_Catalog_Model_Category */
        $categories = $category->getChildrenCategories();
        $productCollection = Mage::getResourceModel('catalog/product_collection');
        $layer->prepareProductCollection($productCollection);
        $productCollection->addCountToCategories($categories);
        return $categories;
    }

    /**
     * Checkin activity of category
     *
     * @param   Varien_Object $category
     * @return  bool
     */
    public function isCategoryActive($category)
    {
        if ($this->getCurrentCategory()) {
            return in_array($category->getId(), $this->getCurrentCategory()->getPathIds());
        }
        return false;
    }

    protected function _getCategoryInstance()
    {
        if (is_null($this->_categoryInstance)) {
            $this->_categoryInstance = Mage::getModel('catalog/category');
        }
        return $this->_categoryInstance;
    }

    /**
     * Get url for category data
     *
     * @param Mage_Catalog_Model_Category $category
     * @return string
     */
    public function getCategoryUrl($category)
    {
        if ($category instanceof Mage_Catalog_Model_Category) {
            $url = $category->getUrl();
        } else {
            $url = $this->_getCategoryInstance()
                ->setData($category->getData())
                ->getUrl();
        }

        return $url;
    }

    /**
     * Enter description here...
     *
     * @param Mage_Catalog_Model_Category $category
     * @param int $level
     * @param boolean $last
     * @return string
     */
    public function drawItem($category, $level=0, $last=false)
    {
        $html = '';
        if (!$category->getIsActive()) {
            return $html;
        }
        if (Mage::helper('catalog/category_flat')->isEnabled()) {
            $children = $category->getChildrenNodes();
            $childrenCount = count($children);
        } else {
            $children = $category->getChildren();
            $childrenCount = $children->count();
        }
        $hasChildren = $children && $childrenCount;
        $html.= '<li';
        if ($hasChildren) {
             //$html.= ' onmouseover="toggleMenu(this,1)" onmouseout="toggleMenu(this,0)"';
   //replace
   $html.= '';
        }

       // $html.= ' class="level'.$level;
       // $html.= ' nav-'.str_replace('/', '-', Mage::helper('catalog/category')->getCategoryUrlPath($category->getRequestPath()));
        if ($this->isCategoryActive($category)) {
           // $html.= ' active';
      $html .='';
        }
        if ($last) {
           // $html .= ' last';
      $html .='';
        }
        if ($hasChildren) {
            $cnt = 0;
            foreach ($children as $child) {
                if ($child->getIsActive()) {
                    $cnt++;
                }
            }
            if ($cnt > 0) {
              //  $html .= ' parent';
      //$html .=' current';
      $html .='';
            }
        }
        $html.= '>'."\n";
        $html.= '<a href="'.$this->getCategoryUrl($category).'"><span>'.$this->htmlEscape($category->getName()).'</span></a>'."\n";

        if ($hasChildren){

            $j = 0;
            $htmlChildren = '';
            foreach ($children as $child) {
                if ($child->getIsActive()) {
                    $htmlChildren.= $this->drawItem($child, $level+1, ++$j >= $cnt);
                }
            }

            if (!empty($htmlChildren)) {
                $html.= '<ul>'."\n"
                        .$htmlChildren
                        .'</ul>';
            }

        }
        $html.= '</li>'."\n";
        return $html;
    }

    /**
     * Enter description here...
     *
     * @return Mage_Catalog_Model_Category
     */
    public function getCurrentCategory()
    {
        if (Mage::getSingleton('catalog/layer')) {
            return Mage::getSingleton('catalog/layer')->getCurrentCategory();
        }
        return false;
    }

    /**
     * Enter description here...
     *
     * @return string
     */
    public function getCurrentCategoryPath()
    {
        if ($this->getCurrentCategory()) {
            return explode(',', $this->getCurrentCategory()->getPathInStore());
        }
        return array();
    }

    /**
     * Enter description here...
     *
     * @param Mage_Catalog_Model_Category $category
     * @return string
     */
    public function drawOpenCategoryItem($category) {
        $html = '';
        if (!$category->getIsActive()) {
            return $html;
        }

        $html.= '<li';

        if ($this->isCategoryActive($category)) {
            $html.= ' class="active"';
        }

        $html.= '>'."\n";
        $html.= '<a href="'.$this->getCategoryUrl($category).'"><span>'.$this->htmlEscape($category->getName()).'</span></a>'."\n";

        if (in_array($category->getId(), $this->getCurrentCategoryPath())){
            $children = $category->getChildren();
            $hasChildren = $children && $children->count();

            if ($hasChildren) {
                $htmlChildren = '';
                foreach ($children as $child) {
                    $htmlChildren.= $this->drawOpenCategoryItem($child);
                }

                if (!empty($htmlChildren)) {
                    $html.= '<ul>'."\n"
                            .$htmlChildren
                            .'</ul>';
                }
            }
        }
        $html.= '</li>'."\n";
        return $html;
    }

}

add categories with images on homepage – magento

to add categories along with images on homepage
just add the code given below to your homepage from admininstration cms management.
{{block type="catalog/navigation" name="catalog.category" template="catalog/category/list.phtml"}}
Also you need to create a list.phtml file under “/app/design/frontend/default/default/template/catalog/category/list.phtml”
and add the below given code to it:
===========================================
<?php foreach ($this->getStoreCategories() as $_category): ?>
<?php $open
= $this->isCategoryActive($_category); ?>
<?php
$cur_category
=Mage::getModel('catalog/category')->load($_category->getId());
$layer = Mage::getSingleton('catalog/layer');
$layer->setCurrentCategory($cur_category);
if (
$immagine = $this->getCurrentCategory()->getImageUrl()):
?> <div style="float: left; padding-right: 30px; text-align: center;">
<
div class="linkimage">
<
p>
<
a href="<?php echo $this->getCategoryUrl($_category)?>">
<
img src="<?php echo $immagine ?>" alt="<?php echo $this->htmlEscape($this->getCurrentCategory()->getName()) ?>" width="135" height="135" />
<?php echo $_category->getName()?>
</a>
</
p>
</
div>
</
div> <?php endif; ?>
<?php
endforeach; ?>
================================================

January 5, 2010

Manual creation of Google Sitemap in Magento

Most of you probably know this, but let’s define what the sitemaps are. Sitemaps are a simple way for site creators to give search engines the information about pages on their site that are available for public. Basically, those are just 1 or more XML files that lists URLs for a site along with additional meta informatio about each URL (like last update, how often it changes, its importance relevant to other pages). With this in mind, search engines can be more clever while crawling the site. Click here see how sitemap of this site looks like.

You will hear the term Google Sitemap a lot, but XML Schema for the Sitemap protocol is not related only to Google at all. It can be used in many places, but the most important ones are Google Webmaster Tools and Yahoo! Site Explorer.

How do we create Google Sitemap in Magento?

1. Sitemap File Configuration

First we need to create sitemap file in Magento. This is basically pointer to tell Magento where to create sitemap file and how to name it. Log in to Magento Administration and go to:
Catalog -> Google Sitemap
Check to see if the sitemap file is already present. Lets assume we wish to create sitemap in the URL: http://www.yourstore.com/sitemap/sitemap.xml
To do it successfully,
  1. FTP to the server
  2. create sitemap folder
  3. chmod the folder to 777
On some servers, previous steps will not be required, but it is better to create the file first so that Magento can edit it.
Let’s go to Magento administration now and click on “Add Sitemap” button. Just insert the default values.
After this step, we just told Magento where to create sitemap file. It is not yet created.

2. Configure Sitemap

Sitemap can be configured from the interface System -> Configuration -> Catalog->Google Sitemap. If you are not sure what does it all mean, check XML Tag definitions section from “Sitemaps XML format” document.

3. Create Sitemap Manually

Looks like Magento folks were thinking that sitemap should only be created by a cron job. Yes, it can be done that way also. Be sure to read Wiki article How to Set Up a Cron Job to get familiar with it. If you are looking for manual creation, quit your search for “Create Sitemap” button. You will not find it. But there is a workaround. You can enter manual URL to execute sitemap creation:
http://www.yourstore.com/index.php/admin/sitemap/generate/sitemap_id/[ID of Sitemap from step 1]
Of course, replace the content with square brackets with actual Sitemap ID.

January 2, 2010

Programmaticaly adding new customers to the Magento store

Every now and then you will have specific case in Magento store where you might need to programmaticaly add new customers. Adding customer with basic information like First name, Last name, email and password is relatively trivial task. Here is the sample (working code):
<?php
$websiteId = Mage::app()->getWebsite()->getId();
$store = Mage::app()->getStore();
 
//$customer = new Mage_Customer_Model_Customer();
$customer = Mage::getModel("customer/customer");
$customer->website_id = $websiteId; 
$customer->setStore($store);
 
$customer->firstname = "Branko";
$customer->lastname = "Ajzele";
$customer->email = "ajzele@someserver.com";
$customer->password_hash = md5("mycoolpass");
$customer->save();
?>
Here are some screenshots of the final result:
customer1
customer2
customer3
Ok, so now we now how to add new customer from our code. But this is bare minimum. Where are the addresses you say? Well, below is the code that fulfills the above one and ads an address information to the customer.
<?php 
 
$websiteId = Mage::app()->getWebsite()->getId();
$store = Mage::app()->getStore();
 
//$customer = new Mage_Customer_Model_Customer();
$customer = Mage::getModel("customer/customer");
$customer->website_id = $websiteId; 
$customer->setStore($store);
 
$customer->firstname = "Branko";
$customer->lastname = "Ajzele";
$customer->email = "ajzele@someserver.com";
$customer->password_hash = md5("mycoolpass");
$customer->save();
 
//$address = new Mage_Customer_Model_Address();
$address = Mage::getModel("customer/address");
$address->setCustomerId($customer->getId());
$address->firstname = $customer->firstname;
$address->lastname = $customer->lastname;
$address->country_id = "HR"; //Country code here
$address->postcode = "31000";
$address->city = "Osijek";
/* NOTE: If country is USA, please set up $address->region also */
$address->telephone = "0038531444888";
$address->fax = "0038531555999";
$address->company = "ActiveCodeline";
$address->street = "My Cool Street";
 
$address->save();
 
?>
And below is the screenshot that reflex the state after executing code above.
customer6
As you can see, adding a new customer from within a code is pretty straightforward process. The thing you should keep an eye on are the required fields. Useful way achieving a proper result is to try to add the customer from within Magento admin interface with all the required address fields then do a little “reverse engineering” by loading and dumping the loaded instance of Mage_Customer_Model_Customer and Mage_Customer_Model_Address objects. Examining the dumped ($object->debug()) structure would give you a pretty good idea of what needs to be provided to object when it is created programmaticaly.
Hope I don’t have to mention that all of this “playing” should first be done on developer machine, never on live site.
Hope this was helpful. Cheers.