You are on page 1of 45

September 8th, 2009 Published by: inchoo

Inchoo's Magento Posts


You're reading the 200th blog post edition of Inchoo's
Magento e-book. It collects all of our blog posts on
Magento. We want to thank everyone for staying with
us so far and hope we will live to see 1000th blog post
anniversary. :)

Inchoo is an ecommerce design and development


company specialized in building Magento online stores.

Boost the speed of your Magento


One of the drawbacks of Magento is currently its speed if
default configuration is used. There are certain ways of making
it run faster. The best one is to enable GZip compression by
changing .htaccess file a little. You just need to uncomment
part of the code. In my case, the speed increase was exactly
235%.

Add custom structural block / reference


in Magento | Inchoo
If you already performed some Magento research, you will
know that it is built on a fully modular model that gives
great scalability and flexibility for your store. While creating
a theme, you are provided with many content blocks that you
can place in structural blocks. If you are not sure what they
are, please read Designer’s Guide to Magento first. Magento
provides few structural blocks by default and many content Step 1: Name the structural block
blocks. This article tells what needs to be in place to create new
Open the file layout/page.xml in your active theme folder.
structural block.
Inside you will find lines like:
What are structural blocks? <block type="core/text_list" name="left" as="left"/>
They are the parent blocks of content blocks and serve to <block type="core/text_list" name="content" as="content"/>
<block type="core/text_list" name="right" as="right"/>
position its content blocks within a store page context. Take
a look at the image below. These structural blocks exist in the Let’s mimic this and add a new line somewhere inside the same
forms of the header area, left column area, right column…etc. block tag.
which serve to create the visual structure for a store page. Our
goal is to create a new structural block called “newreference”. <block type="core/text_list" name="newreference" as="newrefe

Good. Now we told Magento that new structural block exists


with the name “newreference”. Magento still doesn’t know
what to do with it.
Step 2: Tell Magento where to place it
We now need to point Magento where it should output this
new structural block. Let’s go to template/page folder in our
active theme folder. You will notice different layouts there.
Let’s assume we want the new structural block to appear only
on pages that use 2-column layout with right sidebar. In that
case we should open 2columns-right.phtml file.

Created using zinepal.com. Go online to create your own zines or read what others have already published. 1
September 8th, 2009 Published by: inchoo
Let’s assume we wish the “newreference” block to be placed TRUNCATE `sales_order_entity_datetime`;
below 2 columns, but above the footer. In this case, our TRUNCATE `sales_order_entity_decimal`;
TRUNCATE `sales_order_entity_int`;
updated file could look like this: TRUNCATE `sales_order_entity_text`;
TRUNCATE `sales_order_entity_varchar`;
<!-- start middle -->
TRUNCATE `sales_order_int`;
<div class="middle-container">
TRUNCATE `sales_order_text`;
<div class="middle col-2-right-layout">< ?php getChildHtml('breadcrumbs') ?>
TRUNCATE `sales_order_varchar`;
<!-- start center -->
TRUNCATE `sales_flat_quote`;
<div id="main" class="col-main"><!-- start global messages -->
TRUNCATE `sales_flat_quote_address`;
< ?php getChildHtml('global_messages') ?>
TRUNCATE `sales_flat_quote_address_item`;
<!-- end global messages -->
TRUNCATE `sales_flat_quote_item`;
<!-- start content -->
TRUNCATE `sales_flat_quote_item_option`;
< ?php getChildHtml('content') ?>
TRUNCATE `sales_flat_order_item`;
<!-- end content --></div>
TRUNCATE `sendfriend_log`;
<!-- end center -->
TRUNCATE `tag`;
TRUNCATE `tag_relation`;
<!-- start right -->
TRUNCATE `tag_summary`;
<div class="col-right side-col">< ?php getChildHtml('right') ?></div>
TRUNCATE `wishlist`;
<!-- end right --></div>
TRUNCATE `log_quote`;
<div>< ?php getChildHtml('newreference') ?></div>
TRUNCATE `report_event`;
</div>
<!-- end middle -->
ALTER TABLE `sales_order` AUTO_INCREMENT=1;

Step 3: Populating structural block


ALTER TABLE `sales_order_datetime` AUTO_INCREMENT=1;
ALTER TABLE `sales_order_decimal` AUTO_INCREMENT=1;
ALTER TABLE `sales_order_entity` AUTO_INCREMENT=1;
We have the block properly placed, but unfortunately nothing
ALTER TABLE `sales_order_entity_datetime` AUTO_INCREMENT=1;
is new on the frontsite. Let’s populate the new block with ALTER TABLE `sales_order_entity_decimal` AUTO_INCREMENT=1;
something. We will put new products block there as an ALTER TABLE `sales_order_entity_int` AUTO_INCREMENT=1;
example. Go to appropriate layout XML file and add this block ALTER TABLE `sales_order_entity_text` AUTO_INCREMENT=1;
to appropriate place. ALTER TABLE `sales_order_entity_varchar` AUTO_INCREMENT=1;
ALTER TABLE `sales_order_int` AUTO_INCREMENT=1;
<reference name="newreference"> ALTER TABLE `sales_order_text` AUTO_INCREMENT=1;
<block type="catalog/product_new" name="home.product.new" ALTER TABLE `sales_order_varchar` AUTO_INCREMENT=1;
template="catalog/product/new.phtml" />
</reference> 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
That’s it. I hope it will help someone
ALTER TABLE `sales_flat_quote_item` AUTO_INCREMENT=1;
There are 15 comments 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;
How to delete orders in Magento? | ALTER TABLE `tag` AUTO_INCREMENT=1;
ALTER TABLE `tag_relation` AUTO_INCREMENT=1;
Inchoo ALTER TABLE `tag_summary` AUTO_INCREMENT=1;
ALTER TABLE `wishlist` AUTO_INCREMENT=1;
ALTER TABLE `log_quote` AUTO_INCREMENT=1;
You got a Magento project to develop, you created a Magento
ALTER TABLE `report_event` AUTO_INCREMENT=1;
theme, you placed initial products and categories and you
also placed some test orders to see if Shipping and Payment -- reset customers
methods work as expected. Everything seems to be cool and TRUNCATE `customer_address_entity`;
the client wishes to launch the site. You launch it. When you TRUNCATE `customer_address_entity_datetime`;
TRUNCATE `customer_address_entity_decimal`;
enter the administration for the first time after the launch, you TRUNCATE `customer_address_entity_int`;
will see all your test orders there. You know those should be TRUNCATE `customer_address_entity_text`;
deleted. But how? TRUNCATE `customer_address_entity_varchar`;
TRUNCATE `customer_entity`;
If you try to delete orders in the backend, you will find out TRUNCATE `customer_entity_datetime`;
that you can only set the status to “cancelled” and the order is TRUNCATE `customer_entity_decimal`;
still there. Unfortunately, Magento doesn’t enable us to delete TRUNCATE `customer_entity_int`;
those via administration, so you will not see any “Delete order” TRUNCATE `customer_entity_text`;
TRUNCATE `customer_entity_varchar`;
button. This can be quite frustrating both to developers and
TRUNCATE `log_customer`;
the merchants. People coming from an SAP world find the TRUNCATE `log_visitor`;
inability to delete to have some merit but there should be a TRUNCATE `log_visitor_info`;
status that removes the sales count from the reports i.e. sales,
inventory, etc. ALTER TABLE `customer_address_entity` AUTO_INCREMENT=1;
ALTER TABLE `customer_address_entity_datetime` AUTO_INCREMEN
SET FOREIGN_KEY_CHECKS=0; ALTER TABLE `customer_address_entity_decimal` AUTO_INCREMENT
ALTER TABLE `customer_address_entity_int` AUTO_INCREMENT=1;
TRUNCATE `sales_order`; ALTER TABLE `customer_address_entity_text` AUTO_INCREMENT=1;
TRUNCATE `sales_order_datetime`; ALTER TABLE `customer_address_entity_varchar` AUTO_INCREMENT
TRUNCATE `sales_order_decimal`; ALTER TABLE `customer_entity` AUTO_INCREMENT=1;
TRUNCATE `sales_order_entity`; ALTER TABLE `customer_entity_datetime` AUTO_INCREMENT=1;

