Archive

Archive for the ‘Magento’ Category

Workaround for attribute store labels not being displayed in Magento

February 12th, 2012

Here’s a quick workaround for a rather strange issue – sometimes, calling $attribute->getStoreLabel() returns null, although everything looks fine in the admin and in the database. It might be something that is slipping my mind, or it might be a bug, not really sure. However, I had to deal with it and come up with a fix, so I’d thought I’d share.

$_aIds = array();
foreach( $prod->getAttributes() as $attribute ) {
	//need the attribute_id which is missing from the attribute object
	if( !isset($_aIds[$attribute->getAttributeCode()]) ) {
		$_aIds[$attribute->getAttributeCode()] = $attribute->getIdByCode('catalog_product', $attribute->getAttributeCode());
	}

	//if there's not store_label try to set it
	if( !$attribute->getStoreLabel() ) {
		$labels = $attribute->getResource()->getStoreLabelsByAttributeId( $_aIds[$attribute->getAttributeCode()] );
		if( array_key_exists(Mage::app()->getStore()->getStoreId(), $labels)) {
			$attribute->setStoreLabel( $labels[Mage::app()->getStore()->getStoreId()] );
		}
		else {
			$attribute->setStoreLabel( $attribute->getFrontendLabel() );
		}
	}
}
// end workaround

Applies to Magento 1.5.x

Magento ,

Patching the Magento USPS module

January 20th, 2011

Since their last update on Jan 3rd, 2011 USPS has stopped working on all of my Magento distro’s. The reason for that is a change in USPS’ response XML values. Magento has its part of blame here, first for not patching it immediately (which again shows how much they care about the CE users) and second for not coding it properly in the first place – they’re using the method name (i.e. Express Mail) to see if that method is allowed from the admin, instead of using the CLASSID attribute.

This issue has been reported on magentocommerce.com bug tracking system and it’s also discussed in the forum. USPS makes it clear that they’ll discontinue all API versions prior RateV4 ad IntlRateV2:
“All Rate Calculator API integrators are encouraged to migrate to the latest API versions (RateV4, IntlRateV2):
RateV4 and IntlRateV2 will be the only Rate Calculator API versions to offer the full range of new products and functionality
Rate, RateV2, RateV3 and IntlRate will be retired in May 2011, requiring all integrators to migrate to the latest versions”

As explained on the forums, the fix is quite simple, as USPS only added the <sup>®</sup> which is the encoded (twice :) ) version of the registered sign in a sup tag. Magento values are defined without those so when the code tries to match them it fails. All you have to do is clean that string and you’re good to go. I don’t like to modify core files so the fix involves copying app/code/core/Mage/Usa/Model/Shipping/Carrier/Usps.php to app/code/local/Mage/Usa/Model/Shipping/Carrier/ and working on the local version of Usps.php. Strip the special chars:

$mailService = str_replace('®', '', strip_tags(htmlspecialchars_decode(htmlspecialchars_decode((string)$postage->MailService))));

and

$svcDescription = str_replace('®', '', strip_tags(htmlspecialchars_decode(htmlspecialchars_decode((string)$service->SvcDescription))));

 

Here’s the archive with the patch. Just download it and unzip it in the root of your Magento distribution. Download USPS patch for Magento 1.4.2.0 (8.59 kB)

 

Note: This patch applies to Magento CE 1.4.2.0. For all other versions you will have to do it manually as explained above.

 

Magento, PHP , ,

Anatomy of a Magento extension

January 5th, 2011

Magento Commerce has been on the OSS “market” for a while now and I see more and more developers, designers and of course store owners migrating their ecommerce sites to Magento or installing it for their new stores. I’ve been coding on Magento since its beta 0.6 version, actually my first integration was based on this beta. I’ve been advised not to use the beta and they were right. However, I had my reasons for recommending it, using it and somehow advocating for that fresh, promising open source piece of software. In the meanwhile, it turned out I was right – it’s one of the most complete, scalable & feature-rich free ecommerce solution. Not the easiest to integrate or use, not the smoothest or lightweight, but it’s come a long way and it still have room for improvements.

