rss
twitter
    Find out what I'm doing, Follow Me :)

Wednesday, May 12, 2010

Quick script to batch create Magento categories

A site we administer with a reasonable amount of SKUs (far in excess of 100,000), needed some quick category manipulation for a series of new data to be dropped in. The new information had a desired category tree that had to be built up quick, but with over 600 categories to be created, human effort wouldn’t be suitable.

So, using the Magento category ID export script to help manipulate the CSV – we were able to quickly make a script to batch create our categories.

First off, create your CSV with 2 columns, the parent ID for the category and the category name – you could easily add more columns for extra options, but it wasn’t necessary for us.

The CSV file should be something like this:

3,subcat
4,subcat2
6,subcat3

Then it should be saved in ./var/import/importCats.csv

Then save the following in ./quickCatCreate.php

<?php
 
    define('MAGENTO', realpath(dirname(__FILE__)));
    require_once MAGENTO . '/app/Mage.php';
 
    umask(0);
    Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
        $count = 0;
 
    $file = fopen('./var/import/importCats.csv', 'r');
    while (($line = fgetcsv($file)) !== FALSE) { $count++;
      //$line is an array of the csv elements
 
      if (!empty($line[0]) && !empty($line[1])) {
 
          $data['general']['path'] = $line[0];
          $data['general']['name'] = $line[1];
          $data['general']['meta_title'] = "";
          $data['general']['meta_description'] = "";
          $data['general']['is_active'] = "";
          $data['general']['url_key'] = "";
          $data['general']['display_mode'] = "PRODUCTS";
          $data['general']['is_anchor'] = 0;
 
          $data['category']['parent'] = $line[0]; // 3 top level
          $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;
                      }
                  }
                  $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->save();
                  echo "Suceeded <br /> ";
              }
              catch (Exception $e){
                      echo "Failed <br />";
 
              }
          }     
 
  }

Then it is just a matter of visiting the link in your browser to create the categories – customise to your hearts content, any further expansion should be very easy (such as product association etc.)

Uh oh – I’m getting errors after the first record!

Fatal error: Call to a member function getPath() on a non-object in app\code\core\Mage\Catalog\Model\Resource\Eav\Mysql4\Category.php on line 385

There is a small NB though, there is a bug with Magento’s original code that will cause a problem with the above script, a quick fix is outlined here. It is just a matter of commenting out 2 lines to force the variable to be re-set.

In ./app/code/core/Mage/Catalog/Model/Resource/Eav/Mysql4/Category.php line #110

protected function _getTree()
    {
        //if (!$this->_tree) {
            $this->_tree = Mage::getResourceModel('catalog/category_tree')
                ->load();
        //}
        return $this->_tree;
    }

Tuesday, May 11, 2010

Magento - Yahoo Analytics Conversion Code

Unlike other tracking codes, we need to put Yahoo Analytics Conversion code between <HEAD> and </HEAD> tags.

Yahoo’s Instructions for the following code are:

Copy the HTML code below and insert it between the <HEAD> and </HEAD> tags on your site’s conversion page(s). To pass a dynamic revenue value in the tag, you must modify your web pages accordingly.

To add the Yahoo conversion tracking code in the Head tags, we need to look at the checkout layout configuration file:
/app/design/frontend/your_interface/your_theme/layout/checkout.xml

Find out which page layout it uses when an order is completed.

i.e.) For one page checkout, look for this code:

<checkout_onepage_success>
<reference name="root">
<action method="setTemplate"><template>page/2columns-right.phtml</template></action>
</reference>

You can edit the Head section of ‘2columns-right.phtml’ to add the Yahoo tracking code. But if this template, 2columns-right.phtml is being used for other pages, I would make a copy of it and name it ‘2columns-right-success.phtml’ and add the tracking code there. This way, it will track it only when there is a successful conversion.

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php echo $this->getLang() ?>" lang="<?php echo $this->getLang() ?>">
<head>
<?php echo $this->getChildHtml('head') ?><SCRIPT language=”JavaScript” type=”text/javascript”>
<!– Yahoo! Inc.
window.ysm_customData = new Object();
window.ysm_customData.conversion = “transId=,currency=,amount=”;
var ysm_accountid = “—–YAHOO_ACCOUNT_ID—–”;
document.write(”<SCR” + “IPT language=’JavaScript’ type=’text/javascript’ ”
+ “SRC=//” + “srv2.wa.marketingsolutions.yahoo.com” + “/script/ScriptServlet” + “?aid=” + ysm_accountid
+ “></SCR” + “IPT>”);
// –>
</SCRIPT>

Tuesday, May 4, 2010

How to Import Products into Magento

There’s a little confusion among some on how to import products into a Magento ecommerce store. I spent some time today researching and trying to find the best method on doing this. The reason for my research is because there was no simple documentation anywhere that I could find on how to import products. Magento actually has built a pretty robust import/export mechanism into the ecommerce cms that has a ton of flexibility to do many things. I’m not going to cover all of those. This is just for those of you who simply just want to import products into their Magento cart.