Created using zinepal.com. Go online to create your own zines or read what others have already published. 2
September 8th, 2009 Published by: inchoo
ALTER TABLE `customer_entity_decimal` AUTO_INCREMENT=1; ?>
ALTER TABLE `customer_entity_int` AUTO_INCREMENT=1;
ALTER TABLE `customer_entity_text` AUTO_INCREMENT=1; < ?php if (!empty($result)): ?>
ALTER TABLE `customer_entity_varchar` AUTO_INCREMENT=1; <table id="relatedProductsList">
ALTER TABLE `log_customer` AUTO_INCREMENT=1; < ?php foreach ($result as $item): ?>
ALTER TABLE `log_visitor` AUTO_INCREMENT=1; <tr class="productInfo">
ALTER TABLE `log_visitor_info` AUTO_INCREMENT=1; <td><a href="<?php echo $storeUrl ?>/< ?php echo $item->url_
<td>< ?php _e('Starting at') ?> $ < ?php echo floatval($item
-- Reset all ID counters </tr>
TRUNCATE `eav_entity_store`; < ?php endforeach; ?>
ALTER TABLE `eav_entity_store` AUTO_INCREMENT=1; </table>
< ?php endif; ?>
SET FOREIGN_KEY_CHECKS=1;
Hope some of you find this useful. Especially those who refuse
After you have it executed, the test orders will not be in the to use Web Services for connecting different systems.
database any more. Keep in mind that this will delete ALL
orders, in the database. So, you should execute this queries Download connect2MAGE WordPress plugin.
immediately after launch. There are 6 comments

connect2MAGE | WordPress plugin for Custom checkout cart - How to send


easy Magento database connection email after successful checkout in
Hi everyone. I wrote this little plugin while working on one Magento | Inchoo
of our projects. If you know your way around WordPress
then you know what $wpdb variable stands for. Imagine the Recently I have been working on a custom checkout page for
following scenario. You have WordPress installation on one one of our clients in Sweden. I had some trouble figuring out
database, Magento on another. You know your way around how to send default Magento order email with all of the order
SQL. You can always make new object based on WPDB class info. After an hour or so of studying Magento core code, here
inside your template files giving it database access parameters, is the solution on how to send email after successful order has
or you can use this plugin and use $MAGEDB the same way been made.
you use $wpdb. Not sure how useful this alone will be for you, so I’ll throw a
Below is a little example of using $MAGEDB to connect to little advice along the way. When trying to figure how to reuse
Magento database and retrieve some products by reading id’s Magento code, separate some time to study the Model classes
from custom field of some post inside your WordPress. with more detail. Then “tapping into” and reusing some of
them should be far more easier.
Place this code inside one of your templates, like single.php.
< ?php
Latest News RSS box in Magento using
global $MAGEDB;
$MAGEDB->show_errors(true);
Zend_Feed_Rss | Inchoo
You would like to have a eCommerce power of Magento, but
/** BASIC SETUP */
also have a blog to empower your business? In this case,
//$storeUrl = 'http://server/shop/index.php/'; you probably know that Magento doesn’t have some article
$storeUrl = get_option('connect2MAGE_StoreUrl'); manager in the box. Many clients seek for supplementary
solution like Wordpress to accomplish this goal. Ok, so you
//$urlExt = '.html';
created a blog on same or different domain and you would
$urlExt = get_option('connect2MAGE_UrlExt');
like those articles to appear somewhere in Magento (probably
/** END OF BASIC SETUP */ sidebar). This article will explain how to do it.
Let’s create a
$entityIds = get_post_custom_values(get_option('connect2MAGE_CustomFieldName'));
file called latest_news.phtml
in app/design/frontend/default/[your_theme]/template/
$result = array(); callouts/latest_news.phtml
Now we will create a PHP block that will display the list
if(!empty($entityIds)) of articles from RSS feed. We will use Inchoo RSS for
{
$entityIds = $entityIds[0];
demonstration purposes. In your scenario, replace it with your
$sql = "SELECT `e`.*, `_table_price`.`value` AS `price`, own valid RSS URL.
IFNULL(_table_visibility.value, _table_visibility_default.va
$result = $MAGEDB->get_results($sql);
var_dump($result); < ?php $channel = new Zend_Feed_Rss('http://feeds.feedburner
}
<div class="block block-latest-news">
else <div class="block-title">
{ <h2>< ?php echo $this->__('Latest News') ?></h2>
</div>
echo '<p class="relatedProductInfo">No related products available...</p>';
} <div class="block-content">

Created using zinepal.com. Go online to create your own zines or read what others have already published. 3
September 8th, 2009 Published by: inchoo
<ol id="graybox-latest-news"> • use the http://somestore.domain/catalogsearch/
< ?php foreach ($channel as $item): ?> partnumber as a link
<li><a href="<?php echo $item->link; ?>">< ?php echo $item->title; ?></a></li>
< ?php endforeach; ?> • show only custom_partnumber field on the search form
</ol>
</div> First, we have to see where does the /advanced come from.
</div>
Lets open our template folder at
Step 2 app\design\frontend\default\default\template
Now, we should decide where to place it. I assume you already \catalogsearch\
know how Magento blocks and references work. Let’s assume
there you will see the /advanced folder. Make a copy of that
you would like to place it in right column by default for whole
entire folder, in the same location, and name it to something
catalog. In this case open your app/design/frontend/default/
like /custom.
[your_theme]/layout/catalog.xml file and under “default” tag
update “right” reference with something similar. Now your /custom folder should have 2 files: form.phtml and
result.phtml.
That’s it. You should be able to see the list of articles from RSS
feed with the URLs. Hope this will help someone. Next in line is the /layout folder in our template. You need
to open catalogsearch.xml file. Go to line 64. Do you see the

Advanced search in Magento and how to


<catalogsearch_advanced_index> tag there. Make the copy of
it (including all of the content it hold with the closing tag also).
use it in your own way Put the copy of that entire small chunk of code right below.
Now rename all of the occurrences of “advanced” to “custom”
It’s been a while since my last post. I’ve been working on there like on code below:
Magento quite actively last two months. I noticed this negative
<catalogsearch_custom_index>
trend in my blogging; more I know about Magento, the less
<!– Mage_Catalogsearch –>
I write about it. Some things just look so easy now, and they
start to feel like something I should not write about. Anyhow….
<reference name=”root”>
time to share some wisdom with community
Our current client uses somewhat specific (don’t they all) store <action
set. When I say specific, i don’t imply anything bad about it. method=”setTemplate”><template>page/2columns-
One of the stand up features at this clients site is the advanced right.phtml</template></action>
search functionality. One of the coolest features of the built in
advanced search is the possibility to search based on attributes </reference>
assigned to a product.
<reference name=”head”>
To do the search by attributes, your attributes must have that
option turned on when created (or later, when editing an
<action method=”addItem”><type>js_css</
attribute). In our case we had a client that wanted something
type><name>calendar/calendar-win2k-1.css</
like
name><params/><!–<if/
http://somestore.domain/catalogsearch/partnumber ><condition>can_load_calendar_js</condition>–></
or action>

http://somestore.domain/catalogsearch/brand <action method=”addItem”><type>js</


instead of the default one type><name>calendar/calendar.js</name><!–<params/
http://somestore.domain/catalogsearch/advanced ><if/><condition>can_load_calendar_js</condition>–
with all of the searchable fields on form. ></action>

Some of you might say why not use the default and call it a day. <action method=”addItem”><type>js</
Well, default one does not get very user friendly when large type><name>calendar/lang/calendar-en.js</name><!–
number of custom added searchable attributes are added in <params/><if/><condition>can_load_calendar_js</
Magento admin interface. Then the frontend search form gets condition>–></action>
cluttered and users are easily to get confused.
So in our example we would like to use the advanced search <action method=”addItem”><type>js</
and all of it’s behaviour and logic but to use it on somewhat type><name>calendar/calendar-setup.js</name><!–
special link and to hide unnecessary fields. Therefore, our <params/><if/><condition>can_load_calendar_js</
custom pages he would have only one input field on form and condition>–></action>
the submit button. How do we set this up? Well, all of the logic
and functionality is already there. </reference>
What we need is to:
<reference name=”content”>

Created using zinepal.com. Go online to create your own zines or read what others have already published. 4
September 8th, 2009 Published by: inchoo
<block type=”catalogsearch/custom_form” This might not be the best method of reusing already written
name=”catalogsearch_custom_form” code, however I hope it’s any eye opener to somewhat more
template=”catalogsearch/custom/form.phtml”/> elegant aproach.
Enyoj.
</reference>
There are 14 comments
</catalogsearch_custom_index>
Do the same for <catalogsearch_advanced_result> tag. Related products
Now go to the app\code\core\Mage\CatalogSearch\Block
There are three types of product relations in Magento:
folder. And make a copy of /Advanced folder naming
Up-sells, Related Products, and Cross-sell Products. When
it /Custom. Open /Custom/Form.php and replace
viewing a product, Upsells for this product are items that your
class name Mage_CatalogSearch_Block_Advanced_Form
customers would ideally buy instead of the product they’re
with Mage_CatalogSearch_Block_Custom_Form, then
viewing. They might be better quality, produce a higher profit
open /Custom/Result.php and replace class
margin, be more popular, etc. These appear on the product
name Mage_CatalogSearch_Block_Advanced_Result with
info page. Related products appear in the product info page
Mage_CatalogSearch_Block_Custom_Result.
as well, in the right column. Related products are meant to
Inside Form.php there is getModel() function. DO NOT be purchased in addition to the item the customer is viewing.
replace the Mage::getSingleton(’catalogsearch/advanced’); Finally, Cross-sell items appear in the shopping cart. When
with Mage::getSingleton(’catalogsearch/custom’);. The point a customer navigates to the shopping cart (this can happen
is to use the default advanced search logic here. Same goes for automatically after adding a product, or not), the cross-sells
getSearchModel() function inside Result.php file. block displays a selection of items marked as cross-sells to the
Next in line, controllers. We need to make items already in the cart. They’re a bit like impulse buys – like
the copy of AdvancedController.php and name it magazines and candy at the cash registers in grocery stores.
CustomController.php, then open it and replace the
class name Mage_CatalogSearch_AdvancedController with
Upsells
Mage_CatalogSearch_CustomController. This is the example of the Up-sell. Ideally, the visitor is
supposed to analyze those products as they should be relevant
Inside this CustomController.php there is a function
to the one that is just loaded.
called resultAction(). You need to replace the ( …
Mage::getSingleton(’catalogsearch/advanced’) … ) string
‘catalogsearch/advanced’ with ‘catalogsearch/custom’. This is
the one telling the browser what page to open.
Now if you open your url link in browser with /index.php/
catalogsearch/custom instead of /index.php/catalogsearch/
advanced you will see the same form there.
And for the final task… As we said at the start, the point of all
this is to 1) get more custom link in url and 2) display only one
custom searchable attribute field in form. Therefore, for the
last step we need to go to the template\catalogsearch\custom
folder and open form.phtml file.
Inside that file, there is one foreach loop that goes like
There are 2 comments
<?php foreach ($this->getSearchableAttributes() as
$_attribute): ?> File upload in Magento
All we need to do now is to place one if() condition
Now, Magento already have frontend and admin part of file
right below it. If your custom attribute name (code) is
upload option implemented in themes. Since backend part is
“my_custom_attribute” then your if() condition might look
still missing, understand that this still doesn’t work, however,
something like
if you’re interested how it looks, read on ..
<?php foreach ($this->getSearchableAttributes() as
We are coding module of similar functionality for one of our
$_attribute): ?>
clients as we speak, but we have our fingers crossed to see this
<?php if($_code == ‘my_custom_attribute’): ?>
option in next Magento version!

<?php endif; ?>
<?php endforeach; ?>
And you are done. Now you have somewhat more custom url,
and only one custom field displayed on that url.

Created using zinepal.com. Go online to create your own zines or read what others have already published. 5
September 8th, 2009 Published by: inchoo

Inchoo TV – Magento channel Mage::getSingleton(’catalog/session) on view.phtml file we


would retrieve an array with some useful data in it. Do
not get confused with me mentioning the view.phmtl file,
it’s just he file i like to use to test the code. Using
Mage::getSingleton(’core/session) would retrieve us some
more data. You get the picture. Test, test, test… What’s great
about the whole thing is that naming in Magento is perfectly

Making use of Magento getSingleton


logical so most of the time you will probably find stuff you need
in few minutes or so.
method
In one of my previous articles I showed you how to use Figuring out Magento object context
getModel and getData methods in Magento. Although we
One of the problems working under the hood of the Magento
should not put those to methods at the same level, since I’d say
CMS is determining the context of $this. If you are about
the getModel is a bit more higher. Higher in sense, you first
to do any advanced stuff with your template, besides layout
use the geModel to create the instance of object then you use
changes, you need to get familiar with Magento’s objects
getData to retrieve the data from that instance. I have said it
(classes).
before, and I’m saying it again; Magento is a great peace of
full OOP power of PHP. It’s architecture is something not yet Let’s have a look at the /app/design/frontend/default/
widely seen in CMS solutions. default/template/catalog/product/view.phtml file. If you
open this file and execute var_dump($this) your browser will
One of the architectural goodies of Magento is it’s Singleton
return empty page after a short period of delay. By page I mean
design pattern. In short, Singleton design pattern ensures a
on the product view page; the one you see when you click on
class has only one instance. Therefore one should provide a
Magetno product. Experienced users will open PHP error log
global point of access to that single instance of a class.
and notice the error message caused by var_dump(). Error
So why would you want to limit yourself to only one instance? message:
Let’s say you have an application that utilizes database PHP Fatal error: Allowed memory size of 134217728 bytes
connection. Why would you create multiple instance of the exhausted (tried to allocate 121374721 bytes)
same database connection object? What if you had references
I like using print_r() and var_dump(), mostly because so far
to an object in multiple places in your application? Wouldn’t
I had no positive experience using fancy debug or any other
you like to avoid the overhead of creating a new instance of
debugger with systems like Magento.
that object for each reference? Then there is the case where
you might want to pass the object’s state from one reference Why is PHP throwing errors then? If you google out the
to another rather than always starting from an initial state. error PHP has thrown at you, you’ll see that PHP 5.2
has memory limit. Follow the link http://www.php.net/
Inside the Mage.php file of Magento system there is a
manual/en/ini.core.php#ini.memory-limit to see how and
getSingleton method (function if you prefer). Since it’s
what exactly.
footprint is rather small, I’ll copy paste the code for you to see
it. Google search gave me some useful results trying to solve my
problems. I found Krumo at http://krumo.sourceforge.net/.
First, notice the word static. In PHP and in other OOP
It’s a PHP debugging tool, replacement for print_r() and
languages keyword static stands for something like “this can
var_dump(). After setting up Krumo and running it on
be called on non objects, directly from class”. Now let me show
Magento it gave me exactly what I wanted. It gave me the
you the footprint of the getModel method.
object type of the dumped file; in this case it gave me object
Do you notice the parameters inside the brackets? They are the type of $this.
same for both of theme. Where am I getting with this? Well,
If you’re using an IDE studio with code completion support
I already showed you how to figure out the list of all of the
like NuSphere PhpED, ZendStudio or NetBeans and you
available parameters in one of my previous articles on my site.
decide to do something like $this-> you won’t get any methods
So all we need to do at this point is, play with those parameters
listed. I haven’t yet seen the IDE that can perform this kind of
using getSingleton() method and observe the results.
smart logic and figure out the context of $this by it self.
Most important thing you need to remember is that using
What you can do is use the information obtained
getSingleton you are calling already instantiated object. So if
by krumo::dump($this). Performing krumo::dump($this)
you get the empty array as a result, it means the object is
on /app/design/frontend/default/default/template/catalog/
empty. Only the blueprint is there, but nothing is loaded in it.
product/view.phtml file will return object type,
We had the similar case using getModel(’catalog/product‘)
Mage_Catalog_Block_Product_View.
on some pages. If we done var_dump or print_r we could
saw the return array was empty. Then we had to use the load Now if you do
method to load some data into our newly instantiated object. Mage_Catalog_Block_Product_View::
What I’m trying to say, you need to play with it your IDE supporting code completion will give you
to get the feeling. Some models will return data rich a drop down of all the available methods, let’s say
objects some will return empty arrays. If we were to do canEmailToFriend();
Created using zinepal.com. Go online to create your own zines or read what others have already published. 6
September 8th, 2009 Published by: inchoo
Mage_Catalog_Block_Product_View::canEmailToFriend(); What is “Best Value” filed?
Now all you need to do is to replace
When you go to Category page in Magento administration, you
Mage_Catalog_Block_Product_View with $this like
will see “Category Products” tab. From there, you will see the
$this->canEmailToFriend(); list of products that are associated to this category. The last
And you’re done. All of this may look like “why do I need this”. column in “Position”. That is how “Best Value” is determined.
What you need it a smart IDE, one that can figure out the So, best value is not something that is dynamically calculated.
context of $this by it self and call the methods accordingly. No You can tailor it to your likings.
IDE currently does that, if I’m not missing on something. For
now I see no better solution to retrieve the object context of
$this across all those Magento files.
If you need some help setting up Krumo with Magento
you can read my other, somewhat detailed article on
activecodeline.com.
Hope this was useful for you.
There are 2 comments

Get product review info (independent) of


review page
Here at Inchoo, we are working on a private project, that
should see daylight any time soon. One of the requirements How to change default Sort Order
we had is to show product review info on pages independent The file you need to look at is: /app/code/core/Mage/Catalog/
of product review page. Let’s say you wish to show review info Block/Product/List/Toolbar.php Since we’ll modify it, make a
on home page for some of the products. After few weeks with copy to /app/code/local/Mage/Catalog/Block/Product/List/
working with Magento, one learns how to use the model stuff Toolbar.php
directly from view files. Although this might not be the “right”
way, it’s most definitely the fastest way (and I doubt most of One there, you will notice this code at the beginning of the file:
your clients would prefer any other , especially if it’s some $this->_availableOrder = array(
minor modification). 'position' => $this->__('Best Value'),
'name' => $this->__('Name'),
'price' => $this->__('Price')
Simple random banner rotator in );

Magento using static blocks Default order takes the first value available. So, all you have to
do is to either:
This is my first post here and I’ll write about my first challenge
regarding Magento since I came to work at Inchoo. • reorder it if you want to have a selection in the Toolbar or
Please note that you are not restricted only to images, you • set only one value of choice if you will remove the
could use text, video or whatever you want here, but I’ll focus selection from the toolbar
on images with links as title says.
In order to show this block, you should be familiar with I hope this will help somebody.
Magento layouts.
There are 4 comments
Since that is out of scope for this article, I’ll show you how to
put it below the content on cms pages.
Couple of days ago we launched a new Magento project:

Changing default category sort order in


Pebblehill Designs. This site utilizes Magento features and
turns it into a very powerful online catalog. You won’t notice
Magento the Shopping Cart or checkout process yet. Even without
those, this site shows exactly what Pebblehill has to offer: the
Category toolbar has many options. By default is shows how most popular styles of custom upholstered furniture.
many items are in the category, you can choose how many
You can customize the furniture collection to express your
products you wish to be displayed per page, you can change
own unique style made with the highest quality materials and
the listing type (List or Grid) and you may choose Sort Order.
craftsmanship available.
This “Sort Order” can be confusing. The default “Sort Order”
is “Best Value”. What does it mean? How is the Best value Pebble Hill Designs’ parsons chairs are “American made” with
determined? Can we change the default sort order? pride in Georgia. The quality speaks for itself. Your products
are pre-assembled and ready for use when you receive them.

Created using zinepal.com. Go online to create your own zines or read what others have already published. 7
September 8th, 2009 Published by: inchoo
The love and the passion for beautiful home interiors
translates into a high-quality product with a sophisticated
style manufactured in the USA. Pebblehill Designs has
assembled some of the most popular styles of custom
upholstered furniture to offer to our customers. All styles are
available in every fabric shown or you can provide your own
fabric. You can customize the furniture collection to express
your own unique style made with the highest quality materials
and craftsmanship available.

Magento part of the site can be viewed if you click at Shop by


Vehicle or Shop by Brand tabs from the main menu, but you
will notice that some blocks seamlessly integrate between two
solutions.

We developed this site as the Surgeworks team. The design


was created by one of out top designers, Rafael Torales. We
hope you enjoy it and feel free to post your comments.
There are 6 comments

The Best Shopping Cart :: Trend analysis


of osCommerce, Magento, ZenCart and
CRE Loaded | Inchoo
If you try to ask this question on some forum or newsgroup,
you will surely get many replies. Everyone will present you
his favorite. My first developed online store was created with
TeraFlex PLUS, another Magento + standard osCommerce platform. After three or four projects,
I started to work with CRE Loaded and used it frequently for
Wordpress duo years. Although it was also an osCommerce fork, it had many
After we launched TeraFlex Suspensions website few months advantages. I switched to Magento™ early this year and this
ago, we created a new similar website for Teraflex PLUS. is my final choice.
Although the name is similar, this is not the same company. Google™ Trends is a great tool to check some platforms
The primary goal of this site is to help Jeep owners to upgrade popularity by comparing it to the competition. For my short
their pets with parts and accessories for any type of adventure. analysis, I compared:
The secondary goal is to create a Jeep enthusiast community
in Utah, USA and surroundings. The site is powered by
Wordpress and Magento combination.
Magento is a superb Shopping Cart, but it lacks some of the
CMS features. Wordpress is a superb CMS, but it fails to
provide the needs for the eCommerce goals. The combination
of these can create a very powerful website. We present you
TeraFlex PLUS : Jeep Adventure Outfitters
http://www.teraflexplus.com/

As you can see, osCommerce still remains the most popular


eCommerce platform. However, you can notice that this

Created using zinepal.com. Go online to create your own zines or read what others have already published. 8
September 8th, 2009 Published by: inchoo
popularity is fading. ZenCart is stable for the past two years. also tutorial about this on Magento Wiki. However i don’t like
And my previous favorite, CRE Loaded (much better solution approach of duplicating and overriding Mage files from /local,
than ZenCart in my opinion), is very low. Its popularity is also if it can be avoided, so i decided to write this small and useful
fading even after their team put great effort into a new website example of adding or overriding default Magento settings
and identity. through separated config files. And yes, Magento values can
be overridden this way. Default layouts config can be found
Now, take a look at blue line. My prediction is that sometime
in app/code/core/Mage/Cms/etc/config.xml along with used
in Q1 2009, Magento will become most popular eCommerce
xml code structure, so check it out. Thank you for listening!
platform. It will surely kick osCommerce off the throne where
that fat duck was sitting for many years. It was about time.
Drupal to Magento integration, simple
First of all, let me inform you that this article is for those of link tweak with multilingual site
you who are just starting with Magento. If you are a Magento
expert, you will probably know this. Consider it just a reminder I see my coworker and friend Željko Prša made a nice little post
for those who use Magento for first time. There are three on Adding a new language in Magento so I figure I’ll jump with
common mistakes that most people do when they try to use a little Drupal to Magento integration trick concerning link
Magento for first time, so read this article and you won’t be issues and multilingual sites. Here is a piece of code you can
one of them.:) use in your Drupal templates to do the proper switching from
Drupal site to Magento while keeping the selected language of
• More experienced PHP developers will first read site. Note, this tweak assumes you have the desired language
Magento Designers Guide before they try to style setup on both Drupal and Magento side.
Magento, but others won’t and that’s the mistake This part goes to some of your Drupal theme file
number two. Since Magento has great theme fallback
system there is really no need to touch default theme. ...
Although easiest way to make new theme for new global $language ;
Magento is top copy the whole theme to a new folder, $lname = ($language->language == null) ? 'en' : $language->l
$storeView = null;
don’t do that. Copy only the files you will need: from / if($lname == 'de') { $storeView = '?___store=german&amp;amp;
design/frontend/default/default/ directory to /design/ ??>
frontend/default/YOUR_NEW_THEME directory. Do
the same thing with /skin/frontend/default/default/ </p><p style="text-align: left;"><a id="main_menu_shop" href
...
Congratulations, you have your own theme just like
that. All that left is to apply new theme (System- Note the $storeView variable; GET ___store holds the value
>Configuration->Design) and you are ready to do with of code name of the view you assigned in Magento, while GET
your theme files whatever you want. ___from_store variable is used as helper to Magento inner
workings. You can basically omit the other one. Your links to
• Third mistake is modifying Magento core files. What files
Shop from Drupal to Magento should now activate the proper
are core ones? All what is in app/code/core folder. If you
language, the same one you have active on Drupal side.
have a need to modify some of those ones, you just need
to duplicate that file in the same directory path to app/ There are 1 comments
code/local. For example, if you need to modify the file
app/code/core/Mage/Checkout/Block/Success.php
Adding a new language in Magento
copy it to As anything in Magento adding a new language is something
that requires a certain procedure which we will explain right
app/code/local/Mage/Checkout/Block/Success.php now and for future reference.
and leave the core file intact. This way your Magento will • 3. Now go to: Configuration -> Current Configuration
be more bullet-proof to future updates. Scope (Select your language from the dropdown) and on
the right side under “Locale options” choose the desired
language.
Custom CMS page layout in Magento |
Inchoo
That’s it, now when you go to the frontend of the site, you’ll
notice a dropdown menu allowing the language switching.
Last week I had a request to add new custom layout
for few cms pages in one Magento shop. It’s really
useful for different static pages of your shop. First create
Access denied in Magento admin
extension with only config file in it: app/code/local/Inchoo/ Some of you may encountered this problem. You install new
AdditionalCmsPageLayouts/etc/config.xml Magento extension through downloader, try to access its
Add your page/custom-static-page-1.phtml template file (or configuration settings and Magento throws “Access denied”
page at you. Although you’re administrator of the system.
copy some default one for start) and you’re done There is

Created using zinepal.com. Go online to create your own zines or read what others have already published. 9
September 8th, 2009 Published by: inchoo

There are 5 comments

If you worked with osCommerce, Zen Cart, CRE Loaded or any


similar eCommerce platform before, you might find Magento
database structure quite confusing when you see it for the first
time. I advise you not to rush too much figuring out what
is what by glancing through database. Try to spend first few
hours getting familiar with some background. For purposes
of flexibility, the Magento database heavily utilizes an Entity-
Attribute-Value (EAV) data model. As is often the case, the
cost of flexibility is complexity. Is there something in Magento
that is simple from developers point of view?
Data manipulation in Magento is often more knowledge
demanding than that typical use of traditional relational
So what happened here? Magento just doesn’t have stored tables. Therefore, an understanding of EAV principles and
privileges for this new extension. how they have been modeled into Magento it is HIGHLY
First just try to logout and login again. If that doesn’t work, recommended before making changes to the Magento
you need to reset admin privileges. data or the Magento schema (Wikipedia: Entity-attribute-
value_model). Varien has simplified the identification of EAV
Navigate to System->Permissions->Roles and click
related tables with consistent naming conventions. Core EAV
Administrators role.
tables are prefixed with “EAV_”. Diagrams in this post contain
a section labeled “EAV” which displays Magento’s core EAV
tables and thier relationships to non-EAV tables.

Check your Role Resources settings just in case, Resource


Access dropdown should be already set to All for Database diagrams and documents found in this post are
administrators. intended to mirror the database schema as defined by Varien.
Table relationships depicted in the diagrams represent only
those relationships explicitly defined as Foreign Keys in the
Magento database. Additional informal/undiagrammed table
relationships may also exist, so when modifying the schema
or directly manipulating data it is important to identify and
evaluate possible changes to these tables as well (and the
tables they relate to, and the tables they relate to…).
The author of Database Diagram is Gordon Goodwin, IT
Consultant. You can see his info in the PDF.
There are 12 comments

Magento + .Net Framework, simple order


preview app
Without changing anything just click “Save Role” button, so
For those of you who are into kinky stuff I made a simple,
that Magento re-saves all permissions.
more of a proof of concept, application that sits in Widnows
You should be able to access your new extension now without taskbar and shows the order info in balloon popup. Took me
problems. little more than half of hour to get this working. Almost forgot
how great C# is
Created using zinepal.com. Go online to create your own zines or read what others have already published. 10
September 8th, 2009 Published by: inchoo
Magento has this great feature, rss feed for orders. You
can access it via link http://myshopsite/rss/order/new. It
requires authentication, so you need to provide Magento user
and pass to access this link. Idea I wanted to play around
was how to get this info in my windows app. It’s really, really
simple. Below is the screenshot of this little app for you to see
what I’m talking about.

Technically, we create a simple products and after that a


grouped products. When we edit the grouped product, we will
associate simple products to it.It works very fine, but some of
you might have issue if a simple product has custom options.
If that’s the case, and if costum options are set as required
And here is the application it self simpleorderpreview and full (default way), the simple product will not be associative to the
source code (Visual Studio 2008 Express C#, entire solution grouped product. Let’s see what needs to be changed in that
project) acmnewproducts. case.

When you un-archive files from simpleorderpreview there is On Magento site, there is a nice tutorial how to create a
only one thing you need to do prior to running .exe file. You grouped product. Please read it first to become familiar with
need to open ACMNewProducts.exe.config and set username, the process. If you don’t have to assign simple products with
password and url of your own Magento shop. That’s it. Now custom options to a grouped product, that tutorial will be
you can run the app. enough.

One click on Magento icon inside the taskbar executes


show order process, while double cliking the icon closes the
application.
I will not go into the details in this post on how this works.
Basicaly it’s simple XML parser. Most important part is the
HTTP authentification, which you can see in code source code.
Hope you find this usefull, something to play with.
There are 4 comments

Associate simple product with custom


Manually create Google Sitemap in
options in grouped product in Magento |
Magento | Inchoo
Inchoo
Most of you probably know this, but let’s define what the
Does the title sound complicated? Grouped Products display sitemaps are. Sitemaps are a simple way for site creators to
several products on one page. For example – if you’re selling give search engines the information about pages on their site
chef’s knives and you have the same knife in four sizes, you can that are available for public. Basically, those are just 1 or more
make a grouped product to display all four sizes. Customers XML files that lists URLs for a site along with additional meta
can select the size(s) they want and add to cart from this page. informatio about each URL (like last update, how often it
Another example would be a themed bedroom set – you can changes, its importance relevant to other pages). With this in
create a grouped product and sell the sheets, comforter, and mind, search engines can be more clever while crawling the
pillow cases all from the same page. 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.

Created using zinepal.com. Go online to create your own zines or read what others have already published. 11
September 8th, 2009 Published by: inchoo

How do we create Google Sitemap in Magento? One of the things that caught my eye and made me
wonder about the consequences is the Observer and override
1. Sitemap File Configuration functionality that probably most of the serious custom made
Magento modules will utilize. Utilizing Observers enables you
First we need to create sitemap file in Magento. This is
to observe and execute some action inside the “customer work
basically pointer to tell Magento where to create sitemap file
flow” or even some admin stuff. Such functionality is heavily
and how to name it. Log in to Magento Administration and go
known is systems like WordPress and it’s called “hooks”.
to:
Besides hooking, another useful an very powerful feature
Catalog -> Google Sitemap
which is actually related more to the OOP concept itself is the
Check to see if the sitemap file is already present. Lets overriding. Personally i find the combination of observers and
assume we wish to create sitemap in the URL: http:// overrides to be the coolest and most powerful stuff in Magento
www.yourstore.com/sitemap/sitemap.xml module development.
To do it successfully,
So where is the issue? As of time of this writing, the
1. FTP to the server latest Magento version is 1.3.1. Let’s look at the previous
“major” release prior to that one, version 1.2.1.2. Here is
2. create sitemap folder a prepareForCart method signature from app/code/core/
3. chmod the folder to 777 Mage/Catalog/Model/Product/Type/Abstract.php (line 239,
Magento version 1.2.1.2):
On some servers, previous steps will not be required, but it is
Notice the difference? Although this might not look like
better to create the file first so that Magento can edit it.
“that big of a deal” suppose you had implemented override
Let’s go to Magento administration now and click on “Add functionality like
Sitemap” button. Just insert the default values.
In the above code, we override the prepareForCart method to
After this step, we just told Magento where to create sitemap to some custom stuff for us. This peace of code would work
file. It is not yet created. perfectly fine in version 1.2.1.2, but when client decides to
upgrade the shop to 1.3.1 or newer he would get the error like
2. Configure Sitemap
To me, stuff like this is a serious downside towards building
Sitemap can be configured from the interface System ->
advanced modules. Changing core files and core functionality
Configuration -> Catalog->Google Sitemap. If you are not sure
can have serious impact on custom made modules each
what does it all mean, check XML Tag definitions section from
Magento upgrade. Therefore, one should keep an eye open
“Sitemaps XML format” document.
on what modules he will throw into the shop. Personally I
3. Create Sitemap Manually consider online stores very serious and have strong feelings
about each store owner having somewhat of dedicated
Looks like Magento folks were thinking that sitemap should developer that will be in charge even for stuff like adding new
only be created by a cron job. Yes, it can be done that way modules.
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, Just consider the financial loss for a store owner of any more
quit your search for “Create Sitemap” button. You will not find serious web shop if he decides to download the and install
it. But there is a workaround. You can enter manual URL to module himself just to realize that for incompatibility reasons
execute sitemap creation: this new module made his shop fully nonfunctional.
http://www.yourstore.com/index.php/admin/sitemap/
generate/sitemap_id/[ID of Sitemap from step 1] How to transfer large Magento database
Of course, replace the content with square brackets with actual from live to development server and
Sitemap ID.
other way round
There are 9 comments
I have been involved in Magento development for almost a
year now. God knows I had (and still have) my moments of
Observer pitfalls of building serious pain with it . If you are in professional, everyday, PHP
modules in Magento development that focuses mainly on Magento then your life
probably isn’t all flowers and bees. Magento is extremely rich
Unlike good old WordPress that “every kid in the block” knows eCommerce platform, but its main downside IMHO is its size
how to create a plugin for, Magento is a whole new system. It and code complexity. If you download Magento via SVN, you
requires extensive knowledge of OOP, ORM’s, MVC, and few will sound find out it has around 11 600 and more files. This
other stuff. This is why not “every kid in the block” can write a is no small figure. Transferring that much of files over the
module for Magento, and this is why I love it. However, unlike FTP can be a real night mare. Luckily we have SSH and tar
WordPress, Drupal and other community driven systems out command to handle this really neat.
there who keep in mind backward compatibility things with
But what about database. Today I worked on database with
Magento things are a bit different.
more than 20 000 products in store and with extremely
large number of categories. What seemed like easy database
Created using zinepal.com. Go online to create your own zines or read what others have already published. 12
September 8th, 2009 Published by: inchoo
transfer from live site to local developer machine to do a test Affiliates for all, are modules I consider loosely related to core.
and fix on few issues tunerd out to be an issue for itself. They are in one or another way connected to Magento but they
Without further delay, here is my favorite tool to handle all are self standing, independent, applications.
database related work from now on: Navicat. Installation of Affiliate module is a trivial task. It mostly
Among my favorite features is the Data transfer. Directly comes down to extracting downloaded archive file to a web
moving one database to another among different MySQL accessible directory (to your server, hosting) and configuring
servers works like a charm. I find yourself strangled among the config.inc file. (For security reasons, try renaming
often database recommended action I suggests you test the the config.inc to config.inc.php, plus changing the /lib/
trial version of this tool. bootstrap.php on line 23 to include config.inc.php). After
importing affiliates.sql into the database our installation is
Here are some screenshots of Navicat Data transfer in Action.
done.
To configure Magento part, one needs to copy required files
form /carts directory of Affiliate module and then (turn off
Cache) go to System > Configuration and set the required
options. After that you can go back to your Affiliate For
All application, upload some banners and set their url links
to point to your Magento shop. When you test banner the
links (click on one of them to get you to Magento store,
then Magento store url should have a little GET variable
in url like ?ref=someNum). Now when you do the entire
checkout process, order info gets recorded to Affiliate For All
application.
If you wish to play with Affiliate For All without installing it,
you can check out the demo (just use “Admin” both for user
and password).
There are 2 comments

New Magento theme tutorial | Inchoo


There are many new Magento stores that are published
each day. If you are with Magento for a longer time, you
will also notice that many of those look similar to default
or modern Magento theme. Creating an totally unique and
custom one can be a difficult process, easpecially taking into
consideration number of different interfaces we have. This is
why many Magento developers choose to use the CSS from
one of mendioned Magento themes that come with default
installation and style those up. This is not a bad choice at all
as it speeds up the process and those default themes are very
good. But, for those of you who wish to make an extra effort,
we suggest that you to take a look at Magento Blank Theme for
a head start.
Before you get to this point, be sure to read Magento
Designer’s Guide, where the Magento design terminology is
explained in this PDF document.
Blank Theme is a sample skeleton theme for Magento designer
and a perfect way to start a new one. Let’s be honest, we will
rarely want to develop a totally new layout. We wish the header
on the top, footer on the bottom. We wish to have 1, 2 or 3
There are 4 comments columns, we wish to have boxes. Blank Theme does just that:
provides a layout, but without any heavy styling. This makes

Affiliates for all – Magento integration


it excellent base ground for a new Magento project. It doesn’t
come with default installation, so you will have to use Magento
Recently one of our clients needed and info on Affiliate module Connect to get it.
for Magento. When it comes to Magento, word “module” is http://www.magentocommerce.com/extension/518/blank-
loosely related. Sure, every module needs config files in order theme
to report it’s “connection” to Magento core. Modules like this,

Created using zinepal.com. Go online to create your own zines or read what others have already published. 13
September 8th, 2009 Published by: inchoo
Magento community member Ross gave a good review
comment:
Create a Color Switcher in Magento
This is a great theme to use for wire-framing or as a base Magento comes packed with a lot of options. But no matter
for developing a custom theme! It looks like a lot of work has how many options you put into some product you can never
gone in to slimming down the HTML and CSS, which makes cover all of them. One of such options (for now) is a color
it much easier to work with compared to the default theme. switcher in Magento. To be more precise, an image switcher
I particularly appreciate the well structured and commented based on color selection.
CSS. The only things I would want different at this stage is
Recently I’ve made a screencast on my site on this subject,
for the ‘callouts’ to be taken out (and removal of associated
with somewhat different title. The idea is to have a dropdown
media images), and for this theme to be included in the main
box from which you choose a color and based on the color
Magento download (I would even like it to be the ‘default’). 5
selection product image changes. All of this is to be based on
stars from me!
some simple javascript (in my case, jQuery).
Take a sneak peak of how does product info page looks line
Before we continue, you might want to see color switcher in
with no styling, but in finished layout. I’m sure that the CSS
action. We used this solution on our Kapitol Reef project.
wizards will find this invaluable.
First you need to upload some images to your product and
give them some meaningful names like Red, Blue, Green
depending on your product color. When I say give them
name, I mean on label values. Same goes for creating custom
attribute. You create a dropdown selection box and create the
same amount of dropdown options as you have images, giving
them the same name Red, Green, Blue… and so on. Here are
some images for you to see what I’m talking about:

There are 11 comments

Magento product view page analysis |


Inchoo
One of the most edited file in Magento is the template file
View.phtml file. Reason for this is that a lot of clients would
like to rearrange it differently on their online stores. Here is
the analysis of that file and the list of all the methods it uses.
One thing to keep in mind, this document shows you the
View.phtml block file and shows you it’s inherited methods.
All of the Magento block files have the similar inheritance
principle. Therefore to find out the available methods all you
need to do is open up the extended (inherited) classes.
If you are using some smart IDE solution like NetBeans 6.5
with PHP code completion support, you can simply do the
Mage_Catalog_Block_Product_View-> and press the Ctrl +
Space to get the dropdown list of all the available methods.
If that’s not the case, then you will how to do the things the
manual way.

Created using zinepal.com. Go online to create your own zines or read what others have already published. 14
September 8th, 2009 Published by: inchoo
After this is done we go to the code part. There are three things After some additional styling you can get some impressive
you need to do here. results for this. Hope you find it useful.
Upload the jQuery and save it into the /js/jquery/jquery.js. You can see complete screencast at:
One important note on jQuery; for some reason I had to use http://activecodeline.com/wp-content/uploads/videos/
jQuery 1.2.3 to get this example working. Latest version 1.2.6 MagentoProductColorChooser.swf
(as of time of this writing) did not work. You can see the exact
error it gave me on my screencast. There are 28 comments
Now you need to modify /template/page/html/head.phtml

Magento’s Onepage Checkout in a


file to include the jQuery script (or any other if you can code
the same logic into it) and write down few lines of JS to
do the switching (you can download my version of file here
head.phtml)
nutshell
And finaly, you need to modify the /template/catalog/ For the last two days I’ve been working on a custom checkout
product/view/media.phtml file to grab all of the product page for one of our clients. Basicaly a page can be shown
images and dump them into some div. Here is my sample in Magento using simple Core_Template type. Basically all
(media.phtml) so just copy paste the code. code is set inside the .phtml file so it can be shown on every
possible page or block, meaning it’s object independent, no
And some additional screenshots for you to see final result
inheritance. Something you can call from with your layout files
like
To complete my work, I had two mayor requirements. One
was to manage my way around programmable adding a simple
products to cart, plus their quantity and other was to do
checkout with items in cart. Checkout was to be made with
predefined payment method as well as shipping method. After
reviewing a lot of Magento’s code involved in checkout process
and process of adding products to cart and so on I’ve put
together what I see as the most short example one can use to
do a checkout with such predefined conditions.
If you have such special requirements for your site below is the
code that you can place on whatever file you wish and include
it yout tempalte as block type core/template.
Where ubmitCustomCheckout is the name of the submit
button or submit input field. To extract addresses you can use
something like

Magento official documentation


download
We were among a few of the studios to receive the early release
of the Magento documentation before it’s official release date.
We broke the embargo ’cause we just didn’t have the heart
to keep it to our selves, we all now how painful it is to work
without it.

Created using zinepal.com. Go online to create your own zines or read what others have already published. 15
September 8th, 2009 Published by: inchoo

Designer's Guide to Magento PDF There are 4 comments


download | Inchoo
Magento Installation with SVN or Wget
After many developed CRE Loaded’s online stores and
watching Magento development progress for quite some time, Unix command | Inchoo
I decided it was time to use Magento with my next client. My Those of you who know what SVN is, feel free to skip this
starting point for development was official Designer’s guide. article. Those of you who are not familiar with SVN, this is
I’m the type of guy who likes to have documents nice&clean, a must-read. If you use standard FTP to upload all Magento
so I tried to print it but print was a mess. That’s when I decided files, you may find this process very time consuming. Magento
to create PDF of the official documentation for easy print. This 1.1.8 has over 6.700 files in over 2.200 folders. FTPing can
is probably the best starting tutorial for creating a fresh new sometimes take few hours on some servers. Let’s look at
Magento template. alternatives.
I plan to write a short related tutorials in the days of 1st Both alternatives require SSH access to the server. I’m aware
Magento development project, so I invite you to subscribe to that some low quality webhosting providers do not provide
RSS if you wish to be posted. you with SSH info immediately. If you don’t have SSH info,
ask webhosting support. If they don’t give it to you, change
Custom admin theme in Magento webhosting provider. Make it a rule, you’ll make your life
much easier.
As mentioned on Magento forums the easiest way to achieve
Get yourself familiar with basic UNIX commands first.
this is with overriding adminhtml config with your local
custom one and activate it as module. Alternative 1: SVN
This is just a small example of different approach with Admin In the Downloads tab on Magento website, you will notice SVN
Theme config option in admin panel, to show you how things page link:
can be done in different ways in Magento. http://www.magentocommerce.com/svn
Follow directory structure, copy files to their place and you will You can see how short this page is. You have 2 commands
notice new “Admin Theme” option in System->Configuration- you can run at SVN. You can chack latest work in progress or
>General->Design (Default Config scope). Your theme goes you can checkout latest stable version. If you are starting to
in app/design/adminhtml/default/yourthemename folder. It develop a real project, you will probably want a stable version.
doesn’t need to be whole theme of course, just the files you’re
changing. Let’s look at the original command:
svn checkout http://svn.magentocommerce.com/

Disabling wishlist functionality


source/branches/1.1
This is probably not the exact command you wish to run on
If like many of the Magento store owners you find that some of the server. It will place the files in trunk folder. I will assume
the built-in features are not useful to you or to your customers two things:
you can always disable them via the admin interface buy
disabling their respective modules. 1. You will want the clean code
Wishlist is not one of them. 2. You will want to specify the folder where you wish
Magento to be installed
To remove all of the traces of the wishlist functionality you
need to do the following: If those are correct assumptions, you will want to run a
1. Go to the Admin interface (select the appropriate scope) command similar to this one:
and under System -> Configuration -> Customers -> Whishlist svn export --force http://
select “No” under the “Enabled” in the General options. svn.magentocommerce.com/source/branches/1.1
shop
This will remove all of the whishlist links in the magento blocks
as well as the whishlist itself. • svn – This is the command
2. Just to make things perfect you should • export - The difference with checkout is that with an
check the (yourskinname)/template/catalog/product/view/ export, you get a clean copy of the code, and none of
addto.phtml and remove the “pipe” character from that file so the subversion metadata, so it can’t be used to svn up or
that it doesn’t disturb the looks of your site make further changes.
3. Finally, since you do not need Whishlist anymore it is wise to • –force – you will overwrite all of the folders and files if
disable it’s respective module output thru the admin interface they exist
(Go to: System -> Configuration ->Advanced->Advanced and
set disable “Mage_Whishlist” ) • http://svn.magentocommerce.com/source/
branches/1.1 - this is SVN URL. Leave it
That’s it. Your whish is Magento’s command. intact.

Created using zinepal.com. Go online to create your own zines or read what others have already published. 16
September 8th, 2009 Published by: inchoo
• shop - the name of the folder you wish to place the files After you’re done with setting your new templates save the
into. You may set the folders name to your likings. configuration by clicking on the “Save config”.
That’s it. Wise thing to do now would be to check how the
Read more about SVN at Wikipedia SVN Page and Subversion
emails look when received so make a test purchase to verify
official site.
everything is the way it should be.
Alternative 2: Installing via wget There are 3 comments
I will not be very descriptive here. This alternative is very well
explained on Magento website in Wiki section:
http://www.magentocommerce.com/wiki/groups/227/ Bestseller products in Magento
installing_magento_via_shell_ssh Bestseller or best selling product is one of the features people
Both scenarios will only place files. You still need to run web tend to ask for when it comes to Magento™.
based installer afterward. But, that is another story. There are multiple ways to implement this feature.
There are 6 comments In this example, I’m not using controller or model directories
at all; I’m going to show you how to implement this feature

Custom Transactional Emails


using only one file: the View.

Since transactional emails are very important for the process Basically, what you need to do is to create the directory inside
of online shopping you need to have them set up just the you your template directory and place the bestseller.phtml file in
want them and the default templates just don’t cut it. You it. In my example, I’m using the custom-created directory /
need your own logo, email data and custom verbiage to be inchoo. All of the screenshots provided here are based on that
consistent with the image of your company. directory structure.

Here how it’s done : Adding this feature to your store is a matter of two simple
steps:
1. Creating custom transactional e-mails via Admin
a) In the admin panel of your magento installation go to: • copy bestseller-phtml file to your directory
System->Transactional Emails • display the block on home page
You’ll be presented with a list of default emails. You’ll need
To add a block to a home page, you simply log into the
to create a custom email so the only way to avoid writing our
Magento, CMS > Manage Pages > Home. Then add the
custom templates from scratch is to use the existing code of
following to the content area:
the template.
Hint: If you want to see the template before copying, first click {{block type=”core/template” template=”inchoo/
on the “Preview” button on the right. bestseller.phtml”}}
b) To create the new template click on the “Add new template” Notice the type attribute. I used core/template which means
above the “Transactional Emails” list. This is the part where you can place this code anywhere in your site and it will work.
Magento helps you with the option to load a deafult template Code does not inherit any collection objects from controllers
for you to customize. Nice feature indeed. since it has none. All that is necessary for the bestseller.phtml
to work is defined in that single file.
Once you have loaded the deafult template give it a unique
name under the “Template name” input field by adding a
prefix of your own but leaving the deafult name as well.
Example: ” mysite :: New account “.
That way you can easily spot them in the long list of default
and custom emails.
Afterwards you can easily customize the verbiage and styling
within the “Template subject” and “Template content”.
The “Template content” is the body of the message that the
user will recieve upon transaction so be sure to change the E-
mail, name of the company etc. You’ll need to upload the logo
of your company in the images folder of the skin you’re using.
Once you are done with editing, save the changes and repeat
the process for the rest of the email templates.
2. Assigning the templates to different stores and storeviews
Assigning is the easiest part. Just go to the System One more thing: If you study the code in bestseller.phtml file
> Configuration > Sales > Sales Emails and select the you will see, at the very top of the file, the part that says: $this-
corresponding template minding the configuration scope. >show_total.