One of the things I liked from the start (as a developer) was the ability to extend it in a very simple and loosely coupled way (unlike other solutions). Adding the OOP and design patterns made it perfect for my way of thinking. And I think this is the way to go for any major application, even if it might seem cluttered or with a steep learning curve at a first glance. I remember one of the first problems I faced was module creation – I was adding all my code in the core/Mage folder, I was overwriting a lot of the core code although I knew it was bad and so on. However, once I understood how to create a module, things became clearer and much simpler. So here’s a beginner’s guide to creating a new module. Although it’s meant for beginners, you should know the basic folder layout (skins, library, js, apps).

All Magento code resides in app/code and the lib folder. If you check app/code you’ll notice three subfolders: community, core, local. You should be adding your stuff in local or community (usually only when it is a community contribution). So let’s create our first module. I’ll use the namespace mandagreen and the module will be called HelloWorld. For this I need to create the following folders under app/code/local:
Mandagreen/HelloWorld

To keep things simple, in this example we’ll be creating one Block, one Helper and one Model – no controllers & no Resource Models. Here’s where each of these will reside:
blocks – app/code/local/Mandagreen/HelloWorld/Block
helpers – app/code/local/Mandagreen/HelloWorld/Helper
models – app/code/local/Mandagreen/HelloWorld/Model

Create these three folders and then also create a new etc folder. The structure will then look like this:

    app/code/local/Mandagreen/HelloWorld/Block
    app/code/local/Mandagreen/HelloWorld/etc
    app/code/local/Mandagreen/HelloWorld/Helper
    app/code/local/Mandagreen/HelloWorld/Model

The etc folder holds configuration information – in this case we’ll focus only on the module configuration file, which is config.xml. Let’s create it and start adding some xml into it:

<?xml version="1.0"?>
<config>
	<modules>
		<Mandagreen_HelloWorld>
			<version>0.0.1</version>
		</Mandagreen_HelloWorld>
	</modules>

	<global>
		<models>
			<helloworld>
				<class>Mandagreen_HelloWorld_Model</class>
			</helloworld>
		</models>

		<blocks>
			<helloworld>
				<class>Mandagreen_HelloWorld_Block</class>
			</helloworld>
		</blocks>

		<helpers>
			<helloworld>
				<class>Mandagreen_HelloWorld_Helper</class>
			</helloworld>
		</helpers>
	</global>

	<frontend>
		<layout>
			<updates>
				<helloworld>
					<file>mg_helloworld.xml</file>
				</helloworld>
			</updates>
		</layout>

		<translate>
			<modules>
				<Mandagreen_HelloWorld>
					<files>
						<default>Mandagreen_HelloWorld.csv</default>
					</files>
				</Mandagreen_HelloWorld>
			</modules>
		</translate>
	</frontend>
</config>

That’s a lot, isn’t it? :) No worries, I’ll explain. Under the main node (config), youll usually need the global node. The modules node is being used to hold mode info about the current module, maybe dependencies and so on. The frontend node is usually used for defining layout handlers and translation files, but they can do more than that. In this example, we’re gonna have our own layout file called mg_helloworld.xml – you can use any name on it (as long as it’s unique), but I prefer to namespace it as well. Also, I’ve defined a translation file Mandagreen_HelloWorld.csv which needs to be created in app/locale/en_US (or whatever your default locale is).

The global node defines all the classes you’ll be using, in this case helpers, models and blocks. You can see that they are defined the same way, but in different locations: <helpers />, <models /> and <blocks />. Let’s use the helpers node as an example.

		<helpers>
			<helloworld>
				<class>Mandagreen_HelloWorld_Helper</class>
			</helloworld>
		</helpers>

The helloworld node defines a handle and you should be careful to always use unique names. If you’re not sure if a certain name exist, namespace it (mghelloworld for example). This handle will be used to instantiate models, call helpers or use blocks using the Magento factory. For example, for models, you’ll be using Mage::getModel('helloworld/modelname'); instead of new Mandagreen_HelloWorld_Model_Modelname();. Same with helpers, inside a block template – $this->helper('helloworld')->someMethod();.
The other node, class is being used to define the namespace of the class name. In the example above, the name of the Modelname class has to being with Mandagreen_HelloWorld_Helper. A few examples might help:

  • Mandagreen_HelloWorld_Model_Salute, will be found in Mandagreen/HelloWorld/Model/Salute.php and can be accessed via Mage::getModel('helloworld/salute')
  • Mandagreen_HelloWorld_Model_Salute_Hi, will be found in Mandagreen/HelloWorld/Model/Salute/Hi.php and can be accessed via Mage::getModel('helloworld/salute_hi')
  • Mandagreen_HelloWorld_Helper_Help, will be found in Mandagreen/HelloWorld/Model/Help.php and can be accessed via Mage::helper('helloworld/help')