Step 1 – Add a new product manually
add a new product manually to the catalog, assign it to a category, and fill out all fields that will be necessary to your store. The obvious ones are price, description, quantity etc. It’s important that you fill out all fields that you know you are going to need for all the products you import.

Step 2 – Export Your Products
Now we want to export your product to a .csv file so that we can view the fields that are required to import. Go to System >> Import/Export >> Profiles. Now click on Export All Products then Run Profile. Click on the “Run Profile in Popup” button. Once the export is completed, go to your var/export directory on your Magento install and you will find the .csv file there for you to download.

Step 3 – Analyze The .CSV File
Now if you look at your .csv export file you will see the field names that you need to match up. Now just start filling yours in and creating your csv file ready for import. This step is extremely important. Otherwise Magento cannot match what you are trying to import and the importing will fail. At a most basic level, here are the fields that I imported:
    •    store
    •    attribute_set
    •    type
    •    sku
    •    category_ids
    •    status
    •    visibility
    •    tax_class_id
    •    weight
    •    price
    •    name
    •    description

Step 4 – Import Your New .CSV File
Now go to System >> Import/Export >> Profiles. Now click on Import All Products. Change “Type” under Data Format to CSV/Tab Seperated. Now click on Upload File, and browse for your .csv file and click “Save and Continue Editing”. Now go to “Run Profile” and select your file from the dropdown menu. Click the button underneath to run the import. And whalllah. All your products should now be imported.

Tuesday, April 27, 2010

Creating Block From the Code in Magento


Here are some methods of creating block by code in Magento. This type of code can be used directly in template, not need to create a layout file or add a child node inside already existing layout file. You can use this to echo a different type of block inside already loading block and template.

// Directly in the PHTML where you want to show the block
<?php
echo $this->getLayout()->createBlock("module/block")->setTemplate("module/page.phtml")->toHtml();
?>

What we have actually done is just load the layout and create an instance of a block class defined inside its paramerter, then assigned a template to the block and finally echoed as html. Simple! The code above will be equivalent to what we do as following in layout and in template file.
// In layout
<block type="module/block" name="module.name" template="module/page.html"/>
<?php
// In parent PHTML
$this->getChildHtml("module.name");
?>

Monday, April 26, 2010

How To install Magento In Wamp Server


Magento is an open-source ecommerce web application launched on March 31, 2008. It was created by Varien, building on components of the Zend Framework.
Magento is available under the Open Software License version 3.0. Since version 1.1.7 some parts are licensed under the Academic Free License version 3.0.

To Download Magento In Wamp, Follow below steps.

1. Download latest stable version of Magento from http://www.magentocommerce.com/download (Requires free registration), Unzip in www directory and Also create Mysql database and User from your phpmyadmin panel, which can be accessed by http://localhost/phpmyadmin.
2. Now start installing Magento by http://localhost/magento. If not accessible, please check the folder name of your folder.
3. Now Installation Wizard will be start, Step 2 is to enter your mysql details. It will take a while as it creates some tables.
4. Next Step will ask you about Admin login/Pass, So Create your admin/pass and save them.
Well, thats all. Go Open your store and Enjoy

Friday, April 16, 2010

Magento Commerce 1.4: How To Fix ‘Unable to submit your request. Please, try again later’ on the Contact Us form

If you’ve upgraded your Magento Commerce site to 1.4.x you may have run in to the problem where any attempt to send a response via your ‘Contact Us’ page fails with 
“Unable to submit your request.  Please try again later”.

Contact Us Form - Error: Unable to submit your request, please try again later



If you look at the code /app/code/core/Mage/Contacts/controllers/IndexController.php