Created using zinepal.com. Go online to create your own zines or read what others have already published. 17
September 8th, 2009 Published by: inchoo
If I were to write • Support for Downloadable Products. (to see this new
product type in action visit the Magento Demo Store. We
{{block type=”core/template” show_total=”12″
added an example of an MP3 product and an eBook )
template=”inchoo/bestseller.phtml”}}
• Added Layered Navigation to site search result page,
in my home page, then $this would be assigned property
show_total with a value of 12. with control on the attribute level to include or exclude
attributes used on the search results page.
• Improved site search to utilize MySQL fulltext search
• Added support for fixed-taxes on product level for such
taxes as “State Environmental Fee” in the USA and
“WEEE/DEEE” in the EU.
• Upgraded Zend Framework to the latest stable version
1.7.2
• Added a Layered Navigation Cache for improved
performance of large catalogs (currently in beta and is
NOT recommended for production use).

If you need to upgrade existing Magento version through the


Magento Connect Manager to 1.2.0.1, follow this steps:

• Do NOT use your live or production site. We suggest


Therefore, the provided bestseller.phtml file provides the making a copy of your site and upgrading that copy first.
option of setting the number of products you wish to see listed.
• Backup your index.php and .htaccess files (if modified)
Here is the bestseller.phtml packed in bestseller.zip.
• Log into your Magento Connect Manager.
Hope you find this useful.
• Select the ‘Setting’ tab.
There are 20 comments
• Change the Preferred State to ‘Stable’, and save settings.

