Friday, 12 September 2014

Update handle on a certain condition programatically

Follow below steps in order to update a handle on a certain event-

1. Create a observer on a events

In order to add handle to Magento’s layout update object before it’s too late, we have to observe controller_action_layout_load_before event.

<config>
    <frontend>
        <events>
            <controller_action_layout_load_before>
                <observers>
                    <observer_unique_name>
                        <class><Parckagename>_<Modulename>_Model_Observer</class>
                        <method>controllerActionLayoutLoadBefore</method>
                    </observer_unique_name>
                </observers>
            </controller_action_layout_load_before>
        </events>
    </frontend>

</config>

2. Create Observer


<?php
    class <Parckagename>_<Modulename>_Model_Observer
    {
        public function controllerActionLayoutLoadBefore(Varien_Event_Observer $observer)
        {
            /** @var $layout Mage_Core_Model_Layout */
            $layout = $observer->getEvent()->getLayout();
            $id = Mage::app()->getRequest()->getParam(‘id’);
            /* or */
            if(<write any condition> is true)
            {
                $layout->getUpdate()->addHandle(‘OUR_COOL_OBJECT_’.$id);
            }
            
        }
    }
That’s it!

Debug Translation in magento

When you are dealing with multiple translations then some times you want to know the location, from where this translation is coming, so there are steps to debug it:-

1. Go to  app/code/core/Mage/Core/Model/Translate.php

2. Find function translate()

and then write the below code before "return $result":-

$logModule = str_pad($module, 25, "-", STR_PAD_RIGHT);
$logInString = str_pad($text, 150, "-", STR_PAD_RIGHT);
$logOutString = str_pad($result, 200, " ", STR_PAD_RIGHT);
Mage::log($logModule . '>' . $logInString . '>' . $logOutString, null, 'translate.log');

Now check translate.log file under /var/log.

After debugging rollback the whole code in core file "Translate.php"

Sunday, 24 February 2013

Add fields in newsletter in magento

1- Create app/code/local/[package-name]/[module-name]/sql/mysql4-install-0.1.0.php and now the following code:-


$installer = $this;

$installer->startSetup();