public function postAction()
    {
        $post = $this->getRequest()->getPost();
        if ( $post ) {
            $translate = Mage::getSingleton('core/translate');
            /* @var $translate Mage_Core_Model_Translate */
            $translate->setTranslateInline(false);
            try {
                $postObject = new Varien_Object();
                $postObject->setData($post);

                $error = false;

                if (!Zend_Validate::is(trim($post['name']) , 'NotEmpty')) {
                    $error = true;
                }

                if (!Zend_Validate::is(trim($post['comment']) , 'NotEmpty')) {
                    $error = true;
                }
        
                if (!Zend_Validate::is(trim($post['email']), 'EmailAddress')) {
                    $error = true;
                }

                if (Zend_Validate::is(trim($post['hideit']), 'NotEmpty')) {
                    $error = true;
                }

                if ($error) {
                    throw new Exception();
                }

      (...snip...)

            } catch (Exception $e) {
                $translate->setTranslateInline(true);

                Mage::getSingleton('customer/session')->addError(Mage::helper('contacts')->__('Unable to submit your request. Please, try again later'));
                $this->_redirect('*/*/');
                return;
            }

The Contact Us form requires the Name, Comment, Email not be empty or NULL.  We do expect the “hideit” field to (a) exist and (b) be empty/NULL.  The “hideit” field is new in 1.4 and is designed to help prevent spam.  Automated bots would complete this field and this is how we can detect bots.  It’s best to implement a Captcha system as well on your Contact Us page to further improve your spam protection.

If any of the above checks fail, the function throws an exception and we get the “Unable to submit your request. Please, try again later” message.  The message would be more descriptive if it read “Unable to submit your request, please verify all required fields have been completed”.  You can change the message in the locale translation file if you want.  This will also future proof you against updates.

The best thing to do is examine the code on your site.  Those site’s I’ve looked at have the following:

<div class="button-set">
        <p class="required">* Required Fields</p>
        <button type="submit" class="form-button"><span>Submit</span></button>
    </div>

The correct code should be:

<div class="buttons-set">
        <p class="required">* Required Fields</p>
        <input type="text" style="display: none ! important;" value="" id="hideit" name="hideit">
        <button class="button" title="Submit" type="submit"><span><span>Submit</span></span></button>
    </div>

Either something went wrong with the upgrade and the underlying files didn’t get upgraded, or you’re overriding the files within your theme directory.

The Contact Us form is generated by /app/design/frontend/base/default/template/contacts/form.phtml.  The code from a working 1.4.0.1 environment looks like this:

<div class="buttons-set">
        <p class="required"><?php echo Mage::helper('contacts')->__('* Required Fields') ?></p>
        <input type="text" name="hideit" id="hideit" value="" style="display:none !important;" />
        <button type="submit" title="<?php echo Mage::helper('contacts')->__('Submit') ?>" class="button"><span><span><?php echo Mage::helper('contacts')->__('Submit') ?></span></span></button>
    </div>

Remember to backup any files you edit, before editing

You can choose either to edit the file directly or better yet, replace it with the correct 1.4.0.1 file.

Thursday, April 15, 2010

Upgrading To Magento 1.4

With the recent release of Magento version 1.4, many people are having trouble upgrading their current Magento installation, or installing their template on a fresh Magento 1.4 installation. A quick search online and you’ll find countless entries and posts stating that Magento 1.4 is buggy, not working, horrible, etc. Particularly when you browse through the Magento forums.

In fact Magento 1.4 is different than the last previous stable version (1.3.2.4) but you should definitely be able to upgrade your installation, or install your custom template on a Magento 1.4 installation! Here are the most common issues and how to fix them!

Magento modern theme 1.4

This relates to the following issues:

    * Can’t install Modern Theme through Magento Connect
          o Get error “magento-core/Interface_Frontend_Default_Modern requires package “magento-core/Mage_Core_Modules” (version >= 1.3.2.2, version <= 1.3.3, excluded versions: 1.3.3), installed version is 1.4.0.0
            Install Errors
            No valid packages found
            PEAR ERROR: install failed
    * Can’t upgrade Modern Theme through Magento Connect
          o Get similar error as above
    * etc

As of now, there is no good way to install or upgrade the Modern Theme via Magento Connect. BUT you should definitely be able to get it by installing a fresh Magento 1.4 installation.

Magento 1.4 comes by default with the default theme, the modern theme, and the iphone optimized theme. However, you’d have to install Magento manually and NOT use the downloader (as this will include the default theme only). Here is one way to install Magento 1.4 manually:

   1. Download all the files on your computer and upload them on your server
   2. Create a database and a database user and grant that user all permissions to the database. Make sure to write down your database name, database user name, and database user password.
   3. Go to the URL that points to your server and follow the instructions to complete Magento installation

Can’t access admin, blank page, products won’t load, error, etc

Most issues will be resolved once you reindex Magento data and refresh all Magento cache. To reindex Magento data follow these quick steps:

   1. Go to System>Index Management
   2. Click on “select all” in the upper left corner
   3. Under “Action” select “Reindex Data” and click submit

To refresh all Magento cache following these quick steps:

   1. Go to System>Configuration and
   2. Click on “select all” in the upper left corner
   3. Under “action” click on “refresh” and click submit
   4. Then click on these buttons:
         1. Flush Magento Cache
         2. Flush Cache Storage
         3. Fluch Catalog Images Cache
         4. Flush JavaScript/CSS Cache

Upgrading your existing theme (modern or else)

Obviously I cannot cover here all the possible problems and issues that may arise when upgrading your particular template to be compatible with Magento 1.4. However, I found that the most common issue is “Categories not working after upgrading to 1.4″. This relates to the error people get when clicking on some categories: “Error processing your request” followed by a number.

To fix that, you’ll need to do 2 things:

1. First, edit your toolbar.phtml file located under app/design/frontend/default/yourthemename/template/catalog/product/list. Take the updated toolbar.phtml from the new 1.4 default theme (located under app/design/frontend/base/default/template/catalog/product/list) and use it in your theme. Then edit that file to apply any styling you had in your original toolbar.phtml file. Another way of doing it is editing your toolbar.phml file to use the right class names and code (you can compare with the default one and take it from there).

2. Second, open catalog.xml located under app/design/frontend/default/yourthemename/layout/ and find this line:

<block type=”catalog/product_list_toolbar” name=”product_list_toolbar” template=”catalog/product/list/toolbar.phtml”>

And underneath insert this code:

<block type=”page/html_pager” name=”product_list_toolbar_pager”/>

And that should do it!