Now that we explained the config file, let’s move on to actually creating the classes and code. I’ll use the example above and create the following files:

Mandagreen/HelloWorld/Block/Standard.php

<?php

class Mandagreen_HelloWorld_Block_Standard extends Mage_Core_Block_Template {
    function getSomething() {
          return Mage::getModel('helloworld/salute')->getName();
    }
}

Mandagreen/HelloWorld/Helper/Help.php

<?php

class Mandagreen_HelloWorld_Helper_Help extends Mage_Core_Helper_Abstract {
    function shouldSayHi() {
          return true;
    }
}

Mandagreen/HelloWorld/Model/Salute.php

<?php

class Mandagreen_HelloWorld_Model_Salute extends Mage_Core_Model_Abstract { //or Varien_Object or none
    function getName() {
          //do some heavy logic here
          return 'John';
    }
}

One more file is required for the translations to work with this module – a “default” Data helper, defined in Mandagreen/HelloWorld/Helper/Data.php like this:

class Mandagreen_HelloWorld_Helper_Data extends Mage_Core_Helper_Abstract {}

We have the classes but we also need to use them in a template, so let’s create standard.phtml in app/design/frontend/default/default/template/helloworld (create all additional folders if needed). Also, create mg_helloworld.xml under app/design/frontend/default/default/layout.

For the template, things are very easy:

<div style="background: red; padding: 20px;">
	<?php if( $this->helper('helloworld/help')->shouldSayHi() ): ?>
	Hello <?php echo $this->getSomething(); ?>
	<?php else: ?>
	Can't say anything...
	<?php endif; ?>
</div>

while for the layout we’ll use this approach:

<?xml version="1.0"?>
<layout version="0.1.0">
    <default>
        <reference name="content">
            <block type="helloworld/standard" name="helloworld" template="helloworld/standard.phtml" after="-" />
        </reference>
    </default>
</layout>

This should display “Hello John” at the end of the content area on most of the pages, including the homepage. But wait, before you try that you’ll have to enable the module in app/etc/modules. Create a file called Mandagreen_HelloWorld.xml with the following code:

<?xml version="1.0"?>
<config>
    <modules>
        <Mandagreen_HelloWorld>
            <active>true</active>
            <codePool>local</codePool>
        </Mandagreen_HelloWorld>
    </modules>
</config>

Clear all magento cache and refresh the page – your first module, up and running! And here’s the archive for this tutorial – Download Hello World Magento Module (2.99 kB)

Further/recommended reads:

Magento, Uncategorized

Adding Customer Comments as Order Status Comments using Magento & OneStepCheckout

October 24th, 2010

A few days ago I got an email from someone asking me about adding the default customer comments in OneStepCheckout (www.onestepcheckout.com) as regular order comments. I thought I’d share this quick & simple hack with everyone, so here’s what you have to do:
Open app/code/local/Idev/OneStepCheckout/Helper/Data.php, and after

$observer->getEvent()->getOrder()->setOnestepcheckoutCustomercomment($orderComment);

add this line:
$observer->getEvent()->getOrder()->setState( Mage_Sales_Model_Order::STATE_NEW, true, $orderComment, false );

$observer->getEvent()->getOrder()->setState(
    $observer->getEvent()->getOrder()->getStatus(),
    true,
    $orderComment,
    false
);

This will add the comments on the regular comments/statuses thread, as well as a customer comment. If you want to disable customer comments, just comment the original code.

Actually, this approach should also work with the out-of-the-box Magento one step checkout. Add an input on the last step, create a listener for

checkout_type_onepage_save_order

and use the same piece of code:

$observer->getEvent()->getOrder()->setState( $observer->getEvent()->getOrder()->getStatus(), true, $this->_getRequest()->getPost('order_comments'), false );

Note: Tested on Magento 1.4.1.0 & 1.4.1.1

Magento ,

Introducing Magento CSS & JS Minifier

September 15th, 2010

As the title says, I’m glad to announce my first public Magento extension (not yet added in the Connect repository). During my 3 years experience with Magento, I’ve worked on a lot of custom extensions, improvements & fixes, but most of them were client-specific, plus they weren’t designed to have a backend interface (with a few exceptions). This one, however, is entirely configurable from the Admin and it’s both simple and effective.

 

What it does

This quick optimizer parses all javascript & css files included on a page and removes all unnecessary characters. The most simple step is to remove spaces, tabs and new lines – but there’s more than just that. Of course, for small files compression is insignificant, but when you work with almost 600KB and around 30 requests, you can save a lot. Here’s a quick math on one of my Magento installs:

Javascript – 26 requests, 479 KB
CSS – 4 requests, 102 KB

With Magento’s default merging enabled:
Javascript – 1 request, 360 KB (not sure why this is smaller then the 26 summed up, but nvm)
CSS – 1 request, 108.2 KB (same for this one too, but again, nvm)

We’ve already saved 28 requests, which means less overhead – quicker download times for user, less stress on the server.

With the Minifier enabled:
Javascript is 255 KB, which means almost 47% compression
CSS is 92 KB, which means almost 10% compression

 

Advantages

 

Disatvantages

  • Need to write javascripts very careful, adding a semicolon after almost everything
  • Have to rewrite of Mage_Core_Model file
  • Have to override two Magento methods
  • Additional processing time (insignificant in my opinion)

 

Credits

This plugin wouldn’t exist if it weren’t for these two outstanding PHP projects:
Joe Scylla’s CssMin
Ryan Grove’s JsMin
Big thanks to both of them.

 

Download & Install


First, Download Minifier for Magento (10.54 kB), then unzip it and copy the app/ folder to your Magento root folder.

Logout from the admin if you’re already logged in, then login. Go to Cache Management, click on the “Fulsh cache storage” button, then go to Configuration > Developer and enable all the options, as shown in the attached screenshot. Go back to Cache Management and this time click on the “Flush Javascript/CSS cache”.

Go to your store frontend and behold, you’re now using compressed js’s and css’s.

Works on Magento 1.4+

Magento , , ,

How to export customers from orders between certain dates in Magento

August 23rd, 2010

Last week a client who runs his store on Magento Commerce asked me how he could export a list of customers who purchased between certain dates in August. Of course, I first went to the Administration area and tried several approaches (order reports, customer reports, data export). Unfortunately nothing worked, so I had to write a script or a plain SQL and run it from the CLI. I preferred a straight query, rather than a script, and I tried not to use sub-selects. Here’s the adapted part, where I’ve added some variables to keep all the attribute id’s:

SET @etID := (SELECT entity_type_id FROM eav_entity_type WHERE entity_type_code = 'order_address');
SET @atFn := (SELECT attribute_id FROM eav_attribute WHERE attribute_code = 'firstname' AND entity_type_id = @etID);
SET @atLn := (SELECT attribute_id FROM eav_attribute WHERE attribute_code = 'lastname' AND entity_type_id = @etID);
SET @atEmail := (SELECT attribute_id FROM eav_attribute WHERE attribute_code = 'customer_email');

SET @startDate := '2010-08-06 00:00:00';
SET @endDate := '2010-08-13 23:59:59';

SELECT o.increment_id, e.value as email, ln.value as lastname, fn.value as firstname
FROM sales_order o
INNER JOIN sales_order_varchar e ON e.entity_id = o.entity_id AND attribute_id = @atEmail
INNER JOIN sales_order_entity lne ON lne.parent_id = o.entity_id AND lne.entity_type_id = @etID
INNER JOIN sales_order_entity_varchar ln ON ln.entity_id = lne.entity_id AND ln.attribute_id = @atLn
INNER JOIN sales_order_entity_varchar fn ON fn.entity_id = lne.entity_id AND fn.attribute_id = @atFn
WHERE o.created_at BETWEEN @startDate AND @endDate
GROUP BY o.increment_id
ORDER BY o.increment_id DESC;