Magento 1.2. is out with downloadable


• For the Mage_All_Latest package select upgrade.
• Click on the ‘Commit Changes’ button. The upgrade
products | Inchoo should start.
Just at the dawn of 2008, Varien launched a new version • After upgrade is complete click on the ‘Refresh’ button.
of Magento: 1.2. Upgrading previous Magento versions was • Copy your original index.php and .htaccess files back (if
sometimes not an easy task since Varien used to change needed)
standard function names which caused themes to break. We
backup the site, made a copy, took a deep breath, expected the • Log into your admin and rebuild search index
worse, and… Nothing The upgrade went smoothly. Wow, • You should now have Magento 1.2.0 installed.
that felt good.
Happy Magentizing
We were joking at the company today.
Zeljko: You know what’s easy in Magento? There are 1 comments
Branko: There is nothing easy in Magento!
Zeljko is an front end interface developer, while Branko is Listing out products on sale in Magento |
a programmer. Although creating Magento theme is a clear
process if you follow designer’s guide, programming is much Inchoo
more complex. Before this version, Magento upgrades used to One of my recent articles was on the subject of sorting “On
cause troubles. Hope this is over. Sale” product in Magento. The following is a cleaner and more
There is always a good practice NOT to update platform to advanced look at how—with few tricks and smart moves—you
latest version immediately. Even in this case this proved to can reuse existing Magento code and modify it to suit your
be valid. Two days after version 1.2. came version 1.2.0.1. that needs.
fixed some flaws. Keep this in mind when you wish to upgrade Product can be “on sale” in two ways:
to newest version of the platform immediately after it appears.
1. when an item has a special price assigned to it on the
individual level, or
New version sorts some issues from Magento 1.1.x versions
2. when a special promotion “covers” the item
and brings some highly requested features such as:
It is important to remember that you don’t have to set up the
special price on each product to get it to be on sale; you can

Created using zinepal.com. Go online to create your own zines or read what others have already published. 18
September 8th, 2009 Published by: inchoo
simply create a promotion rule and say something like “Set all
the products in Category X to be on sale.”
I provided few screenshots at the bottom of this article to
provide a closer look at what I’m talking about. I will not go
into too much details here since this is a bit more advanced
HOW TO, but here is the process in a nutshell:
First, create a copy of /catalog/product/list.phtml file
and name it onsale_list.phtml. Here is my version of
onsale_list.phtml file.
Second, “activate” this new file. There are few ways you can do
this. Let’s say you wish to assign this onsale_list.phtml on one
of our categories, named “On Sale,” for instance.
We then go to Categories > Manage Categories > On Sale…
select Custom design and under Custom layout update, place
the following:
product_list_toolbar
If you now go to your category On Sale, it should only show
products you have assigned to category “On sale” that have a
special price set to them.
If you now wish to apply Promotion rules to entire “On sale”
category, then you simply assign a rule to one item, and all
the items assigned to the same “On sale” category (covered by
promotion rules) will be automatically listed in the grid.
Basically, the magic is in one simple IF statement
< ?php if(($_product->special_price !== null) or ($_product-
>_rule_price !== null)): ?>
for each block that lists products.
Check out the screenshots, they explain a lot.

Hope you find a way to try this out. Feel free to provide some
feedback or additional suggestions.
There are 3 comments

Magento
After many weeks of work, our 1st Magento project hit
the Web: TeraFlex Suspensions. As the purpose of the site
Created using zinepal.com. Go online to create your own zines or read what others have already published. 19
September 8th, 2009 Published by: inchoo
in not primarily selling, but also branding and community
development, we decided to use Wordpress and Magento
combination to accomplish the client’s goals.

I know that this is not some breakthrough article, but I will


certanly create contact CMS page on all of my future Magento
projects.

The Magento portion is visible at http://www.teraflex.biz/


products/. We created an original and custom theme from Custom price filter in Magento
scratch since we did not want it to look like the default one or to
Quite a few people have asked me for a price filter functionality
have a feel similar to the default one. It was not an easy task as
that comes with Magento. Mostly, the questions are same:
the learning curve for Magento template system is quite steep
How does one put the price filter anywhere on the page? How
compared to other solutions. However, it is worth the time.
does one set it’s on price ranges in that filter? What defines
We added featured products to products page, the lightbox to default price ranges. Is it possible to set price filter for all my
products info page, and numerous styles that made this store products instead of just single category? Lot of questions. The
quite unique. answer might be simpler then you might think.
Wordpress There are two ways to approach this problem. Head trough
wall or stop and think approach.Default Magento price filter
All the menu elements outside Products tab are run by works with algoritam which functions on the following logic
Wordpress. We have stuff like:
All of these elements turn Wordpress into a feature-rich CMS 1. Find the lowest and highest price in the range of filtered
suitable for larger projects. products.

How do you like the new site? Feel free to post a comment. 2. Find what power of 10 these are in.
3. If there’s 2 or less ranges available we go one power
There are 4 comments down.

Place Contact form in CMS Page in So one approach would to be to somehow override default
price filter logic by rewriting it and embedding some new logic
Magento | Inchoo of yours. I call this one head trough wall. I’m not implying
that this is wrong approach, on the contrary this is the generic
As you know, Magento has a built-in contact form that can
solution. However it does require some more time to come up
be used for general contacts. That form isn’t part of any CMS
with.
page, you cannot edit some introduction text, you cannot
add phone numbers administration, and you cannot see the Second solution is by far more easier. It involves using simple
breadcrumbs. If you wish to edit text in that default contact HTML (could use it in your static blocks).
form, you will need to update front-end files. Luckily, there is If one wishes to use the price range filter to filter trough entire
an alternative. product collection he can simply create a subcategory under
If you are a developer, editing your contact form HTML is an the Default root category and add all of the products to it. Then
easy task. You only need to open file: we write some static html code with urls made to fire up the
app/design/frontend/default/[yourtheme]/template/ price filter.
contacts/form.phtml and you will find your way around. Let’s look at the default Magento sample data. It gies you the
However, there are cases when you would like to give your following category layout
client an option to edit some intro text, edit his phone Root Catalog (6)
numbers, edit text behind the form, etc. You are probably
guessing that it would be nice to be able to embed contact form • Furniture (6)
in some CMS page. No problem.
• Living Room (4)
Created using zinepal.com. Go online to create your own zines or read what others have already published. 20
September 8th, 2009 Published by: inchoo
• Bed Room (4) Most of this is quite selfexplanaory so, for those who need
this kind of functionality across some special pages, hope you
Notice the url link above… It wont work if you put it like http:// integrate it withouth any problems.
somesite.domain/furniture/living-room/?price=1%2C199
There are 4 comments
It wont work like that because by default you do not have price
filter functionality covering second subcategory level. What
this means is that following link wont work Magentique - Magento Showcase
Launched | Inchoo
http://somesite.domain/furniture/living-room/?
price=1%2C199
Since the first subcategory level is Furniture, and second are We launched one internal project today: magentique.com. For
Living Room and Bed Room, by default the following url will the last few months we were working almost exlusively on
work with or withoutindex.php. Magento projects. As many of you, we were also wondering
what sites are developed with it. There are very little galleries
• url: http://somesite.domain/furniture/? that give the list of Magento powered stores and that’s how
price=1%2C199 this idea was created. We present you Magentique and hope
• url: http://somesite.domain/index.php/furniture/? you like it.
price=1%2C199 Curiosity about this project is that we used Magento to develop
it. You’ll not see a shopping cart or Add to Cart buttons, but
You could therefore create simple HTML like Magento was the tool we used. Take a look at the gallery,
<select onchange=”setLocation(this.value)”> comment the sites you like. Subscribe to RSS. Share it with
<option value=”http://somesite.domain/all/? you friends. Also, we would welcome your submissions of new
price=1%2C10000″> <!– Here you place your own ranges – stores you own, you created or just the ones you like.
>
0,00 € – 10 000,00 €

</option>

<option value=”http://somesite.domain/all/?
price=2%2C10000″> <!– Here you place your own ranges –
>
10 000,00 € – 20 000,00 €
</option>

<option value=”http://somesite.domain/all/?
price=3%2C10000″> <!– Here you place your own ranges –
>
20 000,00 € – 30 000,00 €
</option>

</select>
And put it into some of the static block. Notice the links in
above HTML code. The /all part of the url is the url key of the Hi,
All category in which we added all of our products. I like your work with Magento, and i see that y’re not
Last, but not least is understanding of the “price=…” affraid of experimenting. My question is relative to http://
parametar. www.raspberrykids.com. I like the layout, especially folder tab
with ‘Description’, ‘Tags’ etc. I didnt find such a feature in
1%2C10000 – where 1 stands for first range of 10000 (last Magento. Can you explain it on Inchoo web (in some article),
number) of course, only when it isnt company secret ) Thankx. Have
or a nice day.
2%2C10000 – where 2 stands for second ranfge of 10000, Online stores on magentique.com are not only our works.
(first would be 0-10000). Magentique is the gallery that lists all Magento sites and not
only our portfolio.
So if we were to write something like
3%2C10 it would be the price range from 20-30, where 3 Regarding blog topics, we try to write about the things we work
stands for third range of tens (number 10). Firs is from 0-10, on. However, we can not cover all Magento possibilities. Hope
second 10-20, third 20-30. you agree.

Created using zinepal.com. Go online to create your own zines or read what others have already published. 21
September 8th, 2009 Published by: inchoo

Can an online store have only one product? Sure it can and <label for="lastname">< ?php echo $this->__('Last name') ?>
we give you the one that just launched. Kapitol Reef was <input id="lastname" name="lastname" class="<em/><strong>inp
founded to develop, perfect, manufacture and market a new
breed of snorkels based upon pressure-balanced breathing in <label for="useremail">< ?php echo $this->__('Email') ?> <sp
the aquatic environment. The entire focus for this company <input type="text" name="useremail" id="useremail" class="<e
is to deliver best-of-class products, starting with the snorkel. <input type="submit" name="submit" value="<?php echo $this-/
Kapitol Reef is in the market for many years and this week
they published a new site. Similar to our work on Teraflex </form>< ?php /* END OF my-custom-form */?>
project, we used Wordpress and Magento platforms for the
<script type="text/javascript">
development.
//< ![CDATA[
The request was to have an extensive online store solution var customForm = new VarienForm('<em><strong>my-custom-form<
with multiple customers groups. Those groups should have //]]>
</script>
different product prices and different payment options.
Magento seemed like a great solution for such a request, You will notice all of the input fields have one common
although the initial concern was if it might be an overkill class name, required-entry. I’m not gonna go over all of the
considering the fact we only have one product to start with? available class names here. To find available class names, try
When the development started to roll out, the concern was no going to One page checkout page, where you have checkout
more. This will work superbly. We give you the new Magento form, then simply view source and look for class names next
store that uses a combination of Wordpress and Magento. to input, radio select and other fields.
Magento portion of the site is visible from the Online Store tab. Most important thing besides assigning class names is that
little piece of JavaScript below the form. Remember to pass
form id into the new VarienForm object.
Basically thats it. Constructing the form this way, automaticaly
makes your form reuse already existing validation code, the
one that the rest of the shop is using.
There are 5 comments

CSRF Attack Prevention


If you login to your Magento admin today, you are welcomed
with message box that says:
CSRF Attack Prevention Read details !
Yesterday Magento team acknowledged CSRF vulnerability
and provided solution in a form of tutorial to change admin
path (frontName) of your Magento shop.
I find this approach strange and funny at the same time. Is
hiding vulnerability new way of fixing it? Especially since
You may also notice a styled color switcher feature we some users of French Magento forums found similar problem
developed for this project. As this product comes in various in downloader (Magento connect manager). I can confirm this
colors, we decided to spice up the product info page and style couse i tested it myself. The most funny part was that Magento
the color choosing to replace the default select box. cached my get request so i couldn’t get rid of my test alert box
There are 7 comments
Few fast tips for Magento admins:
Form Validation in Magento | Inchoo 1. Follow official Magento news, forums, updates.

One of the coolest things in Magento is a form validation, and 2. Don’t click suspicious links. These kind of attacks are
the way how it’s done. Magento uses Prototype library (which, usually done through malformed links that admin clicks
personlay, I’m not a big fan of) to manage form validation. All through mail, comment, or any other source.
you need to do when writing custom form is to assign a valid 3. Clear “saved passwords” from browsers. Since most
class names to your input fields. Here is an example of how web browsers offer to remember passwords, and then
your custom form might look in order to get use of automatic autocomplete them, these kind of attack could easily stole your
form validation. password.
<form name="<em><strong>my-custom-form</strong>" id="my-custom-form" action="" method="post">

<label for="firstname">< ?php echo $this->__('First name') ?> <span class="required">*</span></label><br />
<input id="firstname" name="firstname" class="<em/><strong>input-text required-entry</strong>" />

Created using zinepal.com. Go online to create your own zines or read what others have already published. 22
September 8th, 2009 Published by: inchoo

There are 4 comments This really depends on your server configuration, however
it’s always good to restore permissions to defaults if they are
changed to 777, just to be sure.
Magento Connect
One of the first things that really confused me when i Magento™ and Google™ Website
start using Magento is Magento connect. I just started
learning things, so i was looking for some plugin examples. I Optimizer
visited Magento connect page with extensions and looked for I attended a webinar yesterday called “Maximizing Magento
download button, instead i found “Get extension key” one. Webinar: Optimizing Conversions with Website Testing.” It
If i recall correctly their What is this? explanation wasn’t the was a nice and informative hour-long webinar with Google and
same back then .. or i was just so terrified of Magento at start Magento team speakers that provided us some really useful
that i didn’t understand anything at that point I knew i information.
need to paste that key somewhere, in something they called First of all, you should know what Google Website Optimizer
my Magento connect manager or Magento downloader, but i is. It’s a powerful tool that allows you to test various page
didn’t understand where it is. concepts directly on your visitors and see which of your ideas
Visit Magento connect page. There are really some great works best in practice.
extensions there and many of them are free. The idea behind Google Website Optimizer is “You should
Find extension that interest you, click “Get extension key”, test that.” If you have an idea you don’t know will work—or
agree with license agreement and get key. Pay attention to whether it will increase you conversions—Google has created
Stability description field (stable, alpha, beta). this tool to help you test it.
Google Website Optimizer is easily integrated in Magento.
You can test various changes on your product pages and see
which ones work best for your visitors. Only product page
integration between Magento and Google Website Optimizer
is made for now, however according to Roy Rubin, we can
expect integration with our shopping cart and checkout pages
soon.
What Google Website Optimizer does is serve different
variations of your site to the visitors so that you can test which
one converts best. You can set up easily “A-B compare” where
you serve half of your visitors one page variation and half
of your visitors another. Then all you have to do is compare
results or set up multiple page variations. The Optimizer gives
you nice, clean reports where you can see how are your page
variations performing. To learn more about conversion rates,
read how to improve your web shop conversion rates.
TIPS:

• Run the tests for at least a week or a sample of 10,000


visitors or more. You can’t know if the page variation is
actually good if your test sample was too small.
• Do the big changes first, then fine-tune later. This
one comes from the Google and their experience with
If you click Settings tab of your connect manager you will see Website Optimizer. You should first try to make big
“Preferred State” option there. If you’re installing extension differences and see in which direction has the response
with different “stability” or you get something similar to you want, then refine the pages for optimal conversions.
If you can’t see the change in first five seconds of viewing
you should change this option to appropriate one. You should the page variation, the change is too small.
of course be careful with alphas and betas and know what
you’re doing. • Beware of HiPPO! This one also comes from Google.
HiPPO stands for Highest Paycheck Person’s Opinion.
If you are developer or just interested, ftp to downloader/ When you have powerful tool such as Google Website
pearlib/download after you install extension and you’ll find Optimizer, you can actually test all the ideas and see
packed downloaded extensions there. which one makes you the most money. HiPPO will often
After you use the downloader do you need to change the folder want to serve his visitors his idea—despite the fact that he
permissions back for security reasons or is it OK just to leave could earn more by serving them some other variation.
them at 777?

Created using zinepal.com. Go online to create your own zines or read what others have already published. 23
September 8th, 2009 Published by: inchoo

There are 1 comments wonder where did I pool the number “11″ from?
If you open your database (with any tool), and go
to sales_order table, you will notice entity_type_id
Extending Order object and hooking on column. Each and every entry in sales_order table
event in Magento has the same value for entity_type_id column. In my
Magento installation, this value is “11″. Keep in mind
One of my previous articles was a Magento Event Hooks. that this does not have to mean yours will also be the
This one will be a practical example on using the event same.
hooks. Although the more proper way would be to call them To confirm everything went ok, just Search the database
Observers, bare with me. I’m use to this “hooks”. for the “inchoo_custom_info” (or whatever you used for
Here’s the walk-trough on how to add a new property attribute name).
(attribute) to an object (Mage_Sales_Model_Order object in
our case). Ok, now that we added new attribute (property) to Order
object, we will go on to Observer part. We will create a
To add an attribute to object, we need (the dirty way) 2 little hook that will watch for successfull checkout process and
steps trigger appropriate code execution. In my example I needed
to add some extra info to order upon it’s successfull creation.
• Go to app/code/core/Mage folder. If you drill down
Meaning as soon as checkout process is successfully executed,
into most of the folders and go to /Model subfolder
order is stored in database with some extra info I saved in its
there you will see /Entity subfolder under /Model for
previously created field “inchoo_custom_info”.
most of the stuff (modules) under /Mage. For our
example we go to app/code/core/Mage/Sales/Model/ Here is my Observer file, I called it Observer.php and
Entity/Setup.php file. This Setup.php file holds Objects it’s saved under app/code/local/Inchoo/HookSystem/Model/
fields definitions in database. We need to add new fields Observer.php.
to public function getDefaultEntities(). Once again, this
< ?php
is the “quick” and “dirty” way of adding new attributes.
The “propper” way would be to create the sql file and class Inchoo_HookSystem_Model_Observer
update config file to read the new sql file and… Whatever, {
I haven’t got the whole day Here is the code in my /**
* Event Hook: checkout_type_onepage_save_order
example, that I added to the array in public function * @param $observer Varien_Event_Observer
getDefaultEntities(). */
'inchoo_custom_info' => array(
'type' => 'text', public function hookToOrderSaveEvent()
'backend' => '', {
'frontend' => '', /**
'label' => 'Extra info', * NOTE:
'input' => 'textarea', * Order has already been saved, now we simply add some stuff
'class' => '', * that will be saved to database. We add the stuff to Order
'source' => '', * called "inchoo_custom_info"
'global' => */
Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_STORE,
'visible' => true, $order = new Mage_Sales_Model_Order();
'required' => false, $incrementId = Mage::getSingleton('checkout/session')->getLa
'user_defined' => false,
'default' => '', $order->loadByIncrementId($incrementId);
'searchable' => false,
'filterable' => false, $extraInfo = array(
'comparable' => false, 'shirt_color' => 'Freakin cool blue color',
'visible_on_front' => true, 'developer_is_freak' => true,
'visible_in_advanced_search' => false, 'coded_by' => 'Branko Ajzele, Web Application Develop
'unique' => false, );
),
$extraInfo = serialize($extraInfo);
Basically you can copy-paste some existing attribute that
$order->setData('inchoo_custom_info', $extraInfo);
suites you the most and just change the array key name.
$order->save();
• Run this code only once (you can place it inside any file,
like index.php or view.phtml or any other that you will }
}
execute) then uncomment or remove this code.
Since
$setup = new Mage_Eav_Model_Entity_Setup('core_setup'); this is a module, we also need to add some config
$AttrCode = 'inchoo_custom_info'; files. Here is the content of my app/code/local/Inchoo/
HookSystem/etc/config.xml
$settings = array('position' => 1, 'is_required' => 0);
$setup->addAttribute('11', $AttrCode, $settings); < ?xml version="1.0"?>
<config>
NOTE: In code above, note the line $setup-
>addAttribute(’11′, $AttrCode, $settings). You probabily
Created using zinepal.com. Go online to create your own zines or read what others have already published. 24
September 8th, 2009 Published by: inchoo
<global> avoid editing the default one). You can download Admintheme
<models> module here.
<hooksystem>
<class>Inchoo_HookSystem_Model</class> Important: Our colour highlighting plugin on this site seems to
</hooksystem> lower-case some tag names on xml code, so keep that in mind
</models>
</global>
if you experience some trouble with sample code.
Huh, we are done! Final result is shown on image.
<frontend>
<events> Cheers…
There are 8 comments
<checkout_onepage_controller_success_action>
<observers>
<hooksystem_order_success>