$installer->run("
 ALTER TABLE {$installer->getTable('newsletter_subscriber')}
 ADD (`lastname` TEXT NULL,
 `firstname` TEXT NULL)
 ");

$installer->endSetup();

2- Create app/code/local/[package-name]/[module-name]/controllers/[controller-name].php(like:- IndexController.php)

Code to add first name and last name -



require_once 'Mage/Newsletter/controllers/SubscriberController.php';
class Packagename_Modulename_IndexController extends Mage_Newsletter_SubscriberController
{
    /**
      * New subscription action
      */
    public function newAction()
    {.
     .
     .
     .
                 $status = Mage::getModel('newsletter/subscriber')->subscribe($email);

/*custom fields*/
if ($this->getRequest()->getPost('firstname') || $this->getRequest()->getPost('lastname'))
                {
                     $subscriber = Mage::getModel('newsletter/subscriber')->loadByEmail($email);
                     $firstname     = (string) $this->getRequest()->getPost('firstname');
    $lastname     = (string) $this->getRequest()->getPost('lastname');
                     $subscriber->setFirstname($firstname)->setLastname($lastname);
                     $subscriber->save();
                }
/*custom fields*/
         .
         .
    }


3- Code to see the information on Admin-

    Go to this link : app\code\core\Mage\Adminhtml\Block\Newsletter\Subscriber\grid.php

    Add this code :

    $this->addColumn('subscriber_firstname', array(
            'header'    => Mage::helper('newsletter')->__('Subscriber First Name'),
            'index'     => 'subscriber_firstname',
            'default'   =>    '----'
        ));

and you are done...

Set default option on configurable products in magento


Open app\design\frontend\[your package]\[your theme]\template\catalog\product\view\type\options\configurable.phtml

Now add the below java-script code after :-
var spConfig = new Product.Config(<?php echo $this->getJsonConfig() ?>);


function fireEvent(element,event){
if (document.createEventObject){
// dispatch for IE
var evt = document.createEventObject();
return element.fireEvent('on'+event,evt)
}
else{
// dispatch for firefox + others
var evt = document.createEvent("HTMLEvents");
evt.initEvent(event, true, true ); // event type,bubbling,cancelable
return !element.dispatchEvent(evt);
}
}
Event.observe(window, 'load', function() {
spConfig.settings[0].selectedIndex = 1;
obj = spConfig.settings[0]; // this grabs the first select item
Event.observe(obj,'change',function(){});
fireEvent(obj,'change'); // this simulates selecting the first option, which triggers
spConfig.settings[1].selectedIndex = 1; // this selects the first option of the second attribute drop menu
});

Saturday, 26 January 2013

Programmatically add attributes's option in magento



$arg_attribute = '<attribute-code>';
$attr_model = Mage::getModel('catalog/resource_eav_attribute');
$attr = $attr_model->loadByCode('catalog_product', $arg_attribute);
$attr_id = $attr->getAttributeId();
$opt['attribute_id'] = $attr_id;
$opt['value']['<admin-value>'][0] = '<admin-name>'; //admin name of option
$opt['value']['<admin-value>']][1] = '<admin-name>'; //default store name of option

$setup = new Mage_Eav_Model_Entity_Setup('core_setup');
$setup->addAttributeOption($opt);

Programmatically create a category within another category in magento


//$parentId is the category id of a category under which you want to want add new category.


$category = Mage::getModel('catalog/category');
$category->setName('name of new category')
->setIsActive(1)                       //activate your category
->setDisplayMode('PRODUCTS')
->setIsAnchor(1)
->setCustomDesignApply(1)
->setAttributeSetId($category->getDefaultAttributeSetId());

$parentCategory = Mage::getModel('catalog/category')->load($parentId);
$category->setPath($parentCategory->getPath());

$category->save();
unset($category);


That's all.. Enjoy.. :)

Sunday, 4 November 2012

Import Configurable products with their associated products

There are few steps involved: 

1- Create the attributes that will be configurable by the user.
    or our example, we’ll call it “shoe_size

2- Then go to System->Advanced Profiles and create a new profile.Then copy the below code in "Actions XML" field:-

<action type="dataflow/convert_adapter_io" method="load">
    <var name="type">file</var>
    <var name="path">var/import</var>
    <var name="filename"><![CDATA[Product_Amber.csv]]></var>
    <var name="format"><![CDATA[csv]]></var>
</action>

<action type="dataflow/convert_parser_csv" method="parse">
    <var name="delimiter"><![CDATA[,]]></var>
    <var name="enclose"><![CDATA["]]></var>
    <var name="fieldnames">true</var>
    <var name="store"><![CDATA[0]]></var>
    <var name="number_of_records">1</var>
    <var name="decimal_separator"><![CDATA[.]]></var>
    <var name="adapter">catalog/convert_adapter_productwithlinks</var>
    <var name="method">parse</var>
</action>

Save this profile with any Profile Name.Like "ImportConfigurableProduct"

3- Then go to app/code/core/Mage/Catalog/Model/Convert/Adapter
     Create a new file "Productwithlinks.php " and write the below code in this file:-

<?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)
 */


class Mage_Catalog_Model_Convert_Adapter_Productwithlinks
    extends Mage_Catalog_Model_Convert_Adapter_Product
{

    /**
     * Save product (import)
     *
     * @param array $importData
     * @throws Mage_Core_Exception
     * @return bool
     */
    public function saveRow(array $importData)
    {
        $product = $this->getProductModel();
        $product->setData(array());
        if ($stockItem = $product->getStockItem()) {
            $stockItem->setData(array());
        }

        if (empty($importData['store'])) {
            if (!is_null($this->getBatchParams('store'))) {
                $store = $this->getStoreById($this->getBatchParams('store'));
            } else {
                $message = Mage::helper('catalog')->__('Skip import row, required field "%s" not defined', 'store');
                Mage::throwException($message);
            }
        } else {
            $store = $this->getStoreByCode($importData['store']);
        }

        if ($store === false) {
            $message = Mage::helper('catalog')->__('Skip import row, store "%s" field not exists', $importData['store']);
            Mage::throwException($message);
        }
        if (empty($importData['sku'])) {
            $message = Mage::helper('catalog')->__('Skip import row, required field "%s" not defined', 'sku');
            Mage::throwException($message);
        }
        $product->setStoreId($store->getId());
        $productId = $product->getIdBySku($importData['sku']);
$new = true; // fix for duplicating attributes error
        if ($productId) {
            $product->load($productId);
$new = false; // fix for duplicating attributes error
        }
        $productTypes = $this->getProductTypes();
        $productAttributeSets = $this->getProductAttributeSets();

        /**
        * Check product define type
        */
        if (empty($importData['type']) || !isset($productTypes[strtolower($importData['type'])])) {
            $value = isset($importData['type']) ? $importData['type'] : '';
            $message = Mage::helper('catalog')->__('Skip import row, is not valid value "%s" for field "%s"', $value, 'type');
            Mage::throwException($message);
        }
        $product->setTypeId($productTypes[strtolower($importData['type'])]);
        /**
        * Check product define attribute set
        */
        if (empty($importData['attribute_set']) || !isset($productAttributeSets[$importData['attribute_set']])) {
            $value = isset($importData['attribute_set']) ? $importData['attribute_set'] : '';
            $message = Mage::helper('catalog')->__('Skip import row, is not valid value "%s" for field "%s"', $value, 'attribute_set');
            Mage::throwException($message);
        }
        $product->setAttributeSetId($productAttributeSets[$importData['attribute_set']]);

        foreach ($this->_requiredFields as $field) {
            $attribute = $this->getAttribute($field);
            if (!isset($importData[$field]) && $attribute && $attribute->getIsRequired()) {
                $message = Mage::helper('catalog')->__('Skip import row, required field "%s" for new products not defined', $field);
                Mage::throwException($message);
            }
        }

//================================================
// this part handles configurable products and links 
//================================================
if ($importData['type'] == 'configurable') {
$product->setCanSaveConfigurableAttributes(true);
$configAttributeCodes = $this->userCSVDataAsArray($importData['config_attributes']);
$usingAttributeIds = array();
foreach($configAttributeCodes as $attributeCode) {
$attribute = $product->getResource()->getAttribute($attributeCode);
if ($product->getTypeInstance()->canUseAttribute($attribute)) {
if ($new) { // fix for duplicating attributes error
$usingAttributeIds[] = $attribute->getAttributeId();
}
}
}
if (!empty($usingAttributeIds)) {
$product->getTypeInstance()->setUsedProductAttributeIds($usingAttributeIds);
$product->setConfigurableAttributesData($product->getTypeInstance()->getConfigurableAttributesAsArray());
$product->setCanSaveConfigurableAttributes(true);
$product->setCanSaveCustomOptions(true);
}
if (isset($importData['associated'])) {
$product->setConfigurableProductsData($this->skusToIds($importData['associated'], $product));
}
}

        /**
         * Init product links data (related, upsell, crosssell, grouped)
         */
if (isset($importData['related'])) {
$linkIds = $this->skusToIds($importData['related'], $product);
if (!empty($linkIds)) {
$product->setRelatedLinkData($linkIds);
}
}
if (isset($importData['upsell'])) {
$linkIds = $this->skusToIds($importData['upsell'], $product);
if (!empty($linkIds)) {
$product->setUpSellLinkData($linkIds);
}
}
if (isset($importData['crosssell'])) {
$linkIds = $this->skusToIds($importData['crosssell'], $product);
if (!empty($linkIds)) {
$product->setCrossSellLinkData($linkIds);
}
}
if (isset($importData['grouped'])) {
$linkIds = $this->skusToIds($importData['grouped'], $product);
if (!empty($linkIds)) {
$product->setGroupedLinkData($linkIds);
}
}
//================================================





        if (isset($importData['category_ids'])) {
            $product->setCategoryIds($importData['category_ids']);
        }

        foreach ($this->_ignoreFields as $field) {
            if (isset($importData[$field])) {
                unset($importData[$field]);
            }
        }

        if ($store->getId() != 0) {
            $websiteIds = $product->getWebsiteIds();
            if (!is_array($websiteIds)) {
                $websiteIds = array();
            }
            if (!in_array($store->getWebsiteId(), $websiteIds)) {
                $websiteIds[] = $store->getWebsiteId();
            }
            $product->setWebsiteIds($websiteIds);
        }

        if (isset($importData['websites'])) {
            $websiteIds = $product->getWebsiteIds();
            if (!is_array($websiteIds)) {
                $websiteIds = array();
            }
            $websiteCodes = split(',', $importData['websites']);
            foreach ($websiteCodes as $websiteCode) {
                try {
                    $website = Mage::app()->getWebsite(trim($websiteCode));
                    if (!in_array($website->getId(), $websiteIds)) {
                        $websiteIds[] = $website->getId();
                    }
                }
                catch (Exception $e) {}
            }
            $product->setWebsiteIds($websiteIds);
            unset($websiteIds);
        }

        foreach ($importData as $field => $value) {
            if (in_array($field, $this->_inventorySimpleFields)) {
                continue;
            }
            if (in_array($field, $this->_imageFields)) {
                continue;
            }

            $attribute = $this->getAttribute($field);
            if (!$attribute) {
                continue;
            }

            $isArray = false;
            $setValue = $value;

            if ($attribute->getFrontendInput() == 'multiselect') {
                $value = split(self::MULTI_DELIMITER, $value);
                $isArray = true;
                $setValue = array();
            }

            if ($value && $attribute->getBackendType() == 'decimal') {
                $setValue = $this->getNumber($value);
            }

            if ($attribute->usesSource()) {
                $options = $attribute->getSource()->getAllOptions(false);

                if ($isArray) {
                    foreach ($options as $item) {
                        if (in_array($item['label'], $value)) {
                            $setValue[] = $item['value'];
                        }
                    }
                }
                else {
                    $setValue = null;
                    foreach ($options as $item) {
                        if ($item['label'] == $value) {
                            $setValue = $item['value'];
                        }
                    }
                }
            }

            $product->setData($field, $setValue);
        }

        if (!$product->getVisibility()) {
            $product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE);
        }

        $stockData = array();
        $inventoryFields = $product->getTypeId() == 'simple' ? $this->_inventorySimpleFields : $this->_inventoryOtherFields;
        foreach ($inventoryFields as $field) {
            if (isset($importData[$field])) {
                if (in_array($field, $this->_toNumber)) {
                    $stockData[$field] = $this->getNumber($importData[$field]);
                }
                else {
                    $stockData[$field] = $importData[$field];
                }
            }
        }
        $product->setStockData($stockData);

        $imageData = array();
        foreach ($this->_imageFields as $field) {
            if (!empty($importData[$field]) && $importData[$field] != 'no_selection') {
                if (!isset($imageData[$importData[$field]])) {
                    $imageData[$importData[$field]] = array();
                }
                $imageData[$importData[$field]][] = $field;
            }
        }

        foreach ($imageData as $file => $fields) {
            try {
                $product->addImageToMediaGallery(Mage::getBaseDir('media') . DS . 'import' . $file, $fields);
            }
            catch (Exception $e) {}
        }

        $product->setIsMassupdate(true);
        $product->setExcludeUrlRewrite(true);

        $product->save();

        return true;
    }



    
    protected function userCSVDataAsArray($data) {
return explode(',', str_replace(" ", "", $data));
}

protected function skusToIds($userData,$product) {
$productIds = array();
foreach ($this->userCSVDataAsArray($userData) as $oneSku) {
if (($a_sku = (int)$product->getIdBySku($oneSku)) > 0) {
parse_str("position=", $productIds[$a_sku]);
}
}
return $productIds;
}

    
}

4- Create a csv  "Product_Amber.csv" with fields:-
websites,type,attribute_set,tax_class_id,weight,name,shoe_size,sku,price,description,short_description,category_ids,has_options,visibility,required_options,is_in_stock,qty,status,associated,config_attributes


5- Go to "var" folder and create a new folder with name "import" .Then copy and paste  "Product_Amber.csv"  in this folder.

6- Then open the new advance profile "ImportConfigurableProduct"

Go to "Run Profile" tab and the click on the button "Run Profile In Popup" 

Now you can check your configurable products import successfully with their associated products but not visible on front-end ,because the quantity of configurable and associated products is not set.


7- Create a new csv file with any name like "importDetails.csv" with fields:-

sku,qty,is_in_stock,_type


8- Then go to System->Profiles->Click on "Import All Products":-
  1. Select "Upload file" tab->Browse "importDetails.csv" and then click "Save and Continue Editing".
  2. Select "Run Profile" tab,select last uploaded file and the click on the button "Run Profile In Popup" 
Now you can see your newly added configurable product on front-end under a category.In our example Category id is 7.

That's all.
Enjoy.. :)