The only problem is when the Shipping Name is different than the Billing Name – there’s no control over that, as we’re grouping by increment_id. This could easily be fixed in a PHP script, but the approach there should be different (using collections).

Hope this helps anyone, as it did the trick for me.

Solution tested under Magento 1.4.0.1

Magento, MySQL ,

Fixing “Catalog Price Rules” cart issue in Magento 1.4.1.0

June 29th, 2010

After recently upgrading one of my stores running Magento Commerce I found out the the latest version (at this time 1.4.1.0) had a major bug. Don’t want to sound too harsh, but unfortunately Magento’s support was again awful – there have been one thread on the forum and one issue in their bug tracking system for a while now (almost two weeks if not more) and still no update, although as I said the bug has quite an impact – even tweet’ed the problem to @magento and haven’t gotten any reply (again it’s not the first time). Yes, the product is free, yes it’s open source, but I think a bit of transparency and better communication could come to their advantage.

Bug details/behavior

So, updated from 1.4.0.1 to 1.4.1.0, everything looks fine, catalog price rules are being applied in the catalog (categories and product pages), but when adding the product to the cart the quote item price was the regular price not the special one.

Solution/Fix

After a few hours playing with the rules, observer and other core elements I found the problem. A big “thank you” goes to “myself” who posted the second comment for the issue mentioned above. The problem was within the CatalogRule Observer, when fetching the ID of the Customer Group. Here’s how to fix it:

1 – create the following folders in your Magento distro: app/code/local/Mage/CatalogRule/Model
2 – copy app/code/core/Mage/CatalogRule/Model/Observer.php to app/code/local/Mage/CatalogRule/Model
3 – open the new/copied file and go to line 105. Change this code:

        if ($observer->hasCustomerGroupId()) {
            $gId = $observer->getEvent()->getCustomerGroupId();
        } elseif ($product->hasCustomerGroupId()) {
            $gId = $product->hasCustomerGroupId();
        } else {
            $gId = Mage::getSingleton('customer/session')->getCustomerGroupId();
        }

to:

        if ($observer->hasCustomerGroupId()) {
            $gId = $observer->getEvent()->getCustomerGroupId();
        } elseif ($product->hasCustomerGroupId()) {
            $gId = $product->getCustomerGroupId();
        } else {
            $gId = Mage::getSingleton('customer/session')->getCustomerGroupId();
        }

To be more precise, you have to change hasCustomerGroupId to getCustomerGroupId on line 105.

You can now enjoy your store again!

Magento

Adding Customer Comments on Invoice PDFs in Magento (using OneStepCheckout)

January 18th, 2010

I’ve recently installed OneStepCheckout (http://www.onestepcheckout.com/) on a couple of Magento installations. The extension is very nice, really simple to integrate and I expect to see better conversion rates on the checkout process.

One cool thing is that it comes with the option of activating Customer Order Comments – it adds a textarea field on the checkout page, and a box with the customer comments in the admin, when viewing the order.

However, one of my clients requested I added these comments in the invoice PDF’s. So, here’s how to do it:

Step 1
Copy app/code/core/Mage/Sales/Model/Order/Pdf/Invoice.php to app/code/local/Mage/Sales/Model/Order/Pdf/Invoice.php

Step 2
Open the new file and create a new method:

	function insertOscComments(&$page, $order) {
		if( !$order->getOnestepcheckoutCustomercomment() ) { return; }
		$this->y -= 20;
		$page->setFillColor(new Zend_Pdf_Color_Rgb(0.93, 0.92, 0.92));
		$page->setLineColor(new Zend_Pdf_Color_GrayScale(0.5));
		$page->setLineWidth(0.5);
		$page->drawRectangle(25, $this->y, 570, $this->y - 20);
		$page->setFillColor(new Zend_Pdf_Color_Rgb(1, 1, 1));
		$page->drawRectangle(25, $this->y - 20, 570, $this->y - 40);

		$page->setFillColor(new Zend_Pdf_Color_RGB(0.1, 0.1, 0.1));
		$page->drawText(Mage::helper('onestepcheckout')->__('Customer Comments'), 35, $this->y - 13, 'UTF-8');
		$page->drawText($order->getOnestepcheckoutCustomercomment(), 33, $this->y - 33, 'UTF-8');
		$this->y -= 50;
	}

Step 3
At the end of method getPdf add a call to the new method you created:

  /* Add totals */
  $this->insertTotals($page, $invoice);

  /* Add OneStepCheckout Customer Comments */
  $this->insertOscComments($page, $order);
}