Happy 1st birthday Magento


<type>singleton</type>
<class>hooksystem/observer</class>
<method>hookToOrderSaveEvent</method>
</hooksystem_order_success> Magento celebrates his 1st birthday today and we wish to
</observers> congratulate them for the first successful year. In this year
</checkout_onepage_controller_success_action>
Magento evolved to fully usable online store application
</events>
</frontend> and reached version 1.1. Over 425,000 downloads makes
it the fastest growing ecommerce platform on the market.
</config> Community presented over 165 extensions via Magento
Connect, but the real number of add ons is much greater.
And one more config file to add to app/etc/modules/ Inchoo and Surgeworks will keep you posted for about further
Inchoo_HookSystem.xml. development.
< ?xml version="1.0"?>
<config> Unprintable Content (Video, Flash, etc.)
<modules>
<inchoo_hooksystem>
<active>true</active>
<codepool>local</codepool> Internal Server Error
</inchoo_hooksystem>
</modules> Many of us who started experimenting with this interface and
</config> tried to place various values for Base URL, came to a dead end
where Magento breaks. Usually, we get Internal Server Error
And for the final step, open the app/design/adminhtml/ 500 with each page load. The problem lies in the fact that we
default/mytheme/template/sales/order/view/tab/ can no longer open the Magento administration to correct the
info.phtml file and add the following to it: error. What needs to be done in such a scenario?
One of our clients wrote me
< ?php /** START CUSTOM Coded by Branko Ajzele | branko.ajzele@surgeworks.com a message today:
*/ ?>
< ?php
/** I have put www.mydomain.com in a bad spot.
* NOTE: I changed the base URL to {{base_URL}} and
now im getting
* 'inchoo_custom_info' assumes you have added new attribute/property a 500 entity
to Sale/Order server error on both
the front end and the admin panel. I have
* Please use serialize and unserialize with 'inchoo_custom_info'
*/
$extraInfo = $_order->getData('inchoo_custom_info');
looked through the database and cannot find
?> the right field to change this value back. Can
< ?php if($extraInfo != null or !empty($extraInfo)): ?> you point me in the right direction?
< ?php $extraInfo = unserialize($extraInfo) ?>
<div class="entry-edit"> The client went to System> Configuration> Web> Unsecure
<div class="entry-edit-head"> and placed an invalid value for Base URL field. Beware of this
<h4 class="icon-head head-products">Extra order info</h4>field. Unfortunately, Magento just updates it without any pre-
</div> warnings, but change of this specific value can cause Magento
</div>
to crash.
<div style="height: 30px; padding: 10px; border: #ccc 1px solid; margin-bottom: 20px;">
<pre> Usually, we get an error that looks like this:
< ?php print_r($extraInfo) ?>
</pre> The server encountered an internal error or
</div> misconfiguration and was unable to complete
<br /><br /><br /><br /><br /><br /><br /> your request.
<div class="clear"></div>
< ?php endif; ?> Please contact the server administrator,
webmaster@mysite.com
< ?php /** END CUSTOM Coded by Branko Ajzele | branko.ajzele@surgeworks.com */ ?> and inform them of
the time the error occurred, and anything you
Feel free to remove all my comments. One thing to keep in
might have done that may have caused the
mind here, the url path has the “mytheme” pointing to my
error.
custom theme. Usefull if you do not wish to edit default admin
tempate files. Cooworker and friend of mine, Ivan Weiller, More information about this error may be
wrote a nice little plugin for switching the admin themes (to available in the server error log.
Created using zinepal.com. Go online to create your own zines or read what others have already published. 25
September 8th, 2009 Published by: inchoo
Additionally, a 404 Not Found error One of the projects I was assigned few weeks ago had a great
was encountered while trying to use an amount of products, total of 46 268 to be more precise. Most
ErrorDocument to handle the request. of these are simple products with “Visibility”:”Nowhere” and
are used strictly as Associated products in some Configurable
The client was on right path to find a solution. We need
products. Configurable products are for the most part shown
to open MySQL (usually via php MyAdmin) and find
to the user on frontend. All in all, there is a handful of
core_config_data table. Once there, manually update 2 rows:
Configurable products in the system, each holding couple of
1. config_id:3 web/unsecure/base_url => http:// thousands Associated product.
www.mydomain.com/ There are two issues here. First and most annoying issue I
2. config_id:4 web/secure/base_url => https:// came across in this “WTF” configuration is the performance.
www.mydomain.com/ Complete collapse of any reasonable execution time. Loading
a page that holds this kind of Configurable product takes
Everything should work now. Hope this will help someone. from 3-9 minutes, both on frontend and backend. I’m talking
about 3-9 minutes on local machine with maximum resource
There are 1 comments settings for PHP and MySQL. Second issue here is obvious
misunderstanding of Magento product types and how to use
How to fully disable (turn off) Magento them.

module I have already done Magento project with the approximately


same total number of products in system. Number of products
Although the title might sound silly and so easy, there are lot itself does not impose that much noticeable performance
of people having difficulties with this. At first turning Magento drop if the products are used the “smart way”. By “smart
module can be easy as going trough System Configuration way” I think in terms where you have wast amount
> Current Configuration Scope > Advanced > Advanced > independent Simple products. Magento can handle that quite
Disable Module Output. However, be very careful, this action well. However, having large amount of relations like those
only disables module output as it says. If your module uses, Configurable Products > Associated Products can kill your
let’s say some Observer functionality to hook into some part of store to “usability equals zero”.
the system and does some overriding then those actions won’t Here is where I draw the line on developers part. If you
be disabled. are lucky enough to get working on a new Magento related
do you have a solution to fully disable a Module just for project from scratch you are obliged to recognize these kind of
a specific Website, Store or View? It’s a Problem I’ve been issues and react on time. Change the approach to the way how
having for a while. An just disabling the output doesn’t do the products need to be presented in the system and so on. It is
trick. unacceptable to create thousands of Associated products just
to make them affect the final price of Configurable product.
If you need to come up with solution like this, try developing
Magento site owners: Get serious, focus a custom module to work around the issue not go with it.
on what matters the most Performance drop is guarantied in cases like above. So if the
client comes with the idea like “I have a lot of products that
For the last year or so I have been actively involved in kind of fall into the category of Configurable products that can
online store development based on Magento ECOMMERCE use this and that as Associated product to stay dynamic in that
platform. Everyone involved in Magento development can tell and that selection…” you need to stop, think twice how this
you that Magento extensively uses OOP approach. Although will affect store as whole and then propose the solution. No
not everyone will agree, I like the way platform has been need to blindly go with clients (owners) suggestions. His prime
architectured in the backend. Layouts and config files enable wish is to get his store working and selling with least amount
you great deal of power without even writing a line of PHP of budget as possible.
code. Its not perfect, but what is. I believe most of you heard Now lets look at the owners (clients). I’ve noticed a lot of
the “cliche”: “With great power comes great responsibility”. owners have “special” request for Magento store. Lot of them
Let’s discuss this in regards to Magento. have products that kind of fit under the category of Grouped,
There is a plain and simple message I wish to shout to current Bundled and Configurable products. This is great actually,
and future owners of Magento powered online stores: “Get since all of these come out of the box in Magento. What’s
serious, focus on what matters the most!“. not so great is that their wishes can sometimes be quite
“unreasonable”. Lets look at the “color switcher” functionality
Now what exactly did I have (and still have) in mind with
lot of people ask to be implemented. This kind of functionality
statement like this? Unlike WordPress and Drupal (no offense,
is mostly done by JavaScript where one hides select box that
I use them, I respect them) not everyone can develop quality
Magento would normally show under product options, and so
modules (extensions) for Magento. Platform itself requires
on.
developer a decent amount of knowledge from PHP OOP
and other fancy object related concepts. As mentioned in
one of my previous articles, Observers and “overrides” are
among my favorite concepts (approaches) in Magento module
development.
Created using zinepal.com. Go online to create your own zines or read what others have already published. 26
September 8th, 2009 Published by: inchoo
We realize there are already dozens of sites related to snippets
and code sharing, but none for Magento development. Site is
built on Drupal CMS. There are still lot of “styling” left to do at
the present time, but the site is usable. Branko hopes that you
will not find the site too ugly since he designed it We all love
the simplicity of it that makes the code snippets highly usable.
What makes these code snippets special is that little drop
down field next to each snippet entry where you mark down
the version of Magento for which snippet has been tested for.
The search functionality is planned soon.
Hopefully this project will become handy in those situations
where you find yourself with broken Magento code for some
Sure it looks great, its looks cool but the real question is “How reason. The next step for you is to register and share a
much will it improve your selling?”. I realize the usability can feedback. Help the community by adding your own examples
be as much as important as functionality. By now, there are of code.
even some color switcher modules you can buy. However,
most of magento modules require additional work to be Here is one Snippi example:
properly implemented in order to fit the owners wishes. Due
to the complexity of Magento platform, sometimes even the
smaller changes require lot of time and effort on developer
part. This would all be great and shinny if everything would
work after the upgrading Magento store when the new version
appears. All this leaves entire development process focused on
the “little things”. I say, why not style the theme to the end
with the default Magento page setup. Why change the output
of product view page? Why not leave it default, just fully style it
to match your design. This kinf of approach would be far more
safer in terms of upgrades and in terms of bringing the project
to the end in as much as possible short timing.
What I’m trying to say, Magento comes extremely feature
rich out of the box. Development time is not free, and to my
opinion it should be focused on either building fresh, new
features for the store or at other parts of the system like
Promotions, Catalog price rules, Shopping cart price rules,
Customer groups. The latter one seem to be relatively ignored
in the big picture.
Adding features like “color switcher” could be left for latter
phase of development, the one after the site goes live. The one There are 2 comments
you are sure your store is working the way it should, its stable,
nicely styled, optimized for best performance, and quite well
structured so its relatively bullet prof on updates. Then you Advanced Search sidebar box
can start adding modules, fancy usability tweaks and so on.
I was playing a bit with that advanced search form in Magento,
There are 10 comments so i thought it would be nice touch to add it to left or right
column of the store.
Hello everybody. We are very happy to announce that Snippi Since that multiple selects were causing problems and i also
hit the net. This is a personal project of Branko Ajzele, one of had to get rid of breadcrumb, i created block which extends
our developers, that went live few days ago. He was developing Mage_CatalogSearch_Block_Advanced_Form functionality,
it for some time now and I hope it will be usable for all of you added a little javascript and packed it all to small example
Magento developers who are trying to find a solution for your module:
specific needs. Snippi is a Magento related website for sharing Unpack the rar, copy files at its appropriate place following
Magento code snippets. You can see it live on http://snippi.net directory structure, disable/enable cache to rebuild configs,
Finding a solution for specific need can be a nightmare in layouts, blocks, and you’re on.
Magento since you are faced with the process of heavy digging
through Magento forum and Magento related blogs. Very soon
you will notice that many people had the same issue as you do,
but no concrete answer. You’ll probably find chunks of code
that can help, but you’ll have to put it all together. Snippi’s goal
is to help you in this process.
Created using zinepal.com. Go online to create your own zines or read what others have already published. 27
September 8th, 2009 Published by: inchoo
google charts so it’s trying to connect to that, but everything
else will work fine.
There are 2 comments

Display Promotion
There are two unused product list blocks in Magento which
can be very useful if you push a few buttons, edit few layouts ..
1. Promotion
Block located in app\code\core\Mage\Catalog\Block
\Product\List\Promotion.php
This is basically built in featured product functionality. It
reacts to “promotion” attribute which needs to be created, so
let’s click
Catalog->Attributes->Manage Attributes->Create New
Attribute
Attribute Code: promotion
Scope: Global
CoffeeFreak – Blank Magento extension Catalog Input Type for Store Owner: Yes/No
for building main admin menu with
sidebar and tabs
My previous article, CoolDash – Blank Magento extension for
building admin system configuration area, was about blank
start-up extension for building System > Configuration admin
area. I used a lot of “funny” attribute names so that “get
around” gets some speed. This extension is somewhat similar
to previous one, except its meant to be a blank start-up
extension for building items under main admin menu with
sidebar and tabs.
Keep in mind that, once again, extension name is something I
popped out of my head while I was making myself a coffee:).
Below are two screenshots for you to see final result.
In short, this extension demonstrates the use of controllers
(router definition under config file) and widgets in Magento.
Download Inchoo_CoffeeFreak extension for Magento.
Hope you find it useful.
Label: Promotion (second tab)

Offline Magento problems Other params can be left alone, but it’s up to you of course. I
also labeled it Promotion just for this article.
I was working recently on a local server without internet
Now we need to add created attribute to attribute set, so
connection (nothing can stop us !! ) and i noticed that navigate to
Magento administration is extremely slow. Some parts of Catalog->Attributes->Manage Attribute Sets
administration took up to 10 seconds to load.
On every page view in admin Magento was trying to resolve select attribute set you’re using and drag promotion to General
widgets.magentocommerce.com address and connect to it few group for example.
times which caused time delay. His notification system was
trying to grab new message.
The solution was to disable Mage_AdminNotification module
and since i was offline i didn’t really need it. You can do it in
System -> Advanced -> Disable modules output
Some other admin parts which are using online resources will
still be slower, like Dashboard for example because it is using

Created using zinepal.com. Go online to create your own zines or read what others have already published. 28
September 8th, 2009 Published by: inchoo
<block type="catalog/product_list_random"
name="product_random" template="catalog/product/
list.phtml"/>
since it also extends product_list block, however, since it is
random product listing, that toolbar has no purpose here, so
create phtml that will suit your shop needs, based on catalog/
product/list.phtml. For example, i’m using similar Random
block to display random products in sidebar.
So long, take care, i’m off …
There are 6 comments

CoolDash – Blank Magento extension for


building admin system configuration
area
In order to speed things up with building admin sections
under System > Configuration area in Magento I wrote a
Now when you’re editing your products, there is new little blank extension. Hopefully its a step or two beyond
“Promotion” option under General tab. “Hello world” level. I named the extension “CoolDash”,
short from CoolDashboard. Name holds no special meaning,
just something I popped out of my head. First thing you
might notice when you open config.xmls and system.xml
is the attribute naming. I intentionally used names like
“somecooldashmodel2″. I found it extremely difficult, error
prone and annoying to get around in scenarios where different
areas of config files use same names for attributes with
different meaning, like “customer”, “catalog” and so on.
Hopefully my “funny” naming scheme in config files will give
you a better overview on where everything goes. Below are few
screenshots to see the result.

How to override Magento model classes?


Many times we need to implement new functionality of
existing Magento core classes, but we don’t want to modify
core classes.
For controllers, that’s quite easy. Usually we can copy
controller from core and put it in the same place in local
Products on which you select Yes will be shown on promotion directory, modify class and that’s it.
block which can be displayed through layouts with Of course, there are better ways to do that (make module),
<block type="catalog/product_list_promotion" but I’m not going to write about that right now since it is not
name="product_promotion" template="catalog/product/ subject of this post.
list.phtml"/> I only mentioned that because we can’t do same thing for
or as cms content with models even if we want to, so how to override Magento models
without modifying core files?
{{block type='catalog/product_list_promotion'
template='catalog/product/list.phtml'}} Fortunately, that’s very easy =)
Let’s make one extension of that kind!
This attribute should really be included in default attribute set
or in Magento sample data. Extension we are going to make will be useless, only difference
between this extension and original class will be class name
2. Random var_dump =)
Block located in app\code\core\Mage\Catalog\Block
\Product\List\Random.php What we are going to do now is to take a random model class
from Magento core.
This block loads random product collection from current Let it be Mage_Wishlist_Model_Item located in app/code/
store. core/Mage/Wishlist/Model/Item.php
The fastest way to display it would also be something like
Created using zinepal.com. Go online to create your own zines or read what others have already published. 29
September 8th, 2009 Published by: inchoo
What we want to do is to add new functionality to that class, • It’s free. – This one is a no-brainer, you don’t need to
so let’s make new module. invest any money in it.
Call it Inchoo_Wishlist. • It’s fast. – You don’t need to wait for it to be finished, you
just download it and use it.
Create app/code/local/Inchoo/Wishlist/model/ directory
and copy app/code/core/Mage/Wishlist/Model/Item.php • It works. – Most of the free Magento themes work just
there. fine with Magento out of the box.
Now, rename class Mage_Wishlist_Model_Item to
However, truth be told, I believe the cons of having a free
Inchoo_Wishlist_Model_Item. Magento theme give you enough reason to go for custom
Add this line: design:
var_dump(get_class($this)); exit(); • It’s unprofessional. – A visitor (your potential buyer)
might realize you’re using a free theme. This will make
in loadByProductWishlist method
him wonder, can he really trust your website? Is it a real
Now, let’s create Inchoo_Wishlist.xml in app/etc/modules/ company standing behind this online store? Can I really
Put this code there: give my credit card to these guys? They probably aren’t a
serious company if they don’t have money for the design
< ?xml version="1.0"?>
<config> that fits their company’s identity.
<modules> • There might be no support. – If something goes wrong,
<inchoo_wishlist>
<active>true</active>
there might be no one to help you. Magento can change
<codepool>local</codepool> a lot at upgrade and some themes might start showing
</inchoo_wishlist> errors.
</modules>
</config> • There might be no support for new features. –
Magento is constantly developing ecommerce platform
Now, make app/code/local/Inchoo/Wishlist/etc/Config.xml and new features will always be presented. Some of
file and put this code there: the free templates might not keep up with Magento’s
development and you’ll end up without the ability to use
< ?xml version="1.0"?>
<config>
some of the cool new features that rolled out, wile your
<modules> competitors with custom design will have this advantage.
<inchoo_wishlist>
• The free theme probably isn’t really optimized for best
<version>0.1</version>
</inchoo_wishlist> conversion rate. – Some free themes are done with
</modules> conversion rates in mind, however, the conversion rate
<global> optimization usually depends on your niche and targeted
<models> audience. A design and layout that works for a certain
<wishlist>
company might not be so good in converting visitors into
<rewrite>
<item>Inchoo_Wishlist_Model_Item</item> sales in your niche.
</rewrite>
</wishlist>
</models>
Custom designed Magento themes:
</global> I will not list disadvantages of custom designed Magento
</config> themes since their disadvantages are already listed as
You are done! Try to add something to wishlist! =) advantages of free themes. Here are some really important
Play with other models as well! pros for getting yourself a custom designed Magento theme:

Cheers ^_^ • Unique design that fits your company’s identity. –


This is extremely important if you’re into any serious
There are 5 comments business. Building a strong corporate identity is crucial
for establishing a recognized brand. Your online store
Free Magento Themes vs Custom will not only make you profit with the sales you make, but
it will also help build a brand image with your targeted
Magento Design audience.
This blog post describes pros and cons of having a free • Someone you can count on. – If you choose a reliable
Magento theme versus having a custom Magento design from company to create a Magento theme for your store, you
a marketing perspective. know they will be there once the Magento upgrade comes
to fix any potential problems. They will be there to help
Free Magento Themes: you change things around once the change is required
There are some pretty obvious advantages of using a free and they will be there to consult you and share their
Magento theme: experience and best practices.

Created using zinepal.com. Go online to create your own zines or read what others have already published. 30
September 8th, 2009 Published by: inchoo
• Unique features. – Your online store is specific, you are $shippingPrice = '0.00';
a member of some niche. Most niches will require some }
additional functions that Magento doesn’t support by $method->setPrice($shippingPrice);
default to make the best out of your online store. If you $method->setCost($shippingPrice);
choose to work with experienced development company,
they will be able to provide you with development $result->append($method);
solutions for your problems. This is something you can’t }
get with free or premium Magento themes. return $result;
}
There are 2 comments
public function getAllowedMethods()

Creating Custom Shipping Method in