And that’s all you need.

Magento , ,

Showing all reviews and ratings on a page in Magento

August 6th, 2009

Finally, a new post, and at last it is about Mangeto Commerce (http://www.magentocommerce.com/). In my first Magento how-to you’ll learn how to retrieve all product reviews and show them on a single page, together with the average rating. For this, I assume you have already created a new module and are able to view the page. You’ll only need to manipulate a block and a template.

First, let’s retrieve the reviews collection (this method will go into the block):

	function getReviews() {
		$reviews = Mage::getModel('review/review')->getResourceCollection();
		$reviews->addStoreFilter( Mage::app()->getStore()->getId() )
						->addStatusFilter( Mage_Review_Model_Review::STATUS_APPROVED )
						->setDateOrder()
						->addRateVotes()
						->load();        

		return $reviews;
	}

We’re using Mage_Review_Model_Mysql4_Review_Collection, which is a resource model. First setup the collection, filtering by store – we only want to retrieve the product reviews in the current store -, by status – show only approved reviews -, and ordering by date in reverse order, then load the collection.

addRateVotes() helps loading all the ratings/votes for that review. We’re gonna use this collection to compute the average rating.

Next, let’s move on to the template for a second. We’re gonna call the getReviews() method, then iterate through all the reviews. For each review you would probably want to display the title, nickname, date and details, but also the product associated and the user rating. For the first four, things are pretty easy, all you have to do is call getTitle(), getNickname(), getDetail(), getCreatedAt() on each review object.

To display the product name & link, we need to retrieve the product associated with each review – unfortunately I wasn’t able to find a way to join the product tables inside the query for retrieving all the reviews. So, we need to create a helper method inside our block, called getProduct(). We’re gonna use a storage/registry variable called _loadedProducts, so that we avoid loading the same product multiple times.

	function getProduct( Mage_Review_Model_Review $review ) {
		if( !isset($this->_loadedProducts[ $review->getEntityPkValue() ]) ) {
			$this->_loadedProducts[$review->getEntityPkValue()] = Mage::getModel('catalog/product')->load( $review->getEntityPkValue() );
		}

		return $this->_loadedProducts[ $review->getEntityPkValue() ];
	}

And inside the template:

<?php $_prod = $this->getProduct( $review ); ?>
<a href="<?php echo $_prod->getProductUrl(); ?>"><?php echo $_prod->getName(); ?></a>

One last thing, if you intend to display the average rating of each review, add another helper method inside the block:

	function getAverageRating( Mage_Review_Model_Review $review ) {
		$avg = 0;
		if( count($review->getRatingVotes()) ) {
			$ratings = array();
			foreach( $review->getRatingVotes() as $rating ) {
				$ratings[] = $rating->getPercent();
			}
			$avg = array_sum($ratings)/count($ratings);
		}

		return $avg;
	}

And then call it in the template (in this example we’re using Magento’s default styling):

<div class="rating-box">
	<div class="rating" style="width: <?php echo ceil($this->getAverageRating( $review )); ?>%;"></div>
</div>

That is all! You now have a page where all product reviews can be display.
Things to consider: pagination and cache!

Update: Seems that Magento comes prepared for reviews on products, categories and customers. We only need to load product reviews, so it would be wise to filter by entity. Unfortunately, the current version of Magento doesn’t allow filtering for a certain entity, only by entity and entity PK (which is the product ID in this case). Of course, we could write a decorator and write a method to just add a filter for entity_code = 'product', but the quickest (and dirtiest) way of doing it is by adding a check inside the template foreach loop (or adding a helper method in the block):


if( $review->getEntityId() == 1 ) { continue; }
//1 is the id of the 'product' entity - if you write a method, use a class constant

Magento ,