{
return array('inchoocustom'=>$this->getConfigData('n

Magento - The Tutorial | Inchoo


}

}
In this article I will demonstrate how to write custom shipping
method in Magento commerce. Pay attention on following lines:
First we need to write our shipping method, it’s a class in folder $method->setCarrier('inchoocustom');
app/code/core/Mage/Shipping/Model/Carrier/. $method->setCarrierTitle($this->getConfigData('title'));

I called it Inchoocustom.php and it’s based on Flat rate $method->setMethod('inchoocustom');


$method->setMethodTitle($this->getConfigData('name'));
shipping method but you can developed your own class.
< ?php They determine how we will set up our method. Keyword is
‘inchoocustom’.
class Mage_Shipping_Model_Carrier_Inchoocustom In folder app/code/core/Mage/Shipping/etc/ we need to edit
extends Mage_Shipping_Model_Carrier_Abstract
implements Mage_Shipping_Model_Carrier_Interface
system.xml and config.xml in order to enable our new
{
shipping method.
protected $_code = 'inchoocustom'; system.xml:
public function collectRates(Mage_Shipping_Model_Rate_Request $request)
<inchoocustom translate="label">
{ <label>Inchoo Custom Shipping Method</la
if (!$this->getConfigFlag('active')) { <frontend_type>text</frontend_type>
return false; <sort_order>2</sort_order>
} <show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
$freeBoxes = 0; <show_in_store>1</show_in_store>
if ($request->getAllItems()) { <fields>
foreach ($request->getAllItems() as $item) { <active translate="label">
if ($item->getFreeShipping() && !$item->getProduct()->isVirtual()) { <label>Enabled</label>
$freeBoxes+=$item->getQty(); <frontend_type>select</frontend_
} <source_model>adminhtml/system_c
} <sort_order>1</sort_order>
} <show_in_default>1</show_in_defa
$this->setFreeBoxes($freeBoxes); <show_in_website>1</show_in_webs
<show_in_store>0</show_in_store>
$result = Mage::getModel('shipping/rate_result'); </active>
if ($this->getConfigData('type') == 'O') { // per order <name translate="label">
$shippingPrice = $this->getConfigData('price'); <label>Method name</label>
} elseif ($this->getConfigData('type') == 'I') { // per item <frontend_type>text</frontend_ty
$shippingPrice = ($request->getPackageQty() * $this->getConfigData('price')) - ($this->getFreeBoxes() * $
<sort_order>3</sort_order>
} else { <show_in_default>1</show_in_defa
$shippingPrice = false; <show_in_website>1</show_in_webs
} <show_in_store>1</show_in_store>
</name>
$shippingPrice = $this->getFinalPriceWithHandlingFee($shippingPrice); <price translate="label">
<label>Price</label>
if ($shippingPrice !== false) { <frontend_type>text</frontend_ty
$method = Mage::getModel('shipping/rate_result_method'); <sort_order>5</sort_order>
<show_in_default>1</show_in_defa
$method->setCarrier('inchoocustom'); <show_in_website>1</show_in_webs
$method->setCarrierTitle($this->getConfigData('title')); <show_in_store>0</show_in_store>
</price>
$method->setMethod('inchoocustom'); <handling_type translate="label">
$method->setMethodTitle($this->getConfigData('name')); <label>Calculate Handling Fee</l
<frontend_type>select</frontend_
if ($request->getFreeShipping() === true || $request->getPackageQty() == $this->getFreeBoxes()) {
<source_model>shipping/source_ha
Created using zinepal.com. Go online to create your own zines or read what others have already published. 31
September 8th, 2009 Published by: inchoo
<sort_order>7</sort_order> </specificerrmsg>
<show_in_default>1</show_in_default> </fields>
<show_in_website>1</show_in_website> </inchoocustom>
<show_in_store>0</show_in_store>
</handling_type> config.xml:
<handling_fee translate="label">
<label>Handling Fee</label> <inchoocustom>
<frontend_type>text</frontend_type> <active>0</active>
<sort_order>8</sort_order> <sallowspecific>0</sallowspecific>
<show_in_default>1</show_in_default> <model>shipping/carrier_inchoocustom</model>
<show_in_website>1</show_in_website> <name>Inchoo Custom Shipping Method</name>
<show_in_store>0</show_in_store> <price>5.00</price>
</handling_fee> <title>Inchoo Custom Shipping Method</title>
<sort_order translate="label"> <type>I</type>
<label>Sort order</label> <specificerrmsg>This shipping method is curr
<frontend_type>text</frontend_type> <handling_type>F</handling_type>
</inchoocustom>
</sort_order><sort_order>100</sort_order>
<show_in_default>1</show_in_default>
Now we need to enable our new shipping method in admin
<show_in_website>1</show_in_website>
<show_in_store>0</show_in_store> panel (System->Configuration->Shipping Methods)
And we have our custom shipping method.
<title translate="label">
<label>Title</label>
Enjoy coding.
<frontend_type>text</frontend_type>

There are 11 comments


<sort_order>2</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>

How to make TinyMCE work with Magento


<show_in_store>1</show_in_store>
</title>

CMS pages
<type translate="label">
<label>Type</label>
<frontend_type>select</frontend_type>
Latest version of Magento, as of time of this writing, is 1.3.2.3.
<source_model>adminhtml/system_config_source_shipping_flatrate</source_model>
<sort_order>4</sort_order> Latest, as well as previous versions come with “half-packed”
support for TinyMCE editor. There are however few bugs and
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
few steps that need to be handled in order to enable wysiwyg
<show_in_store>0</show_in_store>
</type> editing in CMS pages. Personally I am not that big of a fan
<sallowspecific translate="label"> of wysiwyg editors, mostly because I am developer and like to
know what I write down.
<label>Ship to applicable countries</label>
<frontend_type>select</frontend_type>
<sort_order>90</sort_order> However, most of the store owners are not developers or even
not that much technically savvy people (not that this is a
<frontend_class>shipping-applicable-country</frontend_class>
bad thing) and they could use wysiwyg editors when adding,
<source_model>adminhtml/system_config_source_shipping_allspecificcountries</source_model>
modifying content.
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>0</show_in_store> Here I will walk you trough few simple steps that will make
</sallowspecific> you enable wysiwyg editing by using TinyMCE. You can see
<specificcountry translate="label">
the screenshots of final result below.
<label>Ship to Specific countries</label>
Step 1: Download and unpack TinyMCE to root /js folder.
<frontend_type>multiselect</frontend_type>
<sort_order>91</sort_order> Two things to keep in mind here. Download regular version
<source_model>adminhtml/system_config_source_country</source_model>
(not jQuery version) of TinyMCE. This is due to the fact that
<show_in_default>1</show_in_default>
Magento uses Prototype, so we need to avoid conflicts. Second,
<show_in_website>1</show_in_website>
<show_in_store>0</show_in_store> watch out for unpack location. Your tiny_mce.js file should be
</specificcountry> accessible on js/tiny_mce/tiny_mce.js path.
<showmethod translate="label">
Step 2: Open the app/code/core/Mage/Adminhtml/Block/
<label>Show method if not applicable</label>
Cms/Page/Edit/Tab/Main.php file. Locate the
<frontend_type>select</frontend_type>
<sort_order>92</sort_order>
<source_model>adminhtml/system_config_source_yesno</source_model>
$fieldset->addField('content', 'editor', array(
<show_in_default>1</show_in_default>
'name' => 'content',
<show_in_website>1</show_in_website>
'label' => Mage::helper('cms')->__('Content'),
<show_in_store>0</show_in_store> 'title' => Mage::helper('cms')->__('Content'),
</showmethod> 'style' => 'height:36em;',
<specificerrmsg translate="label"> 'wysiwyg' => false,
<label>Displayed Error Message</label>
'required' => true,
<frontend_type>textarea</frontend_type>
));
<sort_order>80</sort_order>
and change it to
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store> $fieldset->addField('content', 'editor', array(

Created using zinepal.com. Go online to create your own zines or read what others have already published. 32
September 8th, 2009 Published by: inchoo
'name' => 'content', file. If you are using store that does not have url rewrites
'label' => Mage::helper('cms')->__('Content'), this is something that needs to be done because your
'title' => Mage::helper('cms')->__('Content'),
'style' => 'height:36em;', javascript file would not be found if you go trough link
'wysiwyg' => true, like “http://store.local/index.php/js/tiny_mce/tiny_mce.js”.
'theme' => 'advanced', Then you would get TinyMCE shown on CMS page but it would
'required' => true, be disabled.
));
As you can see, there were only three minor changes needed
As you can see, here we changed on existing attribute (download, modify, modify) to get the TinyMCE editor
(’wysiwyg’) value and added new attribute ‘theme’. working.
Step 3: Open the /lib/Varien/Data/Form/Element/ Hope this helps. Cheers.
Editor.php file and locate the method getElementHtml().
Here we change There are 3 comments

Magento Developer Toolbar prototype |


$html = '
<textarea name="'.$this->getName().'" title="'.$this->getTitle().'" id="'.$this->getHtmlId().'" class="textarea '.$th

Inchoo
<script type="text/javascript">
//< ![CDATA[
/* tinyMCE.init({
mode : "exact", I was playing with some of the Magento controller functions
theme : "'.$this->getTheme().'", today, when I saw my coworker Vedran Subotic struggling
elements : "' . $element . '", with turning the Path hints in On and Off every few minutes.
theme_advanced_toolbar_location : "top", Idea cross my mind, and here is the result Inchoo’s Magento
theme_advanced_toolbar_align : "left",
theme_advanced_path_location : "bottom", Developer Toolbar prototype.
extended_valid_elements : "a[name|href|target|title|onclick],img[class|src|border=0|alt|title|hspace|vspace|width|hei
< ?php
theme_advanced_resize_horizontal : "false",
theme_advanced_resizing : "false",
class Inchoo_Hints_IndexController extends Mage_Core_Control
apply_source_formatting : "true",
{
convert_urls : "false",
force_br_newlines : "true",
public function init()
doctype : \'< !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.
{
});*/
//]]>
}
</script>';
public function indexAction()
to
{
$hints = $this->getRequest()->getParam('hints');
$_storeBaseUrl = str_replace('index.php', '', Mage::getBaseUrl());

//Just to test retrieved url $_db = Mage::getSingleton('core/resource')->getConnection('c


//echo '$_storeBaseUrl: '.$_storeBaseUrl;
if($hints)
$html = ' {
if($hints ==
<textarea name="'.$this->getName().'" title="'.$this->getTitle().'" 'on')
id="'.$this->getHtmlId().'" class="textarea '.$th
{
<script language="javascript" type="text/javascript" src="'.$_storeBaseUrl.'/js/tiny_mce/tiny_mce.js"></script>
<script type="text/javascript"> $_db->query("UPDATE core_config_data SET value = '".$_SERVER
//< ![CDATA[ $_db->query("UPDATE core_config_data SET value = 1 WHERE pat
Event.observe(window, "load", function() { $_db->query("UPDATE core_config_data SET value = 1 WHERE pat
tinyMCE.init({ }
mode : "exact",
theme : "'.$this->getTheme().'", if($hints == 'off')
elements : "' . $element . '", {
theme_advanced_toolbar_location : "top", $_db->query("UPDATE core_config_data SET value = '' WHERE pa
theme_advanced_toolbar_align : "left", $_db->query("UPDATE core_config_data SET value = 0 WHERE pat
theme_advanced_path_location : "bottom", $_db->query("UPDATE core_config_data SET value = 0 WHERE pat
}
extended_valid_elements : "a[name|href|target|title|onclick],img[class|src|border=0|alt|title|hspace|vspace|width|hei
theme_advanced_resize_horizontal : "false", }
theme_advanced_resizing : "false",
apply_source_formatting : "true", $_url = Mage::getUrl('');
convert_urls : "false",
force_br_newlines : "true", if(isset($_SERVER['HTTP_REFERER'])) $_url = $_SERVER['HTTP_R
doctype : \'< !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.
}); $this->getResponse()->setRedirect($_url);
}); }

//]]> public function cleanCacheAction()


</script>'; {
$_url = Mage::getUrl('');
As you might noticed, I used $_storeBaseUrl in this other
if(isset($_SERVER['HTTP_REFERER'])) $_url = $_SERVER['HTTP_R
chunk of code to get the valid path to my TinyMCE javascript
Created using zinepal.com. Go online to create your own zines or read what others have already published. 33
September 8th, 2009 Published by: inchoo
the WordPress and Magento. Probably everyone in web
Mage::app()->cleanCache(); development has heard about WordPress. Personaly I like
$this->getResponse()->setRedirect($_url); them, from Joomla, Drupal, Wordpress… But there is that
} little something that makes WordPress far more loving in the
eyes of the client. Not to start a flame here, lets get back to
public function cleanPhotoCacheAction() the topic. Due to the lack of the proper content management
{ in Magento those who use WordPress can easily manage the
$_url = Mage::getUrl('');
(home page in this case) content trough WordPress and make
it accessible in Magento CMS page (that you can set to home
if(isset($_SERVER['HTTP_REFERER'])) $_url = $_SERVER['HTTP_REFERER'];
page in Magento).
try {
Mage::getModel('catalog/product_image')->clearCache(); When would you like to do so?
}
Imagine you have Magento installed in root of your site
catch (Exception $e) { }
and WordPress under some folder like /articles. By default
$this->getResponse()->setRedirect($_url); WordPress is accessed via http://mysite.domain/articles and
} Magento is accessed trough http://mysite.domain. Our goal
} is to have WordPress Page (that we will title “home“) to be
accessible on http://mysite.domain.
< ?php //START INCHOO DEVELOPER TOOLBAR ?>
Here are the necessary steps involved:
< ?php
• Create a WordPress page named “home” (under url like
$_inchoo_db = Mage::getSingleton('core/resource')->getConnection('core_write');
http://mysite.domain/articles/wp-content)
$hints_are_on = $_inchoo_db->fetchOne("SELECT value FROM core_config_data WHERE path = 'dev/debug/template_hints'");
?>
• Create a file named cmswp_home.phtml under app/
design/frontend/default/
<div style="line-height: 24px; font-size: 10px; font-family: Arial, Verdana; background: #004400; border-bottom:solid
<div>
yourtheme_or_default_theme/template/inchoo/
<span style="font-weight: bold; margin-right: 10px; margin-left: 10px;">INCHOO TOOLBAR</span>
< ?php if($hints_are_on): ?> folder
• Create
<a style="text-decoration: none; color: #bbbbbb;" href="<?php a Magento CMS page (if it already does
echo $this->getUrl('inchoohints/index/index/hints/off')
< ?php else: ?>
not exist) name it anyway you want and then
<a style="text-decoration: none; color: #bbbbbb;" href="<?php echo $this->getUrl('inchoohints/index/index/hints/on')
< ?php endif; ?> add {{block type=”core/template” template=”inchoo/
cmswp_home.phtml”}} to its content
<a style="text-decoration: none; color: #bbbbbb;" href="<?php echo $this->getUrl('inchoohints/index/cleanCache') ?>">
• Set
<a style="text-decoration: none; color: #bbbbbb;" href="<?php the$this->getUrl('inchoohints/index/cleanPhotoCache')
echo newly created Magento CMS page as home
</div> page for Magento under Magento Admin System >
</div> Configuration > Web > Default Pages > CMS Home Page
< ?php //END INCHOO DEVELOPER TOOLBAR ?>
Below is the code you need to copy paste into the
< ?xml version="1.0"?> cmswp_home.phtml file mentioned in above steps.
<config>
<modules> < ?php
<inchoo_hints>
<version>1.0.0</version> /**
</inchoo_hints> * Pulls the content of post named 'home' from WordPress 'wp_
</modules> * @author Branko Ajzele
<frontend> * @license GPL
<routers> */
<ihints>
<use>standard</use> //Fetch database connection
<args> $_conn = Mage::getSingleton('core/resource')->getConnection(
<module>Inchoo_Hints</module>
<frontname>inchoohints</frontname> //Set query that retrieves the home page content
</args> //THIS GOES IF YOU HAVE WORDPRESS AND MAGENTO IN SAME DATABS
</ihints> $_findHomePage = "SELECT post_content FROM wp_posts WHERE po
</routers>
</frontend> //Set default value of home page to null, then do a safe che
</config> $_homePageContent = null;

try {
How to use WordPress home page in /*
//IF YOU HAVE WORDPRESS AND MAGENTO INSTALLED EACH IN ITS OW
Magento home page (CMS page) $conf = array(
'host' => 'localhost',
Simple : ) -Ok, lets get down to business. This one is really, 'username' => 'wordpress_db_username',
'password' => 'wordpress_db_password',
really simple, but powerful. In all it greatness Magento
'dbname' => 'wordpress_db_name'
lacks the good content management solution (CMS features). );
Lot of people are heading down the road of integrating
Created using zinepal.com. Go online to create your own zines or read what others have already published. 34
September 8th, 2009 Published by: inchoo
$_resource = Mage::getSingleton('core/resource'); visitors are able to subscribe to your newsletter via Magento
//Create new connection to new server and new databse Newsletter subscription form in sidebar.
$_conn = $_resource->createConnection('place_some_free_random_resource_name_here', 'pdo_mysql', $conf);
*/ Besides newsletter subscribers, all of your store’s registered
users will also appear in your Magento’s newsletter e-mail
$_homePageContent = $_conn->fetchOne($_findHomePage);
}
database. This database also contains information on different
store views, allowing you to easily send multiple variations
catch (Exception $ex) { of your newsletter to different store view subscribers. This
feature is extremely useful when dealing with multiple
//SEND EXCEPTION INFO TO ADMIN? language web shops.
/*
How to send a Magento Newsletter?
* USE $emailSmtpConf, $transport and $mail->send($transport); in case you need to specify SMTP manualy
$emailSmtpConf = array( Newsletter Template:
'auth' => 'login',
'ssl' => 'tls', The process of sending out Magento Newsletter starts
'username' => 'some_email@gmail.com', with creation of Newsletter Template. Once you create this
'password' => 'some_pass_here' template, the template will remain there even after you send
);
your newsletter to subscribers, allowing you to change it and
use $emailSmtpConf);
$transport = new Zend_Mail_Transport_Smtp('smtp.gmail.com', it multiple times. You can create multiple newsletter
*/ templates with different styling and test them to see which one
attracts the most response from subscribers.
$_sendTo_email = 'ajzele@somemail.com';
$_sendFrom_email = 'branko.ajzele@somemail.com';

//Notify each item author about purchase


$mail = new Zend_Mail();
$mail->addTo($_sendTo_email, 'Branko Ajzele');
$mail->setFrom($_sendFrom_email, 'Branko Ajzele');
$mail->setSubject('Invalid HOME PAGE on site detected');
$mail->setBodyHtml(' Simply click on “Add new template” button on the right and
<h1>Invalid HOME PAGE on site detected</h1> start creating your first newsletter template. You will see a
<p>There seem to be some issues with home page on your site.
screenPlease
with 5 take
fields.aAll
look at fields
of the it.</p>
are required. You will also
<p>Could be that WordPress page has been disabled and this made the query for page return null.</p>
'); notice that the largest field (”Template content” field) already
try { has some sort of code inside. Do not remove this code. This
//Try to send email code will generate the unsubscribe link for your newsletter.
//$mail->send($transport); Make sure that whatever you do this code remains on the
$mail->send();
bottom.
}
catch (Exception $ex) { When creating newsletter template for Magento, note that
//echo $ex->getMessage(); you can actually use HTML in it. This means that if you’re
}
not a tech savvy person, you can simply use some WYSIWYG
} editor and copy / paste the code it creates into your newsletter
template once you’re done. In addition, if you wish to have
?> WYSWYG editor inside your magento, check out our article on
how to use TinyMCE with Magento.
< ?php if($_homePageContent): ?>
< ?php echo $_homePageContent ?> Newsletter Queue:
< ?php else: ?>
<h1>Home page unavailable</h1> If you open this tab in the newsletter top menu, you will
<p>Seems like home page is unavailable at the moment. We notice that for
apologize therethe
areinconvenience.</p>
no newsletters in queue. In order to
< ?php endif; ?> queue a newsletter you need to open “Newsletter Template”
screen once again and in the action box next to your template
That’s it.
choose “Queue Newsletter”. This action will bring up the “Edit
If you wish to have more control over what is outputted take a Newsletter” screen. Notice that you can choose which store
look $_findHomePage variable and the query behind it. view subscribers are going to receive the newsletter. To select
Hope you find this useful. multiple store views, hold Ctrl key and left click on store views
you wish to use. (this will only be necessary if you’re using
Cheers. more then one store view).
There are 5 comments

Magento Newsletter
If you’re using Magento you probably noticed by now that
you have integrated newsletter system with it. By default,

Created using zinepal.com. Go online to create your own zines or read what others have already published. 35
September 8th, 2009 Published by: inchoo
You also need to set a Queue date start. Notices that the date and we don’t want SIDs to appear to those visitors. Most
and time you set are in fact server date and time, not your date important: We don’t want that search engines index the URLs
and time. If you wish to send your newsletter immediately, you with SIDs.
need to set it to your current server date and time or set it into

NaviGate by MerchantPlus in Magento


past.
Newsletter Subscribers Export:
Some merchants use NaviGate payment gateway from
If you wish to use some other service for sending your
MerchatPlus because of the lesser costs than its big brother
newsletter you can easily export your Magento newsletter
Authorize.net. Interesting this about this payment gateway is
subscribers via admin panel. Access the “Newsletter
its compatibility with Authorize.net. So, if you need to enable it
Subscribers” screen via top menu. On the top right you will see
in Magento, you will not have to find someone who will have to
select box with options to export your newsletter subscribers
write the module from scratch. You just need to use standard
in form of CSV or XML. Export it in a form that best fits the
Authorize.net module, but with some modifications.
import options of your other newsletter solution.
So, to use Navigate, you have to enable Authorize.net module.
Can’t send Magento newsletter? Here are some common
NaviGate is compatible with Authorize.net’s AIM Integration
problems:
method. This means that any shopping cart or online store
• Your server time is different then your local time and software that can connect to Authorize.net via this method can
you’ve actually queued the newsletter to be sent a few connect to NaviGate by following this steps:
hours in future and that’s why it’s not sent right now.
1. In the Magento Administration panel, go to
• Magento sent only small part of emails? Don’t worry, it Configuration> Payment Methods.
will send them out. Magento has integrated limit on the 2. Open the Authorize.net module and update the title
number of emails it can send at once. Eventually, all of as you see fit. Enter your NaviGate username and
your emails will be sent. transaction key, which you generate under “Profile &
Settings” in the NaviGate interface.
• You might need to activate your cron job as it’s
often a case cron job is causing you problem. This 3. Change the Gateway URL to: https://
means you will need to visit this address insert- gateway.merchantplus.com/cgi-bin/PAWebClient.cgi
your-magento-store.com/cron.php manually with your 4. Enable Credit Card Verification, if you want to use the
internet browser. CVV code.
5. Then, go to your source code and open the file: /app/

Remove SID from Magento URLs


code/core/Mage/Paygate/Model and find the string
“setCardCodeResponseCode” . Change the line to: -
with .htaccess | Inchoo >setCardCodeResponseCode($r[38]);

Many people wonder why sometimes the SID part appears in Save the file and you should be good!
their Magento URLs. This is when your URL has additional To assist your integration, MerchantPlus created the following
SID query usually at the end. Take a look at the image. The developer tools (you will not need them in our case):
curiosity is that it does not appear always. What is the most
common scenario it happens? You didn’t access the site with For more information on the connection API, see
the same domain variant you entered as your “Base URL” in Authorize.net’s AIM documentation.
your System> Configuration> Web interface.
There are 1 comments
When you decide to launch the site, you have to decide
whether you will market http://www.domain.com/ URL or Magento Flash Widgets Extension – AMF
Point
http://domain.com/. This is an important decision and you
shouldn’t change your mind quite often. Search engines
usually treat those two URLs as a different sites and therefore If you read our previous article where we made it clear we were
the Page Rank potential can be split between those two URLs. working on something interesting for Magento store owners,
So, think about whether you will use www or not and stick by you could see this coming.
this decision.
Once you decided, go to your System> Configuration> Web
interface and enter the desired form to “Base URL” field. When
you access the site you will notice that there are no “SID”s
when the URL matches the value from “Base URL” field and
they appear when it does not.
Now, we want the ability that the site redirects to proper URL
once accessed. Someone can place a wrong link to some forum
or blog. We don’t want those links to lead to improper URL
Created using zinepal.com. Go online to create your own zines or read what others have already published. 36
September 8th, 2009 Published by: inchoo

amfPoint is a Magento Extension that enables you to serve


interactive flash widgets containing your products wherever
and whenever you need them on your Magento store.

Google Analytics eCommerce data from


Magento | Inchoo
Some of you who work with Magento for a long time might
think that this topic is so clear that it doesn’t need to have an
article. We get many inquiries to finalize the work somebody
already started. One of the things we notice is that some Although Google Analytics will tell you to embed the javascript
developers tend to embed the Google Analytics code directly code on your website, you don’t have to do that. You just need
in the Magento theme files. Yes, it works and you will see the to see what is the Web Property ID of the profile. One you know
standard traffic data in the Google Analytics interface, but it it, go to the Magento administration to the interface: System>
is not a way to go. Configuration> Google API> Google Analytics. Enable it and
insert that Web Property ID. Viola.
In most of the cases, those developers edit
footer.phtml in app/design/frontend/default/[your_theme]/
template/page/html folder. As I said, the Google Analytics will
track visitors data properly, but the main issue is that the
eCommerce data will not be collected. To enable eCommerce
data to be visible, first step is that you let Google Analytics to
know that the profile is actually an E-Commerce site.
You will get to this interface by

1. Logging to Google Analytics Forums say that older versions of Magento before 1.2 do not
2. Select an account for this site properly track eCommerce data. In case you have older version
of Magento and have this issue, do not install some special
3. On the list of Account profiles, do not go to the reports, plugins. Upgrade Magento instead.
click on Edit instead
There are 4 comments
4. On the first box “Main Website Profile Information”,
there is another Edit link to the right. Click on it.
5. One there, you will see the interface similar to the one Magento CMS syntax – part1
on this image. Let Google Analytics know this is an Every Magento user noticed that there is special
eCommerce website {{magentocode}} syntax available in cms pages and blocks.
We traced a bit to find out which params are available and
what exactly they do.
As strange as this may sound, processor class that gets called is
Mage_Core_Model_Email_Template_Filter located at app/
code/core/Mage/Core/Model/Email/Template/Filter.php .
There are also some interesting directives in superclass
Varien_Filter_Template, but if i’m not mistaken, none of
them can be used.
There are six replacement codes that can be used and each
triggers its equivalent Directive function:
skinDirective

Created using zinepal.com. Go online to create your own zines or read what others have already published. 37
September 8th, 2009 Published by: inchoo
mediaDirective Example: {{store url=’customer/account’ _query_a=’8′}}

htmlescapeDirective Synonym: Mage::getUrl($params['url'], $params);

storeDirective Params:

blockDirective url = magento routers url

layoutDirective direct_url = normal url, appended to baseurl


I’ll start with easier and most commonly used and continue
_query_PARAMNAME = adds query param, for example
with advanced ones in part two of this article.
_query_a=’8′ adds a=8 to url
1. skinDirective
Description: Used to retrieve path of skin folder and its files, _fragment = adds fragment, for example #comments
theme fallback respected
Example: {{skin url=’images/image.jpg’ _theme=’blank’}} _escape = escapes “,’,<,>

Synonym: Mage::getDesign()->getSkinUrl($params['url'], custom = if using magento route url param, every custom
$params) param added will be appended like /a/8/b/10
I probably missed something in this last one, but it’s very late
Params: and i’m tired of poking through Magento

url = empty or relative file path To be continued ..


There are 10 comments
_theme = alternative theme, fallbacks if file not exist

_package = alternative package Magento FLIR


_area = alternative area(frontend,adminhtml) Facelift Image Replacement (or FLIR, pronounced fleer)
is an image replacement script that dynamically generates
_type, _default etc. = nothing useful, somebody please correct image representations of text on your web page in fonts that
otherwise might not be visible to your visitors. Let’s see how
me if i’m wrong
it behaves in Magento.
2. mediaDirective
1. Download FLIR from FLIR homepage. I was using latest 1.2
Description: Used to retrieve path of root/media folder and its stable for this article because of simplicity, but if you try you’ll
files find out that 2.0 beta also works great but requires little more
Example: {{media url=’image.jpg’}} configuration.
2. Unpack FLIR content (cache,fonts,etc.) inside skin/
Synonym: Mage::getBaseUrl(’media’) . $params['url']
frontend/default/default/facelift
I think it makes perfect sense to put it into skin folder.
Params:
3. Open app/design/frontend/yourpackage/yourtheme/
url = empty or relative file path template/page/html/head.phtml and append
3. htmlescapeDirective <script language=”javascript” src=”<?php echo $this-
>getSkinUrl(’facelift/flir.js’) ?>”></script>
Description: Used to escape special html chars
Example: {{htmlescape var=’<a <script type=”text/javascript”>
href=”www.inchoo.net”>inchoo</a><b>inchoo</ document.observe(”dom:loaded”, function() {
b><i>inchoo</i>’ allowed_tags=’b'}}
FLIR.init({ path: ‘<?php echo $this->getSkinUrl(’facelift/’) ?
Synonym: Mage::helper(’core’)->htmlEscape($params['var'], >’ }, new FLIRStyle({ mode: ‘wrap’ }) );
$params['allowed_tags'])
FLIR.auto();
Params:
});
var = string to escape
</script>
allowed_tags = comma-separated list of allowed tags If your php error reporting isn’t disabled add
4. storeDirective error_reporting(0); somewhere on top of config-flir.php. This
Description: Used to build magento routes and custom urls
Created using zinepal.com. Go online to create your own zines or read what others have already published. 38
September 8th, 2009 Published by: inchoo
is main config file from which you can define options and
custom fonts, so examine it.
Refresh your Magento store and you should see the result.
flir.js can also be alternatively included from layout files inside
head block
<reference name=”head”>

<action method=”addItem”><type>skin_js</
type><name>facelift/flir.js</name></action>

</reference>
There is nice Quick Start Guide and Documentation available
from FLIR homepage, so i won’t go in details on some
advanced FLIR settings, but here are few examples:
//pass selectors as comma separated list
FLIR.auto(’h5,h4′);

//pass an array of selectors

FLIR.auto( [ 'h4', 'h5' ] );

//replace manually with custom options

FLIR.replace( ‘div.box h4′ , new FLIRStyle({ mode: ‘wrap’ ,


css: {’font-family’:'arial’} }) ); It was made with default Magento theme. Enjoy.

//prototype way There are 9 comments

$$(’div.box h4′).each( function(el) { FLIR.replace(el); } ); amfPoint - Make your Products Rock in


Cya.
Magento | Inchoo
Magento product image switcher Something is happening. People from small town in Croatia
called Osijek are concerned about Branko Ajzele. They say that
I just wrote small javascript animation example for product he is spending too much time in front of the computer writing
images and thought someone may find it useful. It’s a fast way some code. We tried to call him many times from the office
to replace default zoom functionality for the ones that don’t but got no reply. After a discussion we drew straws to decide
like it. who will go to his place to check his condition. When I came to
his place and knocked, at first there was an absolute silence.
I’m actually trying to merge something like this with default
I knocked again…
zoom, but i’m not finished yet. Anyway, i left all javascript and
styling in media.phtml file, so just download the file After two attempts, Branko opened the door. First thing I
noticed was a Magento circle on his forehead and a red eyes.
and replace it with your own at
Branko didn’t sleep for a very long time.
app/design/frontend/default/yourtheme/template/catalog/
product/view/media.phtml “Branko, are you ok?“, I asked.
“Yes, Why? What’s going on? What date it is?”
You could feel the smell of burning plastic in the air. It was
obvious that computer was turned on for a long time. I glanced
in the room and I could see the monitor with Magento colored
light and some animations on it.
“What are you working on man?”
He just stared for a couple of seconds which seemed like an
eternity and than he finally spoke…
… To be Continued …

Created using zinepal.com. Go online to create your own zines or read what others have already published. 39
September 8th, 2009 Published by: inchoo

There are 9 comments There are 5 comments

Programatically create Magento blocks How to escape from EAV in Magento? |


and inject them into layout Inchoo
Imagine a scenario where you wish to simply create a view file One of the differences between Magento eCommerce platform
like custom-note.phtml and show this view file on some new and lets say WordPress, when looked from developer point of
url inside the Magento store. One way to do this is to create a view, is “avoid raw queries” approach. For a web application,
CMS page and call that block from within CMS page. But what Magento is massive system. His database, although not so
if you wish to create and append this block to other areas of massive but surely breathtaking with around 220 tables forces
Magento layout that are inaccessible from CMS page interface you to use “eye candy” EAV model to do even simple things.
form admin? What if I want to add new div element under the For instance, if I were to tell you that I want you to retrieve
breadcrumbs and append new block under it? 5 simple products from database that have price in the range
magento philosophy is to create block class under the /Block of 200-600USD you would most likely spent 1-4 hours trying
folder of your module, to create xml layout file under the to work out the query. In the end you would be lucky if you
theme /layouts folder (or to modify existing layout file) and so even get the query that wont break on next Magento upgrade.
on. Anyway you turn it around you either need to have Block Let me just remind you on some of the things you need to be
file or add/modify at least the entry to the layout files. careful in example above.
All this is OK if you are working on your own store so you have Your query would have to take in consideration the at least
full control over the code. However, what if you are developing the following states: is my product visibility such that it can
a module that will be used on different Magento stores. My be seen in Catalog and search result, is my product enabled or
prime concern when building a module is to keep the number disabled, is is out of stock, which website and store view has
of necessary module files to a minimum. it been assigned, is it assigned to only one category and that
category is disabled by some chance, does it have special price
In code below, you will see how easy it is to call your Core/
assigned, does it have promotion rules assigned, does it have
Template block to show on any area of Magento layout.
content (descriptions) for multilingual site assigned.
Extracted from app/code/local/ActiveCodeline/
All of those and more are questions that one has to take
CustomOutputs/controllers/IndexController.php file.
into consideration when doing raw database queries. It makes
public function indexAction() no sense to create query that fetches product and all its
{ appropriate info (price, quantity, description…) if that product
//Get current layout state is disabled or assigned to category that is disabled. For
$this->loadLayout();
instance, if you need “featured” product functionality and
$block = $this->getLayout()->createBlock( you manually create raw query that extracts one “featured”
'Mage_Core_Block_Template', product to lets say home page. There you create nice block
'my_block_name_here', holding all the necessary info of the product with a link for lets
array('template' => 'activecodeline/developer.phtml') say “Add to cart” or “View product”. Clicking one of those two
);
link would give you most likely 404 if the product is disable
$this->getLayout()->getBlock('content')->append($block); or any other condition that enables the product to be shown
is disabled.
//Release layout stream... lol... sounds fancy
$this->renderLayout(); So basically, raw SQL queries in Magento are a “no no” for
} most of the time. Too much work and you never know what
they will change in future upgrades. Which brings me to this
Most IMPORTANT thing to keep in mind here is the “error new trend of theirs which I like to call “Escape from EAV”.
handling”. If you assign a “invalid” block to ->append(), you
will not (most likely) see an error but “nothing happend”
situation.
Anyhow… hope the attached module (extension) will save you
some headaches. I know it took me few hours of tracing and
testing to get the grip of it.
Download ActiveCodeline_CustomOutputs extension.
Cheers.

Created using zinepal.com. Go online to create your own zines or read what others have already published. 40
September 8th, 2009 Published by: inchoo
custom script I wrote. After that i noticed the data in flat tables
got rebuild as well. This of course took several hours. Magento
EAV model seems OK on paper, but with store that hold’s large
number of products it simply does not work, at least not in way
in which their collection objects are built. Changes introduced
in form of flat tables in versions 1.3 should, to some extent,
improve work with stores that have large numbers of products.
However this improvement seems to come in form of “copy all
data from scattered tables to single flat table”.
Solutions like these are nightmare when it comes to upgrading
the store that already has large number of products in. System
is expected to handle part of the job transparently but it failed,
leaving the client with corrupted database.
So, a word of advice for upgrading an existing Magento store:
NEVER do it on live site. Let professional developer transfer
live site and database to his dev machine, or make a copy on
some sub folder on live site. Magento’s extreme out of the
box feature rich capabilities, open source philosophy and good
marketing have made it extremely popular but be careful, free
is such a a loose term.
I am really anxious to see the future path of EAV vs Flat model
in Magento.

EAV, also know as Entity Attribute Value was suppose to There are 8 comments
bee (or is) the next big thing in OOP. Anyhow, Magento and
his way of EAV have two huge downfalls called LACK OF
DOCUMENTATION and WHAT WILL THEY CHANGE IN
Updating options of configurable product
NEXT UPGRADE. The other day I was working on a Magento that is already in the cart
shop that had 22 000 products. Almost all of them were simple
products, just about 600 were grouped. The store was initially < ?php
if($this->getProduct()->isConfigurable()){
installed on Magento 1.2 version. Site was pretty much 95%
$_product = Mage::getModel('catalog/product')->load($this->g
complete from both graphic and development perspective. Mage::getBlockSingleton('catalog/product_view_type_configura
Anyhow, Magento version 1.3.1 was released and on client $_configurable = Mage::getBlockSingleton('catalog/product_vi
demand we decide to to upgrade. Important thing to keep $_cdata = json_decode($_configurable->getJsonConfig());
in mind is that in version 1.3 Magento introduce “change in $_current = array();
foreach((array)$this->getOptionList() as $_option) {
philosophy” concerning the EAV model. $_current[$_option['label']]=$_option['value'];
Altough EAV sounds great (and really is great for most of }
foreach($_cdata->attributes as $attribute) {
the time), it can really slow things down with all those
?>
JOINS executed on database. So the Magento team decided <strong>< ?php echo $attribute->label; ?></strong>
to do a little flat tabling. Basically we now have massive data <select style="width:150px;" name="cart[<?php echo $_item->g
duplication in MySQL where data is taken from various tables < ?php
and copied int one, the flat table. Flat tables were introduced foreach($attribute->options as $option) {
?>
for both Products and categories, in regards to various website
<option <?php echo ($_current[$attribute->label]==$option->l
and store views. < ?php
Basically Magento has the power to “on the fly” create tables }
?>
and do the “magical” copying of data from various tables to </select>
the flat tables. I assume they were looking for a faster way to < ?php
“assemble” Product objects in Magento which in turn should }
boost the speed of collection object i grew so found about. I can } else {
live with duplicated data in database, I mean I am not the one // THIS IS PLACE WHERE EXISTING CODE from [*] goes
}
writing them down. But let me get back to real world scenario. ?>
As I mentioned, store I have been working on had more
than 20 000 products. Due to limitations of both MySQL Now you are done with template and you can style it as you
and PHP failed to do Rebuilt that you can find in System wish as soon as you do few additional steps.
> Configuration > Cache management. This failure caused < ?php
corrupted data in database. This manifested with “empty”
attributes (attributes not showing up in Layered navigation). I class YOUR_FIRM_MODULE_NAME_Model_Card
resolved the issue by “re saving” all of the 20 000 product with {
public function update($e)
Created using zinepal.com. Go online to create your own zines or read what others have already published. 41
September 8th, 2009 Published by: inchoo
{ $emailTemplateVariables['myvar1'] = 'Branko';
$_this = $e->cart; $emailTemplateVariables['myvar2'] = 'Ajzele';
$data = $e->info; $emailTemplateVariables['myvar3'] = 'ActiveCodeline';

foreach ($data as $itemId => $itemInfo) { /**


$item = $_this->getQuote()->getItemById($itemId); * The best part
* Opens the activecodeline_custom_email1.html, throws in th
if (!$item) continue; * and returns the 'parsed' content that you can use as body
if (!isset($itemInfo['option']) or empty($itemInfo['option']))
*/ continue;
$processedTemplate = $emailTemplate->getProcessedTemplate($e
foreach ($item->getOptions() as $option){
/*
if($option->getCode()=='info_buyRequest'){ * Or you can send the email directly,
* note getProcessedTemplate is called inside send()
$unserialized = unserialize($option->getValue()); */
$unserialized['super_attribute'] = $itemInfo['option']; $emailTemplate->send('john@someemail.com','John Doe', $email
$option->setValue(serialize($itemInfo['option'])); ...
}elseif ($option->getCode()=='attributes'){
$option->setValue(serialize($itemInfo['option'])); And here we go again, nothing without xml files -In order
} for above piece of code to work, you need to add an entry to
your config.xml file like shown below.
}
$item->save(); ...
} <global>
} <template>
<email>
} <custom_email_template1 module="SampleModule1">
?> <label>ActiveCodeline custom email module</label>
<file>activecodeline_custom_email1.html</file>
P.S. Yes, I know… before clicking on update cart, we should <type>html</type>
have some JavaScript price changer, but this is all I have at </custom_email_template1>
</email>
this moment since I needed this on card that is autosubmited
</template>
on dropdown change. </global>
...

Magento custom emails And lets not forget the email template itself, app/locale/
en_US/template/email/
Ever wanted to “just send the email” using the built in email activecodeline_custom_email1.html.
features in Magento? Ever hit the wall trying to do something
with Magento? OK, I know the answer to the other one, just <!--@subject ActiveCodeline custom email module @-->
had to ask . Anyhow, sending the emails with Magento
<div>
turned out to be a process of “just” a few hours of tracing <h1>ActiveCodeline custom email example by Branko Ajzele</h1
Magento code. <p>Hi there {{var myvar1}} {{var myvar2}} from {{var myvar3}
</div>
I cant wait for smart comments like, “few hours, huh its
so easy…”. Yea, thats the beauty of Magento… few hours of Hope this was helpful. Cheers.
bashing your head against the wall while you are sipping the
4th cup of coffee until the solution hits you. Interesting do, just There are 8 comments
when you get the hang of it, Magento gets you this “have you
tried this” attitude . Getting started with building Admin
What am I talking about? Scenario: I want to create email
template named activecodeline_custom_email1.html, I want
module in Magento
to pass few variables to it during runtime, I want to send emails
Due to the “complexity” of Magento’s xml files, developers can
programmaticaly. I dont want to create 56 lines of xml file just
waste great amount of time on “unnecessary” things.
to call one template. When I say “complexity” I say it with purpose. XML files are
Here is how. not so complex by them selves, but due to extreme lack of
documentation and changes Magento pumps in every new
... “major” release, people are lost among things that should
/* really be sideways. Anyway, in this little article I will show you
* Loads the html file named 'custom_email_template1.html' from
how to create basic, startup structure for your module to get it
* app/locale/en_US/template/email/activecodeline_custom_email1.html
*/ shown under Magento Admin main top menu.
$emailTemplate = Mage::getModel('core/email_template')
As you can see on the picture below, I am creating a menu item
->loadDefault('custom_email_template1');
with title “ActiveCodeline_SampleModule1″.
//Create an array of variables to assign to template
$emailTemplateVariables = array();

Created using zinepal.com. Go online to create your own zines or read what others have already published. 42
September 8th, 2009 Published by: inchoo
My module is called “SampleModule1″ and it consists of just </config>
a few files. As you go over the provided config.xml file you
My “admin” controller is extremely simple, just an
will see that I used “BigLettersSmallLetters” style. I do this
indexAction() method. However it does tell a lot. Below is a
intentionally because this “naming convention” is another
code of indexAction() method.
great pitfall for developers when it comes to constructing
xml files. I know I too still struggle with “what must be the
lowercase” question. ...
public function indexAction()
Here is my example of config.xml file {
// "Fetch" display
$this->loadLayout();
< ?xml version="1.0"?>
// "Inject" into display
<config> // THe below example will not actualy show anything sinc
<modules> $this->_addContent($this->getLayout()->createBlock('core
<activecodeline_samplemodule1>
<version>0.1.0</version> // echo "Hello developer...";
</activecodeline_samplemodule1>
</modules> // "Output" display
$this->renderLayout();
<global> }
<helpers> ...
<samplemodule1>
And below are all the files required for this “Admin
<class>ActiveCodeline_SampleModule1_Helper</class> example
</samplemodule1>
</helpers>
module” to work.
</global> Note this is only example, DO NOT USE on live site.
<admin> Cheers…
<routers>
<samplemodule1> There are 2 comments
<use>admin</use>

How to create Magento AMF server


<args>
<module>ActiveCodeline_SampleModule1</module>

extension
<frontname>samplemodule1</frontname>
</args>
</samplemodule1>
</routers> I have been working on a project, in my own time, that involves
</admin> Flex – Magento communication. I decided to test Adobe’s
AMF format. In this article I will show you how easy is to create
<adminhtml>
<menu> AMF server as an extension in Magento.
So, where to we start?
<menu1 translate="title" module="SampleModule1">
<title>ActiveCodeline SampleModule1</title>
<sort_order>60</sort_order> The idea is to have special Url which will act as AMF endpoint.
<children> Since Magento is built on top of Zend, this is extremely easy
<menuitem1 module="SampleModule1">
to do.
<title>Menu item 1</title>
For your module to act as a basic AMF server you need
<action>samplemodule1/example</action>
</menuitem1> only 3 files. MyCompany_MyModule.xml that goes under
</children>
</menu1>
the /app/etc/modules/ folder. Then IndexController.php that
</menu> goes under the /app/code/local/MyCompany/MyModule/
<acl> controllers/IndexController.php. And last but not least
<resources> the config.xml file that goes under the /app/code/local/
<admin> MyCompany/MyModule/etc/ folder.
<children>
I will not go into the details and show you the full
<menu1 translate="title" module="SampleModule1">
<title>ActiveCodeline SampleModule1</title> content of each of those files. Important thing is to focus
<sort_order>60</sort_order>
on IndexController.php and config.xml files. Inside your
<children>
<menuitem1> IndexController.php file you will actualy hold the code for your
<title>Menu item 1</title> AMF server (Zend_Amf).
</menuitem1>
</children> Here is an example of indexAction from my
</menu1> IndexController.php file:
</children>
</admin>
</resources> ...
</acl> public function indexAction()
</adminhtml> {
//Create AMF server instance

Created using zinepal.com. Go online to create your own zines or read what others have already published. 43
September 8th, 2009 Published by: inchoo
$server = new Zend_Amf_Server(); develop a feature for Magento than for some other system out
there.
//setProduction(false): return exception info
$server->setProduction(false);

$server->setClass($class, $class); Magento block caching


Recently we were working on speeding up parts of client
//$server->setClassMap("SomeTypedObjectVO", "MyCompany_MyModule_Model_SomeTypedObjectVO");
$server->setClassMap($className, $class); site which had usual problem of slow page loading caused
by complicated configurable products. To solve the problem
//Run the AMF server we were experimenting with extending core Magento caching
echo $server->handle(); capabilities.
Magento
//Just in case so that Magento does not pass anything beyond thishas built in predifined system of block output
point
die; caching. Its block abstract has Zend_Cache caching
}
capabilities that can be modified for your own needs. I’m
...
showing here an example of caching whole product view block,
The above example is the simplest form of Zend AMF server i however this is just a specific example of how things works,
can think of, but it should be enough to get your AMF server problems are different and requires different approach and
responsive to AMF requests. solution.
And to make all of this accessible via Url, we need to add I will start with some external reading and example itself.
entry to congig.xml file. Below is the partial example of my There is great article on Magento Wiki about this topic, along
config.xml file. with category cache example on Magento forums.
With my Inchoo_BlockCaching.rar example module things
... should be little easier to understand.
<frontend>
<routers>
Magento block caching depends of three things:
<mymodule> cache_lifetime => cache lifetime in seconds
<use>standard</use>
<args> cache_tags => cache type identifiers primarly used for
<module>MyCompany_MyModule</module> deleting right cache at the right time
<frontname>myamfserver</frontname>
</args>
</mymodule> cache_key => cache identyfier
</routers>
</frontend>
You can simply inject this data into construtor of any Magento
... block

Above piece of code sets access to AMF server on Url like protected function _construct()
{
http://server/store/index.php/myamfserver. $this->addData(array(
Thats it. 'cache_lifetime' => 3600,
'cache_tags' => array(Mage_Catalog_Model_Product::CACHE_
There are 2 comments 'cache_key' => $this->getProduct()->getId(),
));
}
Top 5 annoying things in Magento or if you need some conditional approach like i did in this
If you ask me, there are two important things that make example define equivalent functions
Magento so attractive. First, its free and open source. Until
month ago Magento was fully free, now they have Community public function getCacheKey(){}
and Enterprise editions. But make no mistake, when it comes public function getCacheLifetime(){}
to out of the box feature list, Community edition will most public function getCacheTags(){}
likely beat any open source cart out there. Rich “out of the box”
features are the second thing that make it so attractive. because constructor approach isn’t enough in most scenarios.
There is a general misassumption about cache_lifetime. If
• Large number of files in system which makes it you set it to false, Zend cache will get default value of 7200
fully impractical to do installations and backup by seconds!! If you want infinite never expired cache set it
transferring files over FTP to 9999999999, which is Zend_Cache maximum value, or
something else big enough.
There are more to add to the list, but these are the ones that
caught my attention for most of the time. We do every day I believe that best way to activate this is to rewrite specific
Magento development, and believe me its quite hard to explain block with our own with caching enabled, like shown in
your client that sometimes it takes you 2-4 times more to example. You should always try to avoid modifying core files,
even copying modified Mage classes to local, because things
get really messy on updates.

Created using zinepal.com. Go online to create your own zines or read what others have already published. 44
September 8th, 2009 Published by: inchoo
Generated cached files can be found in usual subfolders of / <remove name="name_of_the_ol_block"/>
var/cache folder. Two files are generated, first metadata file
which contains serialized cache data and second one which is That’s it. You should now be free of product comparison for
cached html output itself. ever and ever
In my example:
There are 3 comments
mage—internal-metadatas—PRODUCT_INFO_STORE
+ID_PRODUCT+ID Magento duplicated content | Inchoo
mage—PRODUCT_INFO_STORE+ID_PRODUCT+ID Magento has several issues with duplicated content. Of course,
you don’t actually have two versions of the same content
Note that “Blocks HTML output” option needs to be enabled
in your database, however, in the eyes of search engines,
in Cache Management for this to work.
two different URLs serving same content are counted as
Many things in Magento can be cached in similar way and duplicated content and will cause you lots of problems. The
there are predefined mechanism waiting for you to use them. most obvious problem is that your page rank is leaking on
It’s possible that we’ll see more of this implemented in future different versions of virtually the same landing page. You also
Magento versions. might end up with having several versions of the same content
indexed which is bad in so many ways.
Removing Product Comparison in First duplicated content problem in Magento occurs when
you are listing a product in multiple categories. Magento will
Magento create several URLs that actually contain the same content
As many things in Magento, removing product comparison is such as:
not available thru the admin interface. Thus, leaving us with The easiest way to avoid this problem is to simply turn
the only option of getting down and dirty with theme files of the category based URLs in Magento admin panel. This
editing. way you will always serve exactly the same URL no matter
This guide is pretty straightforward and is based on the which direction user took to find your product and it will be
Magento ver. 1.3.1.1 example.com/product_name.html.

Before beginning of this procedure please Go However, you might actually want to have category based
to: System-> Cache Management and disable URLs for both usability and SEO reasons. Don’t worry, there
cache. You can turn it on after you’re done. is a solution for you here, it just involves a little more work to
do. What you need to do is put a rel cannonical on the URLs
Step 1 – reports.xml with category base pointing back to the original product URL.
Open: app/design/frontend/deafult/Your Theme name/ This probably sounds like some sort of voodoo but if you reed
layout/reports.xml and delete the following lines: about rel canonical it will be piece of cake.
This issue is also easily fixed by use of rel canonical. Simply
<block type="reports/product_compared" before="right.permanent.callout" name="right.reports.product.compared" templat
put a rel cannonical on all of the products with SID in URL,
pointing back toname="right.reports.product.viewed"
<block type="reports/product_viewed" before="right.permanent.callout" the product’s original URL. template="r

Step 2 – catalog.xml
Open app/design/frontend/deafult/Your Theme name/
layout/catalog.xml and delete the following line:
<block type="core/template" before="cart_sidebar" name="catalog.compare.sidebar" template="catalog/product/compare/si

Save the files and refresh the page you we’re checking. Product
comparison should not be there but if you click on any of the
products you ‘ll see that the “Add to compare” text link is still
there.
The way to remove it:
Step 3 – addto.phtml
Open up app/design/frontend/default/Your Theme name/
template/catalog/product/view/addto.phtml and delete the
following line:
< ?php if($_compareUrl=$this->helper('catalog/product_compare')->getAddUrl($_product) ): ?>
<li><span class="pipe">|</span> <a href="<?php echo $_compareUrl ?>">< ?php echo $this->__('Add to Compare') ?></a></
< ?php endif; ?>

Oh, of course theif you don’t want to actually delete the code
can always use the following:
Created using zinepal.com. Go online to create your own zines or read what others have already published. 45

You might also like