inchoo s magento posts

45
September 8th, 2009 Published by: inchoo Created using zinepal.com . Go online to create your own zines or read what others have already published. 1 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 blocks. This article tells what needs to be in place to create new structural block. What are structural blocks? They are the parent blocks of content blocks and serve to position its content blocks within a store page context. Take a look at the image below. These structural blocks exist in the forms of the header area, left column area, right column…etc. which serve to create the visual structure for a store page. Our goal is to create a new structural block called “newreference”. Step 1: Name the structural block Open the file layout/page.xml in your active theme folder. Inside you will find lines like: <block type="core/text_list" name="left" as="left"/> <block type="core/text_list" name="content" as="content"/> <block type="core/text_list" name="right" as="right"/> Let’s mimic this and add a new line somewhere inside the same block tag. <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.

Upload: tuyen-tran

Post on 28-Jan-2015

134 views

Category:

Documents


4 download

DESCRIPTION

 

TRANSCRIPT

Page 1: Inchoo s magento posts

September 8th, 2009 Published by: inchoo

Created using zinepal.com. Go online to create your own zines or read what others have already published. 1

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

Inchoo is an ecommerce design and developmentcompany specialized in building Magento online stores.

Boost the speed of your MagentoOne of the drawbacks of Magento is currently its speed ifdefault configuration is used. There are certain ways of makingit run faster. The best one is to enable GZip compression bychanging .htaccess file a little. You just need to uncommentpart of the code. In my case, the speed increase was exactly235%.

Add custom structural block / referencein Magento | InchooIf you already performed some Magento research, you willknow that it is built on a fully modular model that givesgreat scalability and flexibility for your store. While creatinga theme, you are provided with many content blocks that youcan place in structural blocks. If you are not sure what theyare, please read Designer’s Guide to Magento first. Magentoprovides few structural blocks by default and many contentblocks. This article tells what needs to be in place to create newstructural block.

What are structural blocks?They are the parent blocks of content blocks and serve toposition its content blocks within a store page context. Takea look at the image below. These structural blocks exist in theforms of the header area, left column area, right column…etc.which serve to create the visual structure for a store page. Ourgoal is to create a new structural block called “newreference”.

Step 1: Name the structural blockOpen the file layout/page.xml in your active theme folder.Inside you will find lines like:

<block type="core/text_list" name="left" as="left"/><block type="core/text_list" name="content" as="content"/><block type="core/text_list" name="right" as="right"/>

Let’s mimic this and add a new line somewhere inside the sameblock tag.

<block type="core/text_list" name="newreference" as="newreference"/>

Good. Now we told Magento that new structural block existswith the name “newreference”. Magento still doesn’t knowwhat to do with it.

Step 2: Tell Magento where to place itWe now need to point Magento where it should output thisnew structural block. Let’s go to template/page folder in ouractive theme folder. You will notice different layouts there.Let’s assume we want the new structural block to appear onlyon pages that use 2-column layout with right sidebar. In thatcase we should open 2columns-right.phtml file.

dqd
Text Box
www.besthosting4magento.com
Page 2: Inchoo s magento posts

September 8th, 2009 Published by: inchoo

Created using zinepal.com. Go online to create your own zines or read what others have already published. 2

Let’s assume we wish the “newreference” block to be placedbelow 2 columns, but above the footer. In this case, ourupdated file could look like this:

<!-- start middle --><div class="middle-container"><div class="middle col-2-right-layout">< ?php getChildHtml('breadcrumbs') ?><!-- start center --><div id="main" class="col-main"><!-- start global messages -->< ?php getChildHtml('global_messages') ?><!-- end global messages --><!-- start content -->< ?php getChildHtml('content') ?><!-- end content --></div><!-- end center -->

<!-- start right --><div class="col-right side-col">< ?php getChildHtml('right') ?></div><!-- end right --></div><div>< ?php getChildHtml('newreference') ?></div></div><!-- end middle -->

Step 3: Populating structural blockWe have the block properly placed, but unfortunately nothingis new on the frontsite. Let’s populate the new block withsomething. We will put new products block there as anexample. Go to appropriate layout XML file and add this blockto appropriate place.

<reference name="newreference"><block type="catalog/product_new" name="home.product.new" template="catalog/product/new.phtml" /></reference>

That’s it. I hope it will help someone

There are 15 comments

How to delete orders in Magento? |InchooYou got a Magento project to develop, you created a Magentotheme, you placed initial products and categories and youalso placed some test orders to see if Shipping and Paymentmethods work as expected. Everything seems to be cool andthe client wishes to launch the site. You launch it. When youenter the administration for the first time after the launch, youwill see all your test orders there. You know those should bedeleted. But how?

If you try to delete orders in the backend, you will find outthat you can only set the status to “cancelled” and the order isstill there. Unfortunately, Magento doesn’t enable us to deletethose via administration, so you will not see any “Delete order”button. This can be quite frustrating both to developers andthe merchants. People coming from an SAP world find theinability to delete to have some merit but there should be astatus that removes the sales count from the reports i.e. sales,inventory, etc.

SET FOREIGN_KEY_CHECKS=0;

TRUNCATE `sales_order`;TRUNCATE `sales_order_datetime`;TRUNCATE `sales_order_decimal`;TRUNCATE `sales_order_entity`;

TRUNCATE `sales_order_entity_datetime`;TRUNCATE `sales_order_entity_decimal`;TRUNCATE `sales_order_entity_int`;TRUNCATE `sales_order_entity_text`;TRUNCATE `sales_order_entity_varchar`;TRUNCATE `sales_order_int`;TRUNCATE `sales_order_text`;TRUNCATE `sales_order_varchar`;TRUNCATE `sales_flat_quote`;TRUNCATE `sales_flat_quote_address`;TRUNCATE `sales_flat_quote_address_item`;TRUNCATE `sales_flat_quote_item`;TRUNCATE `sales_flat_quote_item_option`;TRUNCATE `sales_flat_order_item`;TRUNCATE `sendfriend_log`;TRUNCATE `tag`;TRUNCATE `tag_relation`;TRUNCATE `tag_summary`;TRUNCATE `wishlist`;TRUNCATE `log_quote`;TRUNCATE `report_event`;

ALTER TABLE `sales_order` AUTO_INCREMENT=1;ALTER TABLE `sales_order_datetime` AUTO_INCREMENT=1;ALTER TABLE `sales_order_decimal` AUTO_INCREMENT=1;ALTER TABLE `sales_order_entity` AUTO_INCREMENT=1;ALTER TABLE `sales_order_entity_datetime` AUTO_INCREMENT=1;ALTER TABLE `sales_order_entity_decimal` AUTO_INCREMENT=1;ALTER TABLE `sales_order_entity_int` AUTO_INCREMENT=1;ALTER TABLE `sales_order_entity_text` AUTO_INCREMENT=1;ALTER TABLE `sales_order_entity_varchar` AUTO_INCREMENT=1;ALTER TABLE `sales_order_int` AUTO_INCREMENT=1;ALTER TABLE `sales_order_text` AUTO_INCREMENT=1;ALTER TABLE `sales_order_varchar` AUTO_INCREMENT=1;ALTER TABLE `sales_flat_quote` AUTO_INCREMENT=1;ALTER TABLE `sales_flat_quote_address` AUTO_INCREMENT=1;ALTER TABLE `sales_flat_quote_address_item` AUTO_INCREMENT=1;ALTER TABLE `sales_flat_quote_item` AUTO_INCREMENT=1;ALTER TABLE `sales_flat_quote_item_option` AUTO_INCREMENT=1;ALTER TABLE `sales_flat_order_item` AUTO_INCREMENT=1;ALTER TABLE `sendfriend_log` AUTO_INCREMENT=1;ALTER TABLE `tag` AUTO_INCREMENT=1;ALTER TABLE `tag_relation` AUTO_INCREMENT=1;ALTER TABLE `tag_summary` AUTO_INCREMENT=1;ALTER TABLE `wishlist` AUTO_INCREMENT=1;ALTER TABLE `log_quote` AUTO_INCREMENT=1;ALTER TABLE `report_event` AUTO_INCREMENT=1;

-- reset customersTRUNCATE `customer_address_entity`;TRUNCATE `customer_address_entity_datetime`;TRUNCATE `customer_address_entity_decimal`;TRUNCATE `customer_address_entity_int`;TRUNCATE `customer_address_entity_text`;TRUNCATE `customer_address_entity_varchar`;TRUNCATE `customer_entity`;TRUNCATE `customer_entity_datetime`;TRUNCATE `customer_entity_decimal`;TRUNCATE `customer_entity_int`;TRUNCATE `customer_entity_text`;TRUNCATE `customer_entity_varchar`;TRUNCATE `log_customer`;TRUNCATE `log_visitor`;TRUNCATE `log_visitor_info`;

ALTER TABLE `customer_address_entity` AUTO_INCREMENT=1;ALTER TABLE `customer_address_entity_datetime` AUTO_INCREMENT=1;ALTER TABLE `customer_address_entity_decimal` AUTO_INCREMENT=1;ALTER TABLE `customer_address_entity_int` AUTO_INCREMENT=1;ALTER TABLE `customer_address_entity_text` AUTO_INCREMENT=1;ALTER TABLE `customer_address_entity_varchar` AUTO_INCREMENT=1;ALTER TABLE `customer_entity` AUTO_INCREMENT=1;ALTER TABLE `customer_entity_datetime` AUTO_INCREMENT=1;

Page 3: Inchoo s magento posts

September 8th, 2009 Published by: inchoo

Created using zinepal.com. Go online to create your own zines or read what others have already published. 3

ALTER TABLE `customer_entity_decimal` AUTO_INCREMENT=1;ALTER TABLE `customer_entity_int` AUTO_INCREMENT=1;ALTER TABLE `customer_entity_text` AUTO_INCREMENT=1;ALTER TABLE `customer_entity_varchar` AUTO_INCREMENT=1;ALTER TABLE `log_customer` AUTO_INCREMENT=1;ALTER TABLE `log_visitor` AUTO_INCREMENT=1;ALTER TABLE `log_visitor_info` AUTO_INCREMENT=1;

-- Reset all ID countersTRUNCATE `eav_entity_store`;ALTER TABLE `eav_entity_store` AUTO_INCREMENT=1;

SET FOREIGN_KEY_CHECKS=1;

After you have it executed, the test orders will not be in thedatabase any more. Keep in mind that this will delete ALLorders, in the database. So, you should execute this queriesimmediately after launch.

connect2MAGE | WordPress plugin foreasy Magento database connectionHi everyone. I wrote this little plugin while working on oneof our projects. If you know your way around WordPressthen you know what $wpdb variable stands for. Imagine thefollowing scenario. You have WordPress installation on onedatabase, Magento on another. You know your way aroundSQL. You can always make new object based on WPDB classinside your template files giving it database access parameters,or you can use this plugin and use $MAGEDB the same wayyou use $wpdb.

Below is a little example of using $MAGEDB to connect toMagento database and retrieve some products by reading id’sfrom custom field of some post inside your WordPress.

Place this code inside one of your templates, like single.php.

< ?php

global $MAGEDB;$MAGEDB->show_errors(true);

/** BASIC SETUP */

//$storeUrl = 'http://server/shop/index.php/';$storeUrl = get_option('connect2MAGE_StoreUrl');

//$urlExt = '.html';$urlExt = get_option('connect2MAGE_UrlExt');

/** END OF BASIC SETUP */

$entityIds = get_post_custom_values(get_option('connect2MAGE_CustomFieldName'));

$result = array();

if(!empty($entityIds)){$entityIds = $entityIds[0];$sql = "SELECT `e`.*, `_table_price`.`value` AS `price`, IFNULL(_table_visibility.value, _table_visibility_default.value) AS `visibility`, IFNULL(_table_status.value, _table_status_default.value) AS `status`, `_table_url_key`.`value` AS `url_key`, IFNULL(_table_name.value, _table_name_default.value) AS `name` FROM `catalog_product_entity` AS `e` INNER JOIN `catalog_product_entity_decimal` AS `_table_price` ON (_table_price.entity_id = e.entity_id) AND (_table_price.attribute_id='99') AND (_table_price.store_id=0) INNER JOIN `catalog_product_entity_int` AS `_table_visibility_default` ON (_table_visibility_default.entity_id = e.entity_id) AND (_table_visibility_default.attribute_id='526') AND _table_visibility_default.store_id=0 LEFT JOIN `catalog_product_entity_int` AS `_table_visibility` ON (_table_visibility.entity_id = e.entity_id) AND (_table_visibility.attribute_id='526') AND (_table_visibility.store_id='1') INNER JOIN `catalog_product_entity_int` AS `_table_status_default` ON (_table_status_default.entity_id = e.entity_id) AND (_table_status_default.attribute_id='273') AND _table_status_default.store_id=0 LEFT JOIN `catalog_product_entity_int` AS `_table_status` ON (_table_status.entity_id = e.entity_id) AND (_table_status.attribute_id='273') AND (_table_status.store_id='1') INNER JOIN `catalog_product_entity_varchar` AS `_table_url_key` ON (_table_url_key.entity_id = e.entity_id) AND (_table_url_key.attribute_id='481') AND (_table_url_key.store_id=0) INNER JOIN `catalog_product_entity_varchar` AS `_table_name_default` ON (_table_name_default.entity_id = e.entity_id) AND (_table_name_default.attribute_id='96') AND _table_name_default.store_id=0 LEFT JOIN `catalog_product_entity_varchar` AS `_table_name` ON (_table_name.entity_id = e.entity_id) AND (_table_name.attribute_id='96') AND (_table_name.store_id='1') WHERE (e.entity_id in (".$entityIds.")) AND (_table_price.value >= 0 and _table_price.value < = 999999999999) AND (IFNULL(_table_visibility.value, _table_visibility_default.value) in (2, 4)) AND (IFNULL(_table_status.value, _table_status_default.value) in (1)) AND (_table_url_key.value not in ('P1FHN3G0LRWGMYZ3')) AND (IFNULL(_table_name.value, _table_name_default.value) not in ('P1FHN3G0LRWGMYZ3'))";$result = $MAGEDB->get_results($sql);var_dump($result);}

else{echo '<p class="relatedProductInfo">No related products available...</p>';}

?>

< ?php if (!empty($result)): ?><table id="relatedProductsList">< ?php foreach ($result as $item): ?><tr class="productInfo"><td><a href="<?php echo $storeUrl ?>/< ?php echo $item->url_key ?>< ?php echo $urlExt ?>">< ?php echo $item->name ?></a></td><td>< ?php _e('Starting at') ?> $ < ?php echo floatval($item->price) ?></td></tr>< ?php endforeach; ?></table>< ?php endif; ?>

Hope some of you find this useful. Especially those who refuseto use Web Services for connecting different systems.

Download connect2MAGE WordPress plugin.

There are 6 comments

Custom checkout cart - How to sendemail after successful checkout inMagento | InchooRecently I have been working on a custom checkout page forone of our clients in Sweden. I had some trouble figuring outhow to send default Magento order email with all of the orderinfo. After an hour or so of studying Magento core code, hereis the solution on how to send email after successful order hasbeen made.

Not sure how useful this alone will be for you, so I’ll throw alittle advice along the way. When trying to figure how to reuseMagento code, separate some time to study the Model classeswith more detail. Then “tapping into” and reusing some ofthem should be far more easier.

Latest News RSS box in Magento usingZend_Feed_Rss | InchooYou would like to have a eCommerce power of Magento, butalso have a blog to empower your business? In this case,you probably know that Magento doesn’t have some articlemanager in the box. Many clients seek for supplementarysolution like Wordpress to accomplish this goal. Ok, so youcreated a blog on same or different domain and you wouldlike those articles to appear somewhere in Magento (probablysidebar). This article will explain how to do it.

Let’s create a file called latest_news.phtmlin app/design/frontend/default/[your_theme]/template/callouts/latest_news.phtmlNow we will create a PHP block that will display the listof articles from RSS feed. We will use Inchoo RSS fordemonstration purposes. In your scenario, replace it with yourown valid RSS URL.

< ?php $channel = new Zend_Feed_Rss('http://feeds.feedburner.com/Inchoo'); ?>

<div class="block block-latest-news"><div class="block-title"><h2>< ?php echo $this->__('Latest News') ?></h2></div><div class="block-content">

Page 4: Inchoo s magento posts

September 8th, 2009 Published by: inchoo

Created using zinepal.com. Go online to create your own zines or read what others have already published. 4

<ol id="graybox-latest-news">< ?php foreach ($channel as $item): ?><li><a href="<?php echo $item->link; ?>">< ?php echo $item->title; ?></a></li>< ?php endforeach; ?></ol></div></div>

Step 2Now, we should decide where to place it. I assume you alreadyknow how Magento blocks and references work. Let’s assumeyou would like to place it in right column by default for wholecatalog. In this case open your app/design/frontend/default/[your_theme]/layout/catalog.xml file and under “default” tagupdate “right” reference with something similar.

That’s it. You should be able to see the list of articles from RSSfeed with the URLs. Hope this will help someone.

Advanced search in Magento and how touse it in your own wayIt’s been a while since my last post. I’ve been working onMagento quite actively last two months. I noticed this negativetrend in my blogging; more I know about Magento, the lessI write about it. Some things just look so easy now, and theystart to feel like something I should not write about. Anyhow….time to share some wisdom with community

Our current client uses somewhat specific (don’t they all) storeset. When I say specific, i don’t imply anything bad about it.One of the stand up features at this clients site is the advancedsearch functionality. One of the coolest features of the built inadvanced search is the possibility to search based on attributesassigned to a product.

To do the search by attributes, your attributes must have thatoption turned on when created (or later, when editing anattribute). In our case we had a client that wanted somethinglike

http://somestore.domain/catalogsearch/partnumberor

http://somestore.domain/catalogsearch/brand

instead of the default onehttp://somestore.domain/catalogsearch/advancedwith all of the searchable fields on form.

Some of you might say why not use the default and call it a day.Well, default one does not get very user friendly when largenumber of custom added searchable attributes are added inMagento admin interface. Then the frontend search form getscluttered and users are easily to get confused.

So in our example we would like to use the advanced searchand all of it’s behaviour and logic but to use it on somewhatspecial link and to hide unnecessary fields. Therefore, ourcustom pages he would have only one input field on form andthe submit button. How do we set this up? Well, all of the logicand functionality is already there.

What we need is to:

• use the http://somestore.domain/catalogsearch/partnumber as a link

• show only custom_partnumber field on the search form

First, we have to see where does the /advanced come from.Lets open our template folder at

app\design\frontend\default\default\template\catalogsearch\

there you will see the /advanced folder. Make a copy of thatentire folder, in the same location, and name it to somethinglike /custom.

Now your /custom folder should have 2 files: form.phtml andresult.phtml.

Next in line is the /layout folder in our template. You needto open catalogsearch.xml file. Go to line 64. Do you see the<catalogsearch_advanced_index> tag there. Make the copy ofit (including all of the content it hold with the closing tag also).Put the copy of that entire small chunk of code right below.Now rename all of the occurrences of “advanced” to “custom”there like on code below:

<catalogsearch_custom_index><!– Mage_Catalogsearch –>

<reference name=”root”>

<actionmethod=”setTemplate”><template>page/2columns-right.phtml</template></action>

</reference>

<reference name=”head”>

<action method=”addItem”><type>js_css</type><name>calendar/calendar-win2k-1.css</name><params/><!–<if/><condition>can_load_calendar_js</condition>–></action>

<action method=”addItem”><type>js</type><name>calendar/calendar.js</name><!–<params/><if/><condition>can_load_calendar_js</condition>–></action>

<action method=”addItem”><type>js</type><name>calendar/lang/calendar-en.js</name><!–<params/><if/><condition>can_load_calendar_js</condition>–></action>

<action method=”addItem”><type>js</type><name>calendar/calendar-setup.js</name><!–<params/><if/><condition>can_load_calendar_js</condition>–></action>

</reference>

<reference name=”content”>

Page 5: Inchoo s magento posts

September 8th, 2009 Published by: inchoo

Created using zinepal.com. Go online to create your own zines or read what others have already published. 5

<block type=”catalogsearch/custom_form”name=”catalogsearch_custom_form”template=”catalogsearch/custom/form.phtml”/>

</reference>

</catalogsearch_custom_index>

Do the same for <catalogsearch_advanced_result> tag.

Now go to the app\code\core\Mage\CatalogSearch\Blockfolder. And make a copy of /Advanced folder namingit /Custom. Open /Custom/Form.php and replaceclass name Mage_CatalogSearch_Block_Advanced_Formwith Mage_CatalogSearch_Block_Custom_Form, thenopen /Custom/Result.php and replace classname Mage_CatalogSearch_Block_Advanced_Result withMage_CatalogSearch_Block_Custom_Result.

Inside Form.php there is getModel() function. DO NOTreplace the Mage::getSingleton(’catalogsearch/advanced’);with Mage::getSingleton(’catalogsearch/custom’);. The pointis to use the default advanced search logic here. Same goes forgetSearchModel() function inside Result.php file.

Next in line, controllers. We need to makethe copy of AdvancedController.php and name itCustomController.php, then open it and replace theclass name Mage_CatalogSearch_AdvancedController withMage_CatalogSearch_CustomController.

Inside this CustomController.php there is a functioncalled resultAction(). You need to replace the ( …Mage::getSingleton(’catalogsearch/advanced’) … ) string‘catalogsearch/advanced’ with ‘catalogsearch/custom’. This isthe 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 allthis is to 1) get more custom link in url and 2) display only onecustom searchable attribute field in form. Therefore, for thelast step we need to go to the template\catalogsearch\customfolder and open form.phtml file.

Inside that file, there is one foreach loop that goes like<?php foreach ($this->getSearchableAttributes() as$_attribute): ?>

All we need to do now is to place one if() conditionright below it. If your custom attribute name (code) is“my_custom_attribute” then your if() condition might looksomething like

<?php foreach ($this->getSearchableAttributes() as$_attribute): ?><?php if($_code == ‘my_custom_attribute’): ?>

<?php endif; ?><?php endforeach; ?>

And you are done. Now you have somewhat more custom url,and only one custom field displayed on that url.

This might not be the best method of reusing already writtencode, however I hope it’s any eye opener to somewhat moreelegant aproach.

Enyoj.

There are 14 comments

Related productsThere are three types of product relations in Magento:Up-sells, Related Products, and Cross-sell Products. Whenviewing a product, Upsells for this product are items that yourcustomers would ideally buy instead of the product they’reviewing. They might be better quality, produce a higher profitmargin, be more popular, etc. These appear on the productinfo page. Related products appear in the product info pageas well, in the right column. Related products are meant tobe purchased in addition to the item the customer is viewing.Finally, Cross-sell items appear in the shopping cart. Whena customer navigates to the shopping cart (this can happenautomatically after adding a product, or not), the cross-sellsblock displays a selection of items marked as cross-sells to theitems already in the cart. They’re a bit like impulse buys – likemagazines and candy at the cash registers in grocery stores.

UpsellsThis is the example of the Up-sell. Ideally, the visitor issupposed to analyze those products as they should be relevantto the one that is just loaded.

There are 2 comments

File upload in MagentoNow, Magento already have frontend and admin part of fileupload option implemented in themes. Since backend part isstill missing, understand that this still doesn’t work, however,if you’re interested how it looks, read on ..

We are coding module of similar functionality for one of ourclients as we speak, but we have our fingers crossed to see thisoption in next Magento version!

Page 6: Inchoo s magento posts

September 8th, 2009 Published by: inchoo

Created using zinepal.com. Go online to create your own zines or read what others have already published. 6

Inchoo TV – Magento channel

Making use of Magento getSingletonmethodIn one of my previous articles I showed you how to usegetModel and getData methods in Magento. Although weshould not put those to methods at the same level, since I’d saythe getModel is a bit more higher. Higher in sense, you firstuse the geModel to create the instance of object then you usegetData to retrieve the data from that instance. I have said itbefore, and I’m saying it again; Magento is a great peace offull OOP power of PHP. It’s architecture is something not yetwidely seen in CMS solutions.

One of the architectural goodies of Magento is it’s Singletondesign pattern. In short, Singleton design pattern ensures aclass has only one instance. Therefore one should provide aglobal point of access to that single instance of a class.

So why would you want to limit yourself to only one instance?Let’s say you have an application that utilizes databaseconnection. Why would you create multiple instance of thesame database connection object? What if you had referencesto an object in multiple places in your application? Wouldn’tyou like to avoid the overhead of creating a new instance ofthat object for each reference? Then there is the case whereyou might want to pass the object’s state from one referenceto another rather than always starting from an initial state.

Inside the Mage.php file of Magento system there is agetSingleton method (function if you prefer). Since it’sfootprint is rather small, I’ll copy paste the code for you to seeit.

First, notice the word static. In PHP and in other OOPlanguages keyword static stands for something like “this canbe called on non objects, directly from class”. Now let me showyou the footprint of the getModel method.

Do you notice the parameters inside the brackets? They are thesame for both of theme. Where am I getting with this? Well,I already showed you how to figure out the list of all of theavailable parameters in one of my previous articles on my site.So all we need to do at this point is, play with those parametersusing getSingleton() method and observe the results.

Most important thing you need to remember is that usinggetSingleton you are calling already instantiated object. So ifyou get the empty array as a result, it means the object isempty. Only the blueprint is there, but nothing is loaded in it.We had the similar case using getModel(’catalog/product‘)on some pages. If we done var_dump or print_r we couldsaw the return array was empty. Then we had to use the loadmethod to load some data into our newly instantiated object.

What I’m trying to say, you need to play with itto get the feeling. Some models will return data richobjects some will return empty arrays. If we were to do

Mage::getSingleton(’catalog/session) on view.phtml file wewould retrieve an array with some useful data in it. Donot get confused with me mentioning the view.phmtl file,it’s just he file i like to use to test the code. UsingMage::getSingleton(’core/session) would retrieve us somemore data. You get the picture. Test, test, test… What’s greatabout the whole thing is that naming in Magento is perfectlylogical so most of the time you will probably find stuff you needin few minutes or so.

Figuring out Magento object contextOne of the problems working under the hood of the MagentoCMS is determining the context of $this. If you are aboutto do any advanced stuff with your template, besides layoutchanges, you need to get familiar with Magento’s objects(classes).

Let’s have a look at the /app/design/frontend/default/default/template/catalog/product/view.phtml file. If youopen this file and execute var_dump($this) your browser willreturn empty page after a short period of delay. By page I meanon the product view page; the one you see when you click onMagetno product. Experienced users will open PHP error logand notice the error message caused by var_dump(). Errormessage:PHP Fatal error: Allowed memory size of 134217728 bytesexhausted (tried to allocate 121374721 bytes)

I like using print_r() and var_dump(), mostly because so farI had no positive experience using fancy debug or any otherdebugger with systems like Magento.

Why is PHP throwing errors then? If you google out theerror PHP has thrown at you, you’ll see that PHP 5.2has memory limit. Follow the link http://www.php.net/manual/en/ini.core.php#ini.memory-limit to see how andwhat exactly.

Google search gave me some useful results trying to solve myproblems. I found Krumo at http://krumo.sourceforge.net/.It’s a PHP debugging tool, replacement for print_r() andvar_dump(). After setting up Krumo and running it onMagento it gave me exactly what I wanted. It gave me theobject type of the dumped file; in this case it gave me objecttype of $this.

If you’re using an IDE studio with code completion supportlike NuSphere PhpED, ZendStudio or NetBeans and youdecide to do something like $this-> you won’t get any methodslisted. I haven’t yet seen the IDE that can perform this kind ofsmart logic and figure out the context of $this by it self.

What you can do is use the information obtainedby krumo::dump($this). Performing krumo::dump($this)on /app/design/frontend/default/default/template/catalog/product/view.phtml file will return object type,Mage_Catalog_Block_Product_View.

Now if you do

Mage_Catalog_Block_Product_View::

your IDE supporting code completion will give youa drop down of all the available methods, let’s saycanEmailToFriend();

Page 7: Inchoo s magento posts

September 8th, 2009 Published by: inchoo

Created using zinepal.com. Go online to create your own zines or read what others have already published. 7

Mage_Catalog_Block_Product_View::canEmailToFriend();

Now all you need to do is to replaceMage_Catalog_Block_Product_View with $this like

$this->canEmailToFriend();

And you’re done. All of this may look like “why do I need this”.What you need it a smart IDE, one that can figure out thecontext of $this by it self and call the methods accordingly. NoIDE currently does that, if I’m not missing on something. Fornow 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 Magentoyou can read my other, somewhat detailed article onactivecodeline.com.

Hope this was useful for you.

There are 2 comments

Get product review info (independent) ofreview pageHere at Inchoo, we are working on a private project, thatshould see daylight any time soon. One of the requirementswe had is to show product review info on pages independentof product review page. Let’s say you wish to show review infoon home page for some of the products. After few weeks withworking with Magento, one learns how to use the model stuffdirectly from view files. Although this might not be the “right”way, it’s most definitely the fastest way (and I doubt most ofyour clients would prefer any other , especially if it’s someminor modification).

Simple random banner rotator inMagento using static blocksThis is my first post here and I’ll write about my first challengeregarding Magento since I came to work at Inchoo.

Please note that you are not restricted only to images, youcould use text, video or whatever you want here, but I’ll focuson images with links as title says.In order to show this block, you should be familiar withMagento layouts.Since that is out of scope for this article, I’ll show you how toput it below the content on cms pages.

Changing default category sort order inMagentoCategory toolbar has many options. By default is shows howmany items are in the category, you can choose how manyproducts you wish to be displayed per page, you can changethe listing type (List or Grid) and you may choose Sort Order.This “Sort Order” can be confusing. The default “Sort Order”is “Best Value”. What does it mean? How is the Best valuedetermined? Can we change the default sort order?

What is “Best Value” filed?When you go to Category page in Magento administration, youwill see “Category Products” tab. From there, you will see thelist of products that are associated to this category. The lastcolumn in “Position”. That is how “Best Value” is determined.So, best value is not something that is dynamically calculated.You can tailor it to your likings.

How to change default Sort OrderThe file you need to look at is: /app/code/core/Mage/Catalog/Block/Product/List/Toolbar.php Since we’ll modify it, make acopy to /app/code/local/Mage/Catalog/Block/Product/List/Toolbar.php

One there, you will notice this code at the beginning of the file:

$this->_availableOrder = array('position' => $this->__('Best Value'),'name' => $this->__('Name'),'price' => $this->__('Price'));

Default order takes the first value available. So, all you have todo is to either:

• reorder it if you want to have a selection in the Toolbar or

• set only one value of choice if you will remove theselection from the toolbar

I hope this will help somebody.

There are 4 comments

Couple of days ago we launched a new Magento project:Pebblehill Designs. This site utilizes Magento features andturns it into a very powerful online catalog. You won’t noticethe Shopping Cart or checkout process yet. Even withoutthose, this site shows exactly what Pebblehill has to offer: themost popular styles of custom upholstered furniture.

You can customize the furniture collection to express yourown unique style made with the highest quality materials andcraftsmanship available.

Pebble Hill Designs’ parsons chairs are “American made” withpride in Georgia. The quality speaks for itself. Your productsare pre-assembled and ready for use when you receive them.

Page 8: Inchoo s magento posts

September 8th, 2009 Published by: inchoo

Created using zinepal.com. Go online to create your own zines or read what others have already published. 8

The love and the passion for beautiful home interiorstranslates into a high-quality product with a sophisticatedstyle manufactured in the USA. Pebblehill Designs hasassembled some of the most popular styles of customupholstered furniture to offer to our customers. All styles areavailable in every fabric shown or you can provide your ownfabric. You can customize the furniture collection to expressyour own unique style made with the highest quality materialsand craftsmanship available.

TeraFlex PLUS, another Magento +Wordpress duoAfter we launched TeraFlex Suspensions website few monthsago, we created a new similar website for Teraflex PLUS.Although the name is similar, this is not the same company.The primary goal of this site is to help Jeep owners to upgradetheir pets with parts and accessories for any type of adventure.The secondary goal is to create a Jeep enthusiast communityin Utah, USA and surroundings. The site is powered byWordpress and Magento combination.

Magento is a superb Shopping Cart, but it lacks some of theCMS features. Wordpress is a superb CMS, but it fails toprovide the needs for the eCommerce goals. The combinationof these can create a very powerful website. We present youTeraFlex PLUS : Jeep Adventure Outfittershttp://www.teraflexplus.com/

Magento part of the site can be viewed if you click at Shop byVehicle or Shop by Brand tabs from the main menu, but youwill notice that some blocks seamlessly integrate between twosolutions.

We developed this site as the Surgeworks team. The designwas created by one of out top designers, Rafael Torales. Wehope you enjoy it and feel free to post your comments.

There are 6 comments

The Best Shopping Cart :: Trend analysisof osCommerce, Magento, ZenCart andCRE Loaded | InchooIf you try to ask this question on some forum or newsgroup,you will surely get many replies. Everyone will present youhis favorite. My first developed online store was created withstandard osCommerce platform. After three or four projects,I started to work with CRE Loaded and used it frequently foryears. Although it was also an osCommerce fork, it had manyadvantages. I switched to Magento™ early this year and thisis my final choice.

Google™ Trends is a great tool to check some platformspopularity by comparing it to the competition. For my shortanalysis, I compared:

As you can see, osCommerce still remains the most populareCommerce platform. However, you can notice that this

Page 9: Inchoo s magento posts

September 8th, 2009 Published by: inchoo

Created using zinepal.com. Go online to create your own zines or read what others have already published. 9

popularity is fading. ZenCart is stable for the past two years.And my previous favorite, CRE Loaded (much better solutionthan ZenCart in my opinion), is very low. Its popularity is alsofading even after their team put great effort into a new websiteand identity.

Now, take a look at blue line. My prediction is that sometimein Q1 2009, Magento will become most popular eCommerceplatform. It will surely kick osCommerce off the throne wherethat fat duck was sitting for many years. It was about time.

First of all, let me inform you that this article is for those ofyou who are just starting with Magento. If you are a Magentoexpert, you will probably know this. Consider it just a reminderfor those who use Magento for first time. There are threecommon mistakes that most people do when they try to useMagento for first time, so read this article and you won’t beone of them.:)

• More experienced PHP developers will first readMagento Designers Guide before they try to styleMagento, but others won’t and that’s the mistakenumber two. Since Magento has great theme fallbacksystem there is really no need to touch default theme.Although easiest way to make new theme for newMagento is top copy the whole theme to a new folder,don’t do that. Copy only the files you will need: from /design/frontend/default/default/ directory to /design/frontend/default/YOUR_NEW_THEME directory. Dothe same thing with /skin/frontend/default/default/Congratulations, you have your own theme just likethat. All that left is to apply new theme (System->Configuration->Design) and you are ready to do withyour theme files whatever you want.

• Third mistake is modifying Magento core files. What filesare core ones? All what is in app/code/core folder. If youhave a need to modify some of those ones, you just needto duplicate that file in the same directory path to app/code/local. For example, if you need to modify the fileapp/code/core/Mage/Checkout/Block/Success.php

copy it to

app/code/local/Mage/Checkout/Block/Success.php

and leave the core file intact. This way your Magento willbe more bullet-proof to future updates.

Custom CMS page layout in Magento |InchooLast week I had a request to add new custom layoutfor few cms pages in one Magento shop. It’s reallyuseful for different static pages of your shop. First createextension with only config file in it: app/code/local/Inchoo/AdditionalCmsPageLayouts/etc/config.xml

Add your page/custom-static-page-1.phtml template file (orcopy some default one for start) and you’re done There is

also tutorial about this on Magento Wiki. However i don’t likeapproach of duplicating and overriding Mage files from /local,if it can be avoided, so i decided to write this small and usefulexample of adding or overriding default Magento settingsthrough separated config files. And yes, Magento values canbe overridden this way. Default layouts config can be foundin app/code/core/Mage/Cms/etc/config.xml along with usedxml code structure, so check it out. Thank you for listening!

Drupal to Magento integration, simplelink tweak with multilingual siteI see my coworker and friend Željko Prša made a nice little poston Adding a new language in Magento so I figure I’ll jump witha little Drupal to Magento integration trick concerning linkissues and multilingual sites. Here is a piece of code you canuse in your Drupal templates to do the proper switching fromDrupal site to Magento while keeping the selected language ofsite. Note, this tweak assumes you have the desired languagesetup on both Drupal and Magento side.

This part goes to some of your Drupal theme file

...global $language ;$lname = ($language->language == null) ? 'en' : $language->language; /* like "en", "de" */$storeView = null;if($lname == 'de') { $storeView = '?___store=german&amp;amp;amp;amp;___from_store=english'; }??>

</p><p style="text-align: left;"><a id="main_menu_shop" href="<?php echo 'http://'.$_SERVER['HTTP_HOST'].base_path() ?>shop/index.php/someProductLink.html< ?php echo $storeView ?>">Shop</a>...

Note the $storeView variable; GET ___store holds the valueof code name of the view you assigned in Magento, while GET___from_store variable is used as helper to Magento innerworkings. You can basically omit the other one. Your links toShop from Drupal to Magento should now activate the properlanguage, the same one you have active on Drupal side.

There are 1 comments

Adding a new language in MagentoAs anything in Magento adding a new language is somethingthat requires a certain procedure which we will explain rightnow and for future reference.

• 3. Now go to: Configuration -> Current ConfigurationScope (Select your language from the dropdown) and onthe right side under “Locale options” choose the desiredlanguage.

That’s it, now when you go to the frontend of the site, you’llnotice a dropdown menu allowing the language switching.

Access denied in Magento adminSome of you may encountered this problem. You install newMagento extension through downloader, try to access itsconfiguration settings and Magento throws “Access denied”page at you. Although you’re administrator of the system.

Page 10: Inchoo s magento posts

September 8th, 2009 Published by: inchoo

Created using zinepal.com. Go online to create your own zines or read what others have already published. 10

So what happened here? Magento just doesn’t have storedprivileges for this new extension.

First just try to logout and login again. If that doesn’t work,you need to reset admin privileges.

Navigate to System->Permissions->Roles and clickAdministrators role.

Check your Role Resources settings just in case, ResourceAccess dropdown should be already set to All foradministrators.

Without changing anything just click “Save Role” button, sothat Magento re-saves all permissions.

You should be able to access your new extension now withoutproblems.

There are 5 comments

If you worked with osCommerce, Zen Cart, CRE Loaded or anysimilar eCommerce platform before, you might find Magentodatabase structure quite confusing when you see it for the firsttime. I advise you not to rush too much figuring out whatis what by glancing through database. Try to spend first fewhours getting familiar with some background. For purposesof flexibility, the Magento database heavily utilizes an Entity-Attribute-Value (EAV) data model. As is often the case, thecost of flexibility is complexity. Is there something in Magentothat is simple from developers point of view?

Data manipulation in Magento is often more knowledgedemanding than that typical use of traditional relationaltables. Therefore, an understanding of EAV principles andhow they have been modeled into Magento it is HIGHLYrecommended before making changes to the Magentodata or the Magento schema (Wikipedia: Entity-attribute-value_model). Varien has simplified the identification of EAVrelated tables with consistent naming conventions. Core EAVtables are prefixed with “EAV_”. Diagrams in this post containa section labeled “EAV” which displays Magento’s core EAVtables and thier relationships to non-EAV tables.

Database diagrams and documents found in this post areintended to mirror the database schema as defined by Varien.Table relationships depicted in the diagrams represent onlythose relationships explicitly defined as Foreign Keys in theMagento database. Additional informal/undiagrammed tablerelationships may also exist, so when modifying the schemaor directly manipulating data it is important to identify andevaluate possible changes to these tables as well (and thetables they relate to, and the tables they relate to…).

The author of Database Diagram is Gordon Goodwin, ITConsultant. You can see his info in the PDF.

There are 12 comments

Magento + .Net Framework, simple orderpreview appFor those of you who are into kinky stuff I made a simple,more of a proof of concept, application that sits in Widnowstaskbar and shows the order info in balloon popup. Took melittle more than half of hour to get this working. Almost forgothow great C# is

Page 11: Inchoo s magento posts

September 8th, 2009 Published by: inchoo

Created using zinepal.com. Go online to create your own zines or read what others have already published. 11

Magento has this great feature, rss feed for orders. Youcan access it via link http://myshopsite/rss/order/new. Itrequires authentication, so you need to provide Magento userand pass to access this link. Idea I wanted to play aroundwas how to get this info in my windows app. It’s really, reallysimple. Below is the screenshot of this little app for you to seewhat I’m talking about.

And here is the application it self simpleorderpreview and fullsource code (Visual Studio 2008 Express C#, entire solutionproject) acmnewproducts.

When you un-archive files from simpleorderpreview there isonly one thing you need to do prior to running .exe file. Youneed to open ACMNewProducts.exe.config and set username,password and url of your own Magento shop. That’s it. Nowyou can run the app.

One click on Magento icon inside the taskbar executesshow order process, while double cliking the icon closes theapplication.

I will not go into the details in this post on how this works.Basicaly it’s simple XML parser. Most important part is theHTTP 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 customoptions in grouped product in Magento |InchooDoes the title sound complicated? Grouped Products displayseveral products on one page. For example – if you’re sellingchef’s knives and you have the same knife in four sizes, you canmake a grouped product to display all four sizes. Customerscan select the size(s) they want and add to cart from this page.Another example would be a themed bedroom set – you cancreate a grouped product and sell the sheets, comforter, andpillow cases all from the same page.

Technically, we create a simple products and after that agrouped products. When we edit the grouped product, we willassociate simple products to it.It works very fine, but some ofyou might have issue if a simple product has custom options.If that’s the case, and if costum options are set as required(default way), the simple product will not be associative to thegrouped product. Let’s see what needs to be changed in thatcase.

On Magento site, there is a nice tutorial how to create agrouped product. Please read it first to become familiar withthe process. If you don’t have to assign simple products withcustom options to a grouped product, that tutorial will beenough.

Manually create Google Sitemap inMagento | InchooMost of you probably know this, but let’s define what thesitemaps are. Sitemaps are a simple way for site creators togive search engines the information about pages on their sitethat are available for public. Basically, those are just 1 or moreXML files that lists URLs for a site along with additional metainformatio about each URL (like last update, how often itchanges, its importance relevant to other pages). With this inmind, search engines can be more clever while crawling thesite. Click here see how sitemap of this site looks like.

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

Page 12: Inchoo s magento posts

September 8th, 2009 Published by: inchoo

Created using zinepal.com. Go online to create your own zines or read what others have already published. 12

How do we create Google Sitemap in Magento?1. Sitemap File ConfigurationFirst we need to create sitemap file in Magento. This isbasically pointer to tell Magento where to create sitemap fileand how to name it. Log in to Magento Administration and goto:Catalog -> Google Sitemap

Check to see if the sitemap file is already present. Letsassume we wish to create sitemap in the URL: http://www.yourstore.com/sitemap/sitemap.xmlTo do it successfully,

1. FTP to the server

2. create sitemap folder

3. chmod the folder to 777

On some servers, previous steps will not be required, but it isbetter to create the file first so that Magento can edit it.

Let’s go to Magento administration now and click on “AddSitemap” button. Just insert the default values.

After this step, we just told Magento where to create sitemapfile. It is not yet created.

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

3. Create Sitemap ManuallyLooks like Magento folks were thinking that sitemap shouldonly be created by a cron job. Yes, it can be done that wayalso. Be sure to read Wiki article How to Set Up a Cron Jobto get familiar with it. If you are looking for manual creation,quit your search for “Create Sitemap” button. You will not findit. But there is a workaround. You can enter manual URL toexecute sitemap creation:

http://www.yourstore.com/index.php/admin/sitemap/generate/sitemap_id/[ID of Sitemap from step 1]

Of course, replace the content with square brackets with actualSitemap ID.

There are 9 comments

Observer pitfalls of building seriousmodules in MagentoUnlike good old WordPress that “every kid in the block” knowshow to create a plugin for, Magento is a whole new system. Itrequires extensive knowledge of OOP, ORM’s, MVC, and fewother stuff. This is why not “every kid in the block” can write amodule for Magento, and this is why I love it. However, unlikeWordPress, Drupal and other community driven systems outthere who keep in mind backward compatibility things withMagento things are a bit different.

One of the things that caught my eye and made mewonder about the consequences is the Observer and overridefunctionality that probably most of the serious custom madeMagento modules will utilize. Utilizing Observers enables youto observe and execute some action inside the “customer workflow” or even some admin stuff. Such functionality is heavilyknown is systems like WordPress and it’s called “hooks”.Besides hooking, another useful an very powerful featurewhich is actually related more to the OOP concept itself is theoverriding. Personally i find the combination of observers andoverrides to be the coolest and most powerful stuff in Magentomodule development.

So where is the issue? As of time of this writing, thelatest Magento version is 1.3.1. Let’s look at the previous“major” release prior to that one, version 1.2.1.2. Here isa prepareForCart method signature from app/code/core/Mage/Catalog/Model/Product/Type/Abstract.php (line 239,Magento version 1.2.1.2):

Notice the difference? Although this might not look like“that big of a deal” suppose you had implemented overridefunctionality like

In the above code, we override the prepareForCart method toto some custom stuff for us. This peace of code would workperfectly fine in version 1.2.1.2, but when client decides toupgrade the shop to 1.3.1 or newer he would get the error like

To me, stuff like this is a serious downside towards buildingadvanced modules. Changing core files and core functionalitycan have serious impact on custom made modules eachMagento upgrade. Therefore, one should keep an eye openon what modules he will throw into the shop. Personally Iconsider online stores very serious and have strong feelingsabout each store owner having somewhat of dedicateddeveloper that will be in charge even for stuff like adding newmodules.

Just consider the financial loss for a store owner of any moreserious web shop if he decides to download the and installmodule himself just to realize that for incompatibility reasonsthis new module made his shop fully nonfunctional.

How to transfer large Magento databasefrom live to development server andother way roundI have been involved in Magento development for almost ayear now. God knows I had (and still have) my moments ofpain with it . If you are in professional, everyday, PHPdevelopment that focuses mainly on Magento then your lifeprobably isn’t all flowers and bees. Magento is extremely richeCommerce platform, but its main downside IMHO is its sizeand code complexity. If you download Magento via SVN, youwill sound find out it has around 11 600 and more files. Thisis no small figure. Transferring that much of files over theFTP can be a real night mare. Luckily we have SSH and tarcommand to handle this really neat.

But what about database. Today I worked on database withmore than 20 000 products in store and with extremelylarge number of categories. What seemed like easy database

Page 13: Inchoo s magento posts

September 8th, 2009 Published by: inchoo

Created using zinepal.com. Go online to create your own zines or read what others have already published. 13

transfer from live site to local developer machine to do a testand fix on few issues tunerd out to be an issue for itself.Without further delay, here is my favorite tool to handle alldatabase related work from now on: Navicat.

Among my favorite features is the Data transfer. Directlymoving one database to another among different MySQLservers works like a charm. I find yourself strangled amongoften database recommended action I suggests you test thetrial version of this tool.

Here are some screenshots of Navicat Data transfer in Action.

There are 4 comments

Affiliates for all – Magento integrationRecently one of our clients needed and info on Affiliate modulefor Magento. When it comes to Magento, word “module” isloosely related. Sure, every module needs config files in orderto report it’s “connection” to Magento core. Modules like this,

Affiliates for all, are modules I consider loosely related to core.They are in one or another way connected to Magento but theyare self standing, independent, applications.

Installation of Affiliate module is a trivial task. It mostlycomes down to extracting downloaded archive file to a webaccessible directory (to your server, hosting) and configuringthe config.inc file. (For security reasons, try renamingthe config.inc to config.inc.php, plus changing the /lib/bootstrap.php on line 23 to include config.inc.php). Afterimporting affiliates.sql into the database our installation isdone.

To configure Magento part, one needs to copy required filesform /carts directory of Affiliate module and then (turn offCache) go to System > Configuration and set the requiredoptions. After that you can go back to your Affiliate ForAll application, upload some banners and set their url linksto point to your Magento shop. When you test banner thelinks (click on one of them to get you to Magento store,then Magento store url should have a little GET variablein url like ?ref=someNum). Now when you do the entirecheckout process, order info gets recorded to Affiliate For Allapplication.

If you wish to play with Affiliate For All without installing it,you can check out the demo (just use “Admin” both for userand password).

There are 2 comments

New Magento theme tutorial | InchooThere are many new Magento stores that are publishedeach day. If you are with Magento for a longer time, youwill also notice that many of those look similar to defaultor modern Magento theme. Creating an totally unique andcustom one can be a difficult process, easpecially taking intoconsideration number of different interfaces we have. This iswhy many Magento developers choose to use the CSS fromone of mendioned Magento themes that come with defaultinstallation and style those up. This is not a bad choice at allas it speeds up the process and those default themes are verygood. But, for those of you who wish to make an extra effort,we suggest that you to take a look at Magento Blank Theme fora head start.

Before you get to this point, be sure to read MagentoDesigner’s Guide, where the Magento design terminology isexplained in this PDF document.

Blank Theme is a sample skeleton theme for Magento designerand a perfect way to start a new one. Let’s be honest, we willrarely want to develop a totally new layout. We wish the headeron the top, footer on the bottom. We wish to have 1, 2 or 3columns, we wish to have boxes. Blank Theme does just that:provides a layout, but without any heavy styling. This makesit excellent base ground for a new Magento project. It doesn’tcome with default installation, so you will have to use MagentoConnect to get it.http://www.magentocommerce.com/extension/518/blank-theme

Page 14: Inchoo s magento posts

September 8th, 2009 Published by: inchoo

Created using zinepal.com. Go online to create your own zines or read what others have already published. 14

Magento community member Ross gave a good reviewcomment:This is a great theme to use for wire-framing or as a basefor developing a custom theme! It looks like a lot of work hasgone in to slimming down the HTML and CSS, which makesit much easier to work with compared to the default theme.I particularly appreciate the well structured and commentedCSS. The only things I would want different at this stage isfor the ‘callouts’ to be taken out (and removal of associatedmedia images), and for this theme to be included in the mainMagento download (I would even like it to be the ‘default’). 5stars from me!

Take a sneak peak of how does product info page looks linewith no styling, but in finished layout. I’m sure that the CSSwizards will find this invaluable.

There are 11 comments

Magento product view page analysis |InchooOne of the most edited file in Magento is the template fileView.phtml file. Reason for this is that a lot of clients wouldlike to rearrange it differently on their online stores. Here isthe analysis of that file and the list of all the methods it uses.

One thing to keep in mind, this document shows you theView.phtml block file and shows you it’s inherited methods.All of the Magento block files have the similar inheritanceprinciple. Therefore to find out the available methods all youneed to do is open up the extended (inherited) classes.

If you are using some smart IDE solution like NetBeans 6.5with PHP code completion support, you can simply do theMage_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 themanual way.

Create a Color Switcher in MagentoMagento comes packed with a lot of options. But no matterhow many options you put into some product you can nevercover all of them. One of such options (for now) is a colorswitcher in Magento. To be more precise, an image switcherbased on color selection.

Recently I’ve made a screencast on my site on this subject,with somewhat different title. The idea is to have a dropdownbox from which you choose a color and based on the colorselection product image changes. All of this is to be based onsome simple javascript (in my case, jQuery).

Before we continue, you might want to see color switcher inaction. We used this solution on our Kapitol Reef project.

First you need to upload some images to your product andgive them some meaningful names like Red, Blue, Greendepending on your product color. When I say give themname, I mean on label values. Same goes for creating customattribute. You create a dropdown selection box and create thesame amount of dropdown options as you have images, givingthem the same name Red, Green, Blue… and so on. Here aresome images for you to see what I’m talking about:

Page 15: Inchoo s magento posts

September 8th, 2009 Published by: inchoo

Created using zinepal.com. Go online to create your own zines or read what others have already published. 15

After this is done we go to the code part. There are three thingsyou need to do here.Upload the jQuery and save it into the /js/jquery/jquery.js.One important note on jQuery; for some reason I had to usejQuery 1.2.3 to get this example working. Latest version 1.2.6(as of time of this writing) did not work. You can see the exacterror it gave me on my screencast.Now you need to modify /template/page/html/head.phtmlfile to include the jQuery script (or any other if you can codethe same logic into it) and write down few lines of JS todo the switching (you can download my version of file herehead.phtml)And finaly, you need to modify the /template/catalog/product/view/media.phtml file to grab all of the productimages and dump them into some div. Here is my sample(media.phtml) so just copy paste the code.

And some additional screenshots for you to see final result

After some additional styling you can get some impressiveresults for this. Hope you find it useful.

You can see complete screencast at:http://activecodeline.com/wp-content/uploads/videos/MagentoProductColorChooser.swf

There are 28 comments

Magento’s Onepage Checkout in anutshellFor the last two days I’ve been working on a custom checkoutpage for one of our clients. Basicaly a page can be shownin Magento using simple Core_Template type. Basically allcode is set inside the .phtml file so it can be shown on everypossible page or block, meaning it’s object independent, noinheritance. Something you can call from with your layout fileslike

To complete my work, I had two mayor requirements. Onewas to manage my way around programmable adding a simpleproducts to cart, plus their quantity and other was to docheckout with items in cart. Checkout was to be made withpredefined payment method as well as shipping method. Afterreviewing a lot of Magento’s code involved in checkout processand process of adding products to cart and so on I’ve puttogether what I see as the most short example one can use todo a checkout with such predefined conditions.

If you have such special requirements for your site below is thecode that you can place on whatever file you wish and includeit yout tempalte as block type core/template.

Where ubmitCustomCheckout is the name of the submitbutton or submit input field. To extract addresses you can usesomething like

Magento official documentationdownloadWe were among a few of the studios to receive the early releaseof the Magento documentation before it’s official release date.

We broke the embargo ’cause we just didn’t have the heartto keep it to our selves, we all now how painful it is to workwithout it.

Page 16: Inchoo s magento posts

September 8th, 2009 Published by: inchoo

Created using zinepal.com. Go online to create your own zines or read what others have already published. 16

Designer's Guide to Magento PDFdownload | InchooAfter many developed CRE Loaded’s online stores andwatching Magento development progress for quite some time,I decided it was time to use Magento with my next client. Mystarting point for development was official Designer’s guide.I’m the type of guy who likes to have documents nice&clean,so I tried to print it but print was a mess. That’s when I decidedto create PDF of the official documentation for easy print. Thisis probably the best starting tutorial for creating a fresh newMagento template.

I plan to write a short related tutorials in the days of 1stMagento development project, so I invite you to subscribe toRSS if you wish to be posted.

Custom admin theme in MagentoAs mentioned on Magento forums the easiest way to achievethis is with overriding adminhtml config with your localcustom one and activate it as module.

This is just a small example of different approach with AdminTheme config option in admin panel, to show you how thingscan be done in different ways in Magento.

Follow directory structure, copy files to their place and you willnotice new “Admin Theme” option in System->Configuration->General->Design (Default Config scope). Your theme goesin app/design/adminhtml/default/yourthemename folder. Itdoesn’t need to be whole theme of course, just the files you’rechanging.

Disabling wishlist functionalityIf like many of the Magento store owners you find that some ofthe built-in features are not useful to you or to your customersyou can always disable them via the admin interface buydisabling their respective modules.

Wishlist is not one of them.

To remove all of the traces of the wishlist functionality youneed to do the following:

1. Go to the Admin interface (select the appropriate scope)and under System -> Configuration -> Customers -> Whishlistselect “No” under the “Enabled” in the General options.

This will remove all of the whishlist links in the magento blocksas well as the whishlist itself.

2. Just to make things perfect you shouldcheck the (yourskinname)/template/catalog/product/view/addto.phtml and remove the “pipe” character from that file sothat it doesn’t disturb the looks of your site

3. Finally, since you do not need Whishlist anymore it is wise todisable it’s respective module output thru the admin interface(Go to: System -> Configuration ->Advanced->Advanced andset disable “Mage_Whishlist” )

That’s it. Your whish is Magento’s command.

There are 4 comments

Magento Installation with SVN or WgetUnix command | InchooThose of you who know what SVN is, feel free to skip thisarticle. Those of you who are not familiar with SVN, this isa must-read. If you use standard FTP to upload all Magentofiles, you may find this process very time consuming. Magento1.1.8 has over 6.700 files in over 2.200 folders. FTPing cansometimes take few hours on some servers. Let’s look atalternatives.

Both alternatives require SSH access to the server. I’m awarethat some low quality webhosting providers do not provideyou with SSH info immediately. If you don’t have SSH info,ask webhosting support. If they don’t give it to you, changewebhosting provider. Make it a rule, you’ll make your lifemuch easier.

Get yourself familiar with basic UNIX commands first.

Alternative 1: SVNIn the Downloads tab on Magento website, you will notice SVNpage link:http://www.magentocommerce.com/svn

You can see how short this page is. You have 2 commandsyou can run at SVN. You can chack latest work in progress oryou can checkout latest stable version. If you are starting todevelop a real project, you will probably want a stable version.

Let’s look at the original command:svn checkout http://svn.magentocommerce.com/source/branches/1.1

This is probably not the exact command you wish to run onthe server. It will place the files in trunk folder. I will assumetwo things:

1. You will want the clean code

2. You will want to specify the folder where you wishMagento to be installed

If those are correct assumptions, you will want to run acommand similar to this one:svn export --force http://svn.magentocommerce.com/source/branches/1.1shop

• svn – This is the command

• export - The difference with checkout is that with anexport, you get a clean copy of the code, and none ofthe subversion metadata, so it can’t be used to svn up ormake further changes.

• –force – you will overwrite all of the folders and files ifthey exist

• http://svn.magentocommerce.com/source/branches/1.1 - this is SVN URL. Leave itintact.

Page 17: Inchoo s magento posts

September 8th, 2009 Published by: inchoo

Created using zinepal.com. Go online to create your own zines or read what others have already published. 17

• shop - the name of the folder you wish to place the filesinto. You may set the folders name to your likings.

Read more about SVN at Wikipedia SVN Page and Subversionofficial site.

Alternative 2: Installing via wgetI will not be very descriptive here. This alternative is very wellexplained on Magento website in Wiki section:http://www.magentocommerce.com/wiki/groups/227/installing_magento_via_shell_ssh

Both scenarios will only place files. You still need to run webbased installer afterward. But, that is another story.

There are 6 comments

Custom Transactional EmailsSince transactional emails are very important for the processof online shopping you need to have them set up just the youwant them and the default templates just don’t cut it. Youneed your own logo, email data and custom verbiage to beconsistent with the image of your company.

Here how it’s done :

1. Creating custom transactional e-mails via Admin

a) In the admin panel of your magento installation go to:System->Transactional Emails

You’ll be presented with a list of default emails. You’ll needto create a custom email so the only way to avoid writing ourcustom templates from scratch is to use the existing code ofthe template.Hint: If you want to see the template before copying, first clickon the “Preview” button on the right.

b) To create the new template click on the “Add new template”above the “Transactional Emails” list. This is the part whereMagento helps you with the option to load a deafult templatefor you to customize. Nice feature indeed.

Once you have loaded the deafult template give it a uniquename under the “Template name” input field by adding aprefix 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 defaultand custom emails.

Afterwards you can easily customize the verbiage and stylingwithin the “Template subject” and “Template content”.

The “Template content” is the body of the message that theuser will recieve upon transaction so be sure to change the E-mail, name of the company etc. You’ll need to upload the logoof your company in the images folder of the skin you’re using.

Once you are done with editing, save the changes and repeatthe 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> Configuration > Sales > Sales Emails and select thecorresponding template minding the configuration scope.

After you’re done with setting your new templates save theconfiguration by clicking on the “Save config”.

That’s it. Wise thing to do now would be to check how theemails look when received so make a test purchase to verifyeverything is the way it should be.

There are 3 comments

Bestseller products in MagentoBestseller or best selling product is one of the features peopletend to ask for when it comes to Magento™.

There are multiple ways to implement this feature.

In this example, I’m not using controller or model directoriesat all; I’m going to show you how to implement this featureusing only one file: the View.

Basically, what you need to do is to create the directory insideyour template directory and place the bestseller.phtml file init. In my example, I’m using the custom-created directory /inchoo. All of the screenshots provided here are based on thatdirectory structure.

Adding this feature to your store is a matter of two simplesteps:

• copy bestseller-phtml file to your directory

• display the block on home page

To add a block to a home page, you simply log into theMagento, CMS > Manage Pages > Home. Then add thefollowing to the content area:

{{block type=”core/template” template=”inchoo/bestseller.phtml”}}

Notice the type attribute. I used core/template which meansyou can place this code anywhere in your site and it will work.Code does not inherit any collection objects from controllerssince it has none. All that is necessary for the bestseller.phtmlto work is defined in that single file.

One more thing: If you study the code in bestseller.phtml fileyou will see, at the very top of the file, the part that says: $this->show_total.

Page 18: Inchoo s magento posts

September 8th, 2009 Published by: inchoo

Created using zinepal.com. Go online to create your own zines or read what others have already published. 18

If I were to write

{{block type=”core/template” show_total=”12″template=”inchoo/bestseller.phtml”}}

in my home page, then $this would be assigned propertyshow_total with a value of 12.

Therefore, the provided bestseller.phtml file provides theoption of setting the number of products you wish to see listed.

Here is the bestseller.phtml packed in bestseller.zip.

Hope you find this useful.

There are 20 comments

Magento 1.2. is out with downloadableproducts | InchooJust at the dawn of 2008, Varien launched a new versionof Magento: 1.2. Upgrading previous Magento versions wassometimes not an easy task since Varien used to changestandard function names which caused themes to break. Webackup the site, made a copy, took a deep breath, expected theworse, and… Nothing The upgrade went smoothly. Wow,that felt good.

We were joking at the company today.

Zeljko: You know what’s easy in Magento?Branko: There is nothing easy in Magento!

Zeljko is an front end interface developer, while Branko isa programmer. Although creating Magento theme is a clearprocess if you follow designer’s guide, programming is muchmore complex. Before this version, Magento upgrades used tocause troubles. Hope this is over.

There is always a good practice NOT to update platform tolatest version immediately. Even in this case this proved tobe valid. Two days after version 1.2. came version 1.2.0.1. thatfixed some flaws. Keep this in mind when you wish to upgradeto newest version of the platform immediately after it appears.

New version sorts some issues from Magento 1.1.x versionsand brings some highly requested features such as:

• Support for Downloadable Products. (to see this newproduct type in action visit the Magento Demo Store. Weadded an example of an MP3 product and an eBook )

• Added Layered Navigation to site search result page,with control on the attribute level to include or excludeattributes used on the search results page.

• Improved site search to utilize MySQL fulltext search

• Added support for fixed-taxes on product level for suchtaxes as “State Environmental Fee” in the USA and“WEEE/DEEE” in the EU.

• Upgraded Zend Framework to the latest stable version1.7.2

• Added a Layered Navigation Cache for improvedperformance of large catalogs (currently in beta and isNOT recommended for production use).

If you need to upgrade existing Magento version through theMagento Connect Manager to 1.2.0.1, follow this steps:

• Do NOT use your live or production site. We suggestmaking a copy of your site and upgrading that copy first.

• Backup your index.php and .htaccess files (if modified)

• Log into your Magento Connect Manager.

• Select the ‘Setting’ tab.

• Change the Preferred State to ‘Stable’, and save settings.

• For the Mage_All_Latest package select upgrade.

• Click on the ‘Commit Changes’ button. The upgradeshould start.

• After upgrade is complete click on the ‘Refresh’ button.

• Copy your original index.php and .htaccess files back (ifneeded)

• Log into your admin and rebuild search index

• You should now have Magento 1.2.0 installed.

Happy Magentizing

There are 1 comments

Listing out products on sale in Magento |InchooOne of my recent articles was on the subject of sorting “OnSale” product in Magento. The following is a cleaner and moreadvanced look at how—with few tricks and smart moves—youcan reuse existing Magento code and modify it to suit yourneeds.

Product can be “on sale” in two ways:

1. when an item has a special price assigned to it on theindividual level, or

2. when a special promotion “covers” the item

It is important to remember that you don’t have to set up thespecial price on each product to get it to be on sale; you can

Page 19: Inchoo s magento posts

September 8th, 2009 Published by: inchoo

Created using zinepal.com. Go online to create your own zines or read what others have already published. 19

simply create a promotion rule and say something like “Set allthe products in Category X to be on sale.”

I provided few screenshots at the bottom of this article toprovide a closer look at what I’m talking about. I will not gointo too much details here since this is a bit more advancedHOW TO, but here is the process in a nutshell:

First, create a copy of /catalog/product/list.phtml fileand name it onsale_list.phtml. Here is my version ofonsale_list.phtml file.

Second, “activate” this new file. There are few ways you can dothis. Let’s say you wish to assign this onsale_list.phtml on oneof our categories, named “On Sale,” for instance.

We then go to Categories > Manage Categories > On Sale…select Custom design and under Custom layout update, placethe following:

product_list_toolbar

If you now go to your category On Sale, it should only showproducts you have assigned to category “On sale” that have aspecial 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 allthe items assigned to the same “On sale” category (covered bypromotion 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 somefeedback or additional suggestions.

There are 3 comments

MagentoAfter many weeks of work, our 1st Magento project hitthe Web: TeraFlex Suspensions. As the purpose of the site

Page 20: Inchoo s magento posts

September 8th, 2009 Published by: inchoo

Created using zinepal.com. Go online to create your own zines or read what others have already published. 20

in not primarily selling, but also branding and communitydevelopment, we decided to use Wordpress and Magentocombination to accomplish the client’s goals.

The Magento portion is visible at http://www.teraflex.biz/products/. We created an original and custom theme fromscratch since we did not want it to look like the default one or tohave a feel similar to the default one. It was not an easy task asthe learning curve for Magento template system is quite steepcompared to other solutions. However, it is worth the time.

We added featured products to products page, the lightbox toproducts info page, and numerous styles that made this storequite unique.

WordpressAll the menu elements outside Products tab are run byWordpress. We have stuff like:

All of these elements turn Wordpress into a feature-rich CMSsuitable for larger projects.

How do you like the new site? Feel free to post a comment.

There are 4 comments

Place Contact form in CMS Page inMagento | InchooAs you know, Magento has a built-in contact form that canbe used for general contacts. That form isn’t part of any CMSpage, you cannot edit some introduction text, you cannotadd phone numbers administration, and you cannot see thebreadcrumbs. If you wish to edit text in that default contactform, you will need to update front-end files. Luckily, there isan alternative.

If you are a developer, editing your contact form HTML is aneasy task. You only need to open file:app/design/frontend/default/[yourtheme]/template/contacts/form.phtml and you will find your way around.

However, there are cases when you would like to give yourclient an option to edit some intro text, edit his phonenumbers, edit text behind the form, etc. You are probablyguessing that it would be nice to be able to embed contact formin some CMS page. No problem.

I know that this is not some breakthrough article, but I willcertanly create contact CMS page on all of my future Magentoprojects.

Custom price filter in MagentoQuite a few people have asked me for a price filter functionalitythat comes with Magento. Mostly, the questions are same:How does one put the price filter anywhere on the page? Howdoes one set it’s on price ranges in that filter? What definesdefault price ranges. Is it possible to set price filter for all myproducts instead of just single category? Lot of questions. Theanswer might be simpler then you might think.

There are two ways to approach this problem. Head troughwall or stop and think approach.Default Magento price filterworks with algoritam which functions on the following logic

1. Find the lowest and highest price in the range of filteredproducts.

2. Find what power of 10 these are in.

3. If there’s 2 or less ranges available we go one powerdown.

So one approach would to be to somehow override defaultprice filter logic by rewriting it and embedding some new logicof yours. I call this one head trough wall. I’m not implyingthat this is wrong approach, on the contrary this is the genericsolution. However it does require some more time to come upwith.

Second solution is by far more easier. It involves using simpleHTML (could use it in your static blocks).

If one wishes to use the price range filter to filter trough entireproduct collection he can simply create a subcategory underthe Default root category and add all of the products to it. Thenwe write some static html code with urls made to fire up theprice filter.

Let’s look at the default Magento sample data. It gies you thefollowing category layout

Root Catalog (6)

• Furniture (6)

• Living Room (4)

Page 21: Inchoo s magento posts

September 8th, 2009 Published by: inchoo

Created using zinepal.com. Go online to create your own zines or read what others have already published. 21

• Bed Room (4)

Notice the url link above… It wont work if you put it like http://somesite.domain/furniture/living-room/?price=1%2C199

It wont work like that because by default you do not have pricefilter functionality covering second subcategory level. Whatthis means is that following link wont workhttp://somesite.domain/furniture/living-room/?price=1%2C199

Since the first subcategory level is Furniture, and second areLiving Room and Bed Room, by default the following url willwork with or withoutindex.php.

• url: http://somesite.domain/furniture/?price=1%2C199

• url: http://somesite.domain/index.php/furniture/?price=1%2C199

You could therefore create simple HTML like

<select onchange=”setLocation(this.value)”><option value=”http://somesite.domain/all/?price=1%2C10000″> <!– Here you place your own ranges –>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 inabove HTML code. The /all part of the url is the url key of theAll category in which we added all of our products.

Last, but not least is understanding of the “price=…”parametar.

1%2C10000 – where 1 stands for first range of 10000 (lastnumber)or

2%2C10000 – where 2 stands for second ranfge of 10000,(first would be 0-10000).

So if we were to write something like3%2C10 it would be the price range from 20-30, where 3stands for third range of tens (number 10). Firs is from 0-10,second 10-20, third 20-30.

Most of this is quite selfexplanaory so, for those who needthis kind of functionality across some special pages, hope youintegrate it withouth any problems.

There are 4 comments

Magentique - Magento ShowcaseLaunched | InchooWe launched one internal project today: magentique.com. Forthe last few months we were working almost exlusively onMagento projects. As many of you, we were also wonderingwhat sites are developed with it. There are very little galleriesthat give the list of Magento powered stores and that’s howthis idea was created. We present you Magentique and hopeyou like it.

Curiosity about this project is that we used Magento to developit. You’ll not see a shopping cart or Add to Cart buttons, butMagento was the tool we used. Take a look at the gallery,comment the sites you like. Subscribe to RSS. Share it withyou friends. Also, we would welcome your submissions of newstores you own, you created or just the ones you like.

Hi,I like your work with Magento, and i see that y’re notaffraid of experimenting. My question is relative to http://www.raspberrykids.com. I like the layout, especially folder tabwith ‘Description’, ‘Tags’ etc. I didnt find such a feature inMagento. Can you explain it on Inchoo web (in some article),of course, only when it isnt company secret ) Thankx. Havea nice day.

Online stores on magentique.com are not only our works.Magentique is the gallery that lists all Magento sites and notonly our portfolio.

Regarding blog topics, we try to write about the things we workon. However, we can not cover all Magento possibilities. Hopeyou agree.

Page 22: Inchoo s magento posts

September 8th, 2009 Published by: inchoo

Created using zinepal.com. Go online to create your own zines or read what others have already published. 22

Can an online store have only one product? Sure it can andwe give you the one that just launched. Kapitol Reef wasfounded to develop, perfect, manufacture and market a newbreed of snorkels based upon pressure-balanced breathing inthe aquatic environment. The entire focus for this companyis to deliver best-of-class products, starting with the snorkel.Kapitol Reef is in the market for many years and this weekthey published a new site. Similar to our work on Teraflexproject, we used Wordpress and Magento platforms for thedevelopment.

The request was to have an extensive online store solutionwith multiple customers groups. Those groups should havedifferent product prices and different payment options.Magento seemed like a great solution for such a request,although the initial concern was if it might be an overkillconsidering the fact we only have one product to start with?

When the development started to roll out, the concern was nomore. This will work superbly. We give you the new Magentostore that uses a combination of Wordpress and Magento.Magento portion of the site is visible from the Online Store tab.

You may also notice a styled color switcher feature wedeveloped for this project. As this product comes in variouscolors, we decided to spice up the product info page and stylethe color choosing to replace the default select box.

There are 7 comments

Form Validation in Magento | InchooOne of the coolest things in Magento is a form validation, andthe way how it’s done. Magento uses Prototype library (which,personlay, I’m not a big fan of) to manage form validation. Allyou need to do when writing custom form is to assign a validclass names to your input fields. Here is an example of howyour custom form might look in order to get use of automaticform validation.

<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>" />

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

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

<input type="submit" name="submit" value="<?php echo $this-/>__('Submit') ?>" />

</form>< ?php /* END OF my-custom-form */?>

<script type="text/javascript">//< ![CDATA[var customForm = new VarienForm('<em><strong>my-custom-form</strong>');//]]></script>

You will notice all of the input fields have one commonclass name, required-entry. I’m not gonna go over all of theavailable class names here. To find available class names, trygoing to One page checkout page, where you have checkoutform, then simply view source and look for class names nextto input, radio select and other fields.

Most important thing besides assigning class names is thatlittle piece of JavaScript below the form. Remember to passform id into the new VarienForm object.

Basically thats it. Constructing the form this way, automaticalymakes your form reuse already existing validation code, theone that the rest of the shop is using.

There are 5 comments

CSRF Attack PreventionIf you login to your Magento admin today, you are welcomedwith message box that says:

CSRF Attack Prevention Read details !

Yesterday Magento team acknowledged CSRF vulnerabilityand provided solution in a form of tutorial to change adminpath (frontName) of your Magento shop.

I find this approach strange and funny at the same time. Ishiding vulnerability new way of fixing it? Especially sincesome users of French Magento forums found similar problemin downloader (Magento connect manager). I can confirm thiscouse i tested it myself. The most funny part was that Magentocached my get request so i couldn’t get rid of my test alert box

Few fast tips for Magento admins:

1. Follow official Magento news, forums, updates.

2. Don’t click suspicious links. These kind of attacks areusually done through malformed links that admin clicksthrough mail, comment, or any other source.

3. Clear “saved passwords” from browsers. Since mostweb browsers offer to remember passwords, and thenautocomplete them, these kind of attack could easily stole yourpassword.

Page 23: Inchoo s magento posts

September 8th, 2009 Published by: inchoo

Created using zinepal.com. Go online to create your own zines or read what others have already published. 23

There are 4 comments

Magento ConnectOne of the first things that really confused me when istart using Magento is Magento connect. I just startedlearning things, so i was looking for some plugin examples. Ivisited Magento connect page with extensions and looked fordownload button, instead i found “Get extension key” one.

If i recall correctly their What is this? explanation wasn’t thesame back then .. or i was just so terrified of Magento at startthat i didn’t understand anything at that point I knew ineed to paste that key somewhere, in something they calledmy Magento connect manager or Magento downloader, but ididn’t understand where it is.

Visit Magento connect page. There are really some greatextensions there and many of them are free.Find extension that interest you, click “Get extension key”,agree with license agreement and get key. Pay attention toStability description field (stable, alpha, beta).

If you click Settings tab of your connect manager you will see“Preferred State” option there. If you’re installing extensionwith different “stability” or you get something similar to

you should change this option to appropriate one. You shouldof course be careful with alphas and betas and know whatyou’re doing.

If you are developer or just interested, ftp to downloader/pearlib/download after you install extension and you’ll findpacked downloaded extensions there.

After you use the downloader do you need to change the folderpermissions back for security reasons or is it OK just to leavethem at 777?

This really depends on your server configuration, howeverit’s always good to restore permissions to defaults if they arechanged to 777, just to be sure.

Magento™ and Google™ WebsiteOptimizerI attended a webinar yesterday called “Maximizing MagentoWebinar: Optimizing Conversions with Website Testing.” Itwas a nice and informative hour-long webinar with Google andMagento team speakers that provided us some really usefulinformation.

First of all, you should know what Google Website Optimizeris. It’s a powerful tool that allows you to test various pageconcepts directly on your visitors and see which of your ideasworks best in practice.

The idea behind Google Website Optimizer is “You shouldtest that.” If you have an idea you don’t know will work—orwhether it will increase you conversions—Google has createdthis tool to help you test it.

Google Website Optimizer is easily integrated in Magento.You can test various changes on your product pages and seewhich ones work best for your visitors. Only product pageintegration between Magento and Google Website Optimizeris made for now, however according to Roy Rubin, we canexpect integration with our shopping cart and checkout pagessoon.

What Google Website Optimizer does is serve differentvariations of your site to the visitors so that you can test whichone converts best. You can set up easily “A-B compare” whereyou serve half of your visitors one page variation and halfof your visitors another. Then all you have to do is compareresults or set up multiple page variations. The Optimizer givesyou nice, clean reports where you can see how are your pagevariations 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,000visitors or more. You can’t know if the page variation isactually good if your test sample was too small.

• Do the big changes first, then fine-tune later. Thisone comes from the Google and their experience withWebsite Optimizer. You should first try to make bigdifferences and see in which direction has the responseyou want, then refine the pages for optimal conversions.If you can’t see the change in first five seconds of viewingthe page variation, the change is too small.

• Beware of HiPPO! This one also comes from Google.HiPPO stands for Highest Paycheck Person’s Opinion.When you have powerful tool such as Google WebsiteOptimizer, you can actually test all the ideas and seewhich one makes you the most money. HiPPO will oftenwant to serve his visitors his idea—despite the fact that hecould earn more by serving them some other variation.

Page 24: Inchoo s magento posts

September 8th, 2009 Published by: inchoo

Created using zinepal.com. Go online to create your own zines or read what others have already published. 24

There are 1 comments

Extending Order object and hooking onevent in MagentoOne of my previous articles was a Magento Event Hooks.This one will be a practical example on using the eventhooks. Although the more proper way would be to call themObservers, bare with me. I’m use to this “hooks”.

Here’s the walk-trough on how to add a new property(attribute) to an object (Mage_Sales_Model_Order object inour case).

To add an attribute to object, we need (the dirty way) 2 littlesteps

• Go to app/code/core/Mage folder. If you drill downinto most of the folders and go to /Model subfolderthere you will see /Entity subfolder under /Model formost of the stuff (modules) under /Mage. For ourexample we go to app/code/core/Mage/Sales/Model/Entity/Setup.php file. This Setup.php file holds Objectsfields definitions in database. We need to add new fieldsto public function getDefaultEntities(). Once again, thisis the “quick” and “dirty” way of adding new attributes.The “propper” way would be to create the sql file andupdate config file to read the new sql file and… Whatever,I haven’t got the whole day Here is the code in myexample, that I added to the array in public functiongetDefaultEntities().

'inchoo_custom_info' => array('type' => 'text','backend' => '','frontend' => '','label' => 'Extra info','input' => 'textarea','class' => '','source' => '','global' => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_STORE,'visible' => true,'required' => false,'user_defined' => false,'default' => '','searchable' => false,'filterable' => false,'comparable' => false,'visible_on_front' => true,'visible_in_advanced_search' => false,'unique' => false,),

Basically you can copy-paste some existing attribute thatsuites you the most and just change the array key name.

• Run this code only once (you can place it inside any file,like index.php or view.phtml or any other that you willexecute) then uncomment or remove this code.

$setup = new Mage_Eav_Model_Entity_Setup('core_setup');$AttrCode = 'inchoo_custom_info';

$settings = array('position' => 1, 'is_required' => 0);$setup->addAttribute('11', $AttrCode, $settings);

NOTE: In code above, note the line $setup->addAttribute(’11′, $AttrCode, $settings). You probabily

wonder where did I pool the number “11″ from?If you open your database (with any tool), and goto sales_order table, you will notice entity_type_idcolumn. Each and every entry in sales_order tablehas the same value for entity_type_id column. In myMagento installation, this value is “11″. Keep in mindthat this does not have to mean yours will also be thesame.

To confirm everything went ok, just Search the databasefor the “inchoo_custom_info” (or whatever you used forattribute name).

Ok, now that we added new attribute (property) to Orderobject, we will go on to Observer part. We will create ahook that will watch for successfull checkout process andtrigger appropriate code execution. In my example I neededto add some extra info to order upon it’s successfull creation.Meaning as soon as checkout process is successfully executed,order is stored in database with some extra info I saved in itspreviously created field “inchoo_custom_info”.

Here is my Observer file, I called it Observer.php andit’s saved under app/code/local/Inchoo/HookSystem/Model/Observer.php.

< ?php

class Inchoo_HookSystem_Model_Observer{/*** Event Hook: checkout_type_onepage_save_order* @param $observer Varien_Event_Observer*/

public function hookToOrderSaveEvent(){/*** NOTE:* Order has already been saved, now we simply add some stuff to it,* that will be saved to database. We add the stuff to Order object property* called "inchoo_custom_info"*/$order = new Mage_Sales_Model_Order();$incrementId = Mage::getSingleton('checkout/session')->getLastRealOrderId();

$order->loadByIncrementId($incrementId);

$extraInfo = array('shirt_color' => 'Freakin cool blue color','developer_is_freak' => true,'coded_by' => 'Branko Ajzele, Web Application Developer');

$extraInfo = serialize($extraInfo);

$order->setData('inchoo_custom_info', $extraInfo);$order->save();

}}

Since this is a module, we also need to add some configfiles. Here is the content of my app/code/local/Inchoo/HookSystem/etc/config.xml

< ?xml version="1.0"?><config>

Page 25: Inchoo s magento posts

September 8th, 2009 Published by: inchoo

Created using zinepal.com. Go online to create your own zines or read what others have already published. 25

<global><models><hooksystem><class>Inchoo_HookSystem_Model</class></hooksystem></models></global>

<frontend><events><checkout_onepage_controller_success_action><observers><hooksystem_order_success><type>singleton</type><class>hooksystem/observer</class><method>hookToOrderSaveEvent</method></hooksystem_order_success></observers></checkout_onepage_controller_success_action></events></frontend>

</config>

And one more config file to add to app/etc/modules/Inchoo_HookSystem.xml.

< ?xml version="1.0"?><config><modules><inchoo_hooksystem><active>true</active><codepool>local</codepool></inchoo_hooksystem></modules></config>

And for the final step, open the app/design/adminhtml/default/mytheme/template/sales/order/view/tab/info.phtml file and add the following to it:

< ?php /** START CUSTOM Coded by Branko Ajzele | [email protected] */ ?>< ?php/*** NOTE:* 'inchoo_custom_info' assumes you have added new attribute/property to Sale/Order entity* Please use serialize and unserialize with 'inchoo_custom_info'*/$extraInfo = $_order->getData('inchoo_custom_info');?>< ?php if($extraInfo != null or !empty($extraInfo)): ?>< ?php $extraInfo = unserialize($extraInfo) ?><div class="entry-edit"><div class="entry-edit-head"><h4 class="icon-head head-products">Extra order info</h4></div></div><div style="height: 30px; padding: 10px; border: #ccc 1px solid; margin-bottom: 20px;"><pre>< ?php print_r($extraInfo) ?></pre></div><br /><br /><br /><br /><br /><br /><br /><div class="clear"></div>< ?php endif; ?>< ?php /** END CUSTOM Coded by Branko Ajzele | [email protected] */ ?>

Feel free to remove all my comments. One thing to keep inmind here, the url path has the “mytheme” pointing to mycustom theme. Usefull if you do not wish to edit default admintempate files. Cooworker and friend of mine, Ivan Weiller,wrote a nice little plugin for switching the admin themes (to

avoid editing the default one). You can download Adminthememodule here.

Important: Our colour highlighting plugin on this site seems tolower-case some tag names on xml code, so keep that in mindif you experience some trouble with sample code.

Huh, we are done! Final result is shown on image.

Cheers…

There are 8 comments

Happy 1st birthday MagentoMagento celebrates his 1st birthday today and we wish tocongratulate them for the first successful year. In this yearMagento evolved to fully usable online store applicationand reached version 1.1. Over 425,000 downloads makesit the fastest growing ecommerce platform on the market.Community presented over 165 extensions via MagentoConnect, but the real number of add ons is much greater.Inchoo and Surgeworks will keep you posted for about furtherdevelopment.

Unprintable Content (Video, Flash, etc.)

Internal Server ErrorMany of us who started experimenting with this interface andtried to place various values for Base URL, came to a dead endwhere Magento breaks. Usually, we get Internal Server Error500 with each page load. The problem lies in the fact that wecan no longer open the Magento administration to correct theerror. What needs to be done in such a scenario?

One of our clients wrote me a message today:

I have put www.mydomain.com in a bad spot.I changed the base URL to {{base_URL}} andnow im getting a 500 server error on boththe front end and the admin panel. I havelooked through the database and cannot findthe right field to change this value back. Canyou point me in the right direction?

The client went to System> Configuration> Web> Unsecureand placed an invalid value for Base URL field. Beware of thisfield. Unfortunately, Magento just updates it without any pre-warnings, but change of this specific value can cause Magentoto crash.

Usually, we get an error that looks like this:

The server encountered an internal error ormisconfiguration and was unable to completeyour request.

Please contact the server administrator,[email protected] and inform them ofthe time the error occurred, and anything youmight have done that may have caused theerror.

More information about this error may beavailable in the server error log.

Page 26: Inchoo s magento posts

September 8th, 2009 Published by: inchoo

Created using zinepal.com. Go online to create your own zines or read what others have already published. 26

Additionally, a 404 Not Found errorwas encountered while trying to use anErrorDocument to handle the request.

The client was on right path to find a solution. We needto open MySQL (usually via php MyAdmin) and findcore_config_data table. Once there, manually update 2 rows:

1. config_id:3 web/unsecure/base_url => http://www.mydomain.com/

2. config_id:4 web/secure/base_url => https://www.mydomain.com/

Everything should work now. Hope this will help someone.

There are 1 comments

How to fully disable (turn off) MagentomoduleAlthough the title might sound silly and so easy, there are lotof people having difficulties with this. At first turning Magentomodule can be easy as going trough System Configuration> Current Configuration Scope > Advanced > Advanced >Disable Module Output. However, be very careful, this actiononly disables module output as it says. If your module uses,let’s say some Observer functionality to hook into some part ofthe system and does some overriding then those actions won’tbe disabled.

do you have a solution to fully disable a Module just fora specific Website, Store or View? It’s a Problem I’ve beenhaving for a while. An just disabling the output doesn’t do thetrick.

Magento site owners: Get serious, focuson what matters the mostFor the last year or so I have been actively involved inonline store development based on Magento ECOMMERCEplatform. Everyone involved in Magento development can tellyou that Magento extensively uses OOP approach. Althoughnot everyone will agree, I like the way platform has beenarchitectured in the backend. Layouts and config files enableyou great deal of power without even writing a line of PHPcode. Its not perfect, but what is. I believe most of you heardthe “cliche”: “With great power comes great responsibility”.Let’s discuss this in regards to Magento.

There is a plain and simple message I wish to shout to currentand future owners of Magento powered online stores: “Getserious, focus on what matters the most!“.

Now what exactly did I have (and still have) in mind withstatement like this? Unlike WordPress and Drupal (no offense,I use them, I respect them) not everyone can develop qualitymodules (extensions) for Magento. Platform itself requiresdeveloper a decent amount of knowledge from PHP OOPand other fancy object related concepts. As mentioned inone of my previous articles, Observers and “overrides” areamong my favorite concepts (approaches) in Magento moduledevelopment.

One of the projects I was assigned few weeks ago had a greatamount of products, total of 46 268 to be more precise. Mostof these are simple products with “Visibility”:”Nowhere” andare used strictly as Associated products in some Configurableproducts. Configurable products are for the most part shownto the user on frontend. All in all, there is a handful ofConfigurable products in the system, each holding couple ofthousands Associated product.

There are two issues here. First and most annoying issue Icame across in this “WTF” configuration is the performance.Complete collapse of any reasonable execution time. Loadinga page that holds this kind of Configurable product takesfrom 3-9 minutes, both on frontend and backend. I’m talkingabout 3-9 minutes on local machine with maximum resourcesettings for PHP and MySQL. Second issue here is obviousmisunderstanding of Magento product types and how to usethem.

I have already done Magento project with the approximatelysame total number of products in system. Number of productsitself does not impose that much noticeable performancedrop if the products are used the “smart way”. By “smartway” I think in terms where you have wast amountindependent Simple products. Magento can handle that quitewell. However, having large amount of relations like thoseConfigurable Products > Associated Products can kill yourstore to “usability equals zero”.

Here is where I draw the line on developers part. If youare lucky enough to get working on a new Magento relatedproject from scratch you are obliged to recognize these kind ofissues and react on time. Change the approach to the way howproducts need to be presented in the system and so on. It isunacceptable to create thousands of Associated products justto make them affect the final price of Configurable product.If you need to come up with solution like this, try developinga custom module to work around the issue not go with it.Performance drop is guarantied in cases like above. So if theclient comes with the idea like “I have a lot of products thatkind of fall into the category of Configurable products that canuse this and that as Associated product to stay dynamic in thatand that selection…” you need to stop, think twice how thiswill affect store as whole and then propose the solution. Noneed to blindly go with clients (owners) suggestions. His primewish is to get his store working and selling with least amountof budget as possible.

Now lets look at the owners (clients). I’ve noticed a lot ofowners have “special” request for Magento store. Lot of themhave products that kind of fit under the category of Grouped,Bundled and Configurable products. This is great actually,since all of these come out of the box in Magento. What’snot so great is that their wishes can sometimes be quite“unreasonable”. Lets look at the “color switcher” functionalitylot of people ask to be implemented. This kind of functionalityis mostly done by JavaScript where one hides select box thatMagento would normally show under product options, and soon.

Page 27: Inchoo s magento posts

September 8th, 2009 Published by: inchoo

Created using zinepal.com. Go online to create your own zines or read what others have already published. 27

Sure it looks great, its looks cool but the real question is “Howmuch will it improve your selling?”. I realize the usability canbe as much as important as functionality. By now, there areeven some color switcher modules you can buy. However,most of magento modules require additional work to beproperly implemented in order to fit the owners wishes. Dueto the complexity of Magento platform, sometimes even thesmaller changes require lot of time and effort on developerpart. This would all be great and shinny if everything wouldwork after the upgrading Magento store when the new versionappears. All this leaves entire development process focused onthe “little things”. I say, why not style the theme to the endwith the default Magento page setup. Why change the outputof product view page? Why not leave it default, just fully style itto match your design. This kinf of approach would be far moresafer in terms of upgrades and in terms of bringing the projectto the end in as much as possible short timing.

What I’m trying to say, Magento comes extremely featurerich out of the box. Development time is not free, and to myopinion it should be focused on either building fresh, newfeatures for the store or at other parts of the system likePromotions, Catalog price rules, Shopping cart price rules,Customer groups. The latter one seem to be relatively ignoredin the big picture.

Adding features like “color switcher” could be left for latterphase of development, the one after the site goes live. The oneyou are sure your store is working the way it should, its stable,nicely styled, optimized for best performance, and quite wellstructured so its relatively bullet prof on updates. Then youcan start adding modules, fancy usability tweaks and so on.

There are 10 comments

Hello everybody. We are very happy to announce that Snippihit the net. This is a personal project of Branko Ajzele, one ofour developers, that went live few days ago. He was developingit for some time now and I hope it will be usable for all of youMagento developers who are trying to find a solution for yourspecific needs. Snippi is a Magento related website for sharingMagento code snippets. You can see it live on http://snippi.net

Finding a solution for specific need can be a nightmare inMagento since you are faced with the process of heavy diggingthrough Magento forum and Magento related blogs. Very soonyou will notice that many people had the same issue as you do,but no concrete answer. You’ll probably find chunks of codethat can help, but you’ll have to put it all together. Snippi’s goalis to help you in this process.

We realize there are already dozens of sites related to snippetsand code sharing, but none for Magento development. Site isbuilt on Drupal CMS. There are still lot of “styling” left to do atthe present time, but the site is usable. Branko hopes that youwill not find the site too ugly since he designed it We all lovethe simplicity of it that makes the code snippets highly usable.

What makes these code snippets special is that little dropdown field next to each snippet entry where you mark downthe version of Magento for which snippet has been tested for.The search functionality is planned soon.

Hopefully this project will become handy in those situationswhere you find yourself with broken Magento code for somereason. The next step for you is to register and share afeedback. Help the community by adding your own examplesof code.

Here is one Snippi example:

There are 2 comments

Advanced Search sidebar boxI was playing a bit with that advanced search form in Magento,so i thought it would be nice touch to add it to left or rightcolumn of the store.

Since that multiple selects were causing problems and i alsohad to get rid of breadcrumb, i created block which extendsMage_CatalogSearch_Block_Advanced_Form functionality,added a little javascript and packed it all to small examplemodule:

Unpack the rar, copy files at its appropriate place followingdirectory structure, disable/enable cache to rebuild configs,layouts, blocks, and you’re on.

Page 28: Inchoo s magento posts

September 8th, 2009 Published by: inchoo

Created using zinepal.com. Go online to create your own zines or read what others have already published. 28

CoffeeFreak – Blank Magento extensionfor building main admin menu withsidebar and tabsMy previous article, CoolDash – Blank Magento extension forbuilding admin system configuration area, was about blankstart-up extension for building System > Configuration adminarea. I used a lot of “funny” attribute names so that “getaround” gets some speed. This extension is somewhat similarto previous one, except its meant to be a blank start-upextension for building items under main admin menu withsidebar and tabs.

Keep in mind that, once again, extension name is something Ipopped 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.

Offline Magento problemsI was working recently on a local server without internetconnection (nothing can stop us !! ) and i noticed thatMagento administration is extremely slow. Some parts ofadministration took up to 10 seconds to load.

On every page view in admin Magento was trying to resolvewidgets.magentocommerce.com address and connect to it fewtimes which caused time delay. His notification system wastrying to grab new message.

The solution was to disable Mage_AdminNotification moduleand since i was offline i didn’t really need it. You can do it inSystem -> Advanced -> Disable modules output

Some other admin parts which are using online resources willstill be slower, like Dashboard for example because it is using

google charts so it’s trying to connect to that, but everythingelse will work fine.

There are 2 comments

Display PromotionThere are two unused product list blocks in Magento whichcan be very useful if you push a few buttons, edit few layouts ..

1. PromotionBlock located in app\code\core\Mage\Catalog\Block\Product\List\Promotion.php

This is basically built in featured product functionality. Itreacts to “promotion” attribute which needs to be created, solet’s clickCatalog->Attributes->Manage Attributes->Create NewAttribute

Attribute Code: promotionScope: Global

Catalog Input Type for Store Owner: Yes/No

Label: Promotion (second tab)

Other params can be left alone, but it’s up to you of course. Ialso labeled it Promotion just for this article.

Now we need to add created attribute to attribute set, sonavigate toCatalog->Attributes->Manage Attribute Sets

select attribute set you’re using and drag promotion to Generalgroup for example.

Page 29: Inchoo s magento posts

September 8th, 2009 Published by: inchoo

Created using zinepal.com. Go online to create your own zines or read what others have already published. 29

Now when you’re editing your products, there is new“Promotion” option under General tab.

Products on which you select Yes will be shown on promotionblock which can be displayed through layouts with

<block type="catalog/product_list_promotion"name="product_promotion" template="catalog/product/list.phtml"/>

or as cms content with

{{block type='catalog/product_list_promotion'template='catalog/product/list.phtml'}}

This attribute should really be included in default attribute setor in Magento sample data.

2. RandomBlock located in app\code\core\Mage\Catalog\Block\Product\List\Random.php

This block loads random product collection from currentstore.

The fastest way to display it would also be something like

<block type="catalog/product_list_random"name="product_random" template="catalog/product/list.phtml"/>

since it also extends product_list block, however, since it israndom product listing, that toolbar has no purpose here, socreate phtml that will suit your shop needs, based on catalog/product/list.phtml. For example, i’m using similar Randomblock to display random products in sidebar.

So long, take care, i’m off …

There are 6 comments

CoolDash – Blank Magento extension forbuilding admin system configurationareaIn order to speed things up with building admin sectionsunder System > Configuration area in Magento I wrote alittle blank extension. Hopefully its a step or two beyond“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 youmight notice when you open config.xmls and system.xmlis the attribute naming. I intentionally used names like“somecooldashmodel2″. I found it extremely difficult, errorprone and annoying to get around in scenarios where differentareas of config files use same names for attributes withdifferent meaning, like “customer”, “catalog” and so on.

Hopefully my “funny” naming scheme in config files will giveyou a better overview on where everything goes. Below are fewscreenshots to see the result.

How to override Magento model classes?Many times we need to implement new functionality ofexisting Magento core classes, but we don’t want to modifycore classes.For controllers, that’s quite easy. Usually we can copycontroller from core and put it in the same place in localdirectory, modify class and that’s it.

Of course, there are better ways to do that (make module),but I’m not going to write about that right now since it is notsubject of this post.

I only mentioned that because we can’t do same thing formodels even if we want to, so how to override Magento modelswithout modifying core files?

Fortunately, that’s very easy =)Let’s make one extension of that kind!

Extension we are going to make will be useless, only differencebetween this extension and original class will be class namevar_dump =)

What we are going to do now is to take a random model classfrom Magento core.Let it be Mage_Wishlist_Model_Item located in app/code/core/Mage/Wishlist/Model/Item.php

Page 30: Inchoo s magento posts

September 8th, 2009 Published by: inchoo

Created using zinepal.com. Go online to create your own zines or read what others have already published. 30

What we want to do is to add new functionality to that class,so let’s make new module.

Call it Inchoo_Wishlist.

Create app/code/local/Inchoo/Wishlist/model/ directoryand copy app/code/core/Mage/Wishlist/Model/Item.phpthere.

Now, rename class Mage_Wishlist_Model_Item toInchoo_Wishlist_Model_Item.

Add this line:

var_dump(get_class($this)); exit();

in loadByProductWishlist method

Now, let’s create Inchoo_Wishlist.xml in app/etc/modules/Put this code there:

< ?xml version="1.0"?><config> <modules> <inchoo_wishlist> <active>true</active> <codepool>local</codepool> </inchoo_wishlist> </modules></config>

Now, make app/code/local/Inchoo/Wishlist/etc/Config.xmlfile and put this code there:

< ?xml version="1.0"?><config> <modules> <inchoo_wishlist> <version>0.1</version> </inchoo_wishlist> </modules> <global> <models> <wishlist> <rewrite> <item>Inchoo_Wishlist_Model_Item</item> </rewrite> </wishlist> </models> </global></config>

You are done! Try to add something to wishlist! =)Play with other models as well!

Cheers ^_^

There are 5 comments

Free Magento Themes vs CustomMagento DesignThis blog post describes pros and cons of having a freeMagento theme versus having a custom Magento design froma marketing perspective.

Free Magento Themes:There are some pretty obvious advantages of using a freeMagento theme:

• It’s free. – This one is a no-brainer, you don’t need toinvest any money in it.

• It’s fast. – You don’t need to wait for it to be finished, youjust download it and use it.

• It works. – Most of the free Magento themes work justfine with Magento out of the box.

However, truth be told, I believe the cons of having a freeMagento theme give you enough reason to go for customdesign:

• It’s unprofessional. – A visitor (your potential buyer)might realize you’re using a free theme. This will makehim wonder, can he really trust your website? Is it a realcompany standing behind this online store? Can I reallygive my credit card to these guys? They probably aren’t aserious company if they don’t have money for the designthat fits their company’s identity.

• There might be no support. – If something goes wrong,there might be no one to help you. Magento can changea lot at upgrade and some themes might start showingerrors.

• There might be no support for new features. –Magento is constantly developing ecommerce platformand new features will always be presented. Some ofthe free templates might not keep up with Magento’sdevelopment and you’ll end up without the ability to usesome of the cool new features that rolled out, wile yourcompetitors with custom design will have this advantage.

• The free theme probably isn’t really optimized for bestconversion rate. – Some free themes are done withconversion rates in mind, however, the conversion rateoptimization usually depends on your niche and targetedaudience. A design and layout that works for a certaincompany might not be so good in converting visitors intosales in your niche.

Custom designed Magento themes:I will not list disadvantages of custom designed Magentothemes since their disadvantages are already listed asadvantages of free themes. Here are some really importantpros for getting yourself a custom designed Magento theme:

• Unique design that fits your company’s identity. –This is extremely important if you’re into any seriousbusiness. Building a strong corporate identity is crucialfor establishing a recognized brand. Your online storewill not only make you profit with the sales you make, butit will also help build a brand image with your targetedaudience.

• Someone you can count on. – If you choose a reliablecompany to create a Magento theme for your store, youknow they will be there once the Magento upgrade comesto fix any potential problems. They will be there to helpyou change things around once the change is requiredand they will be there to consult you and share theirexperience and best practices.

Page 31: Inchoo s magento posts

September 8th, 2009 Published by: inchoo

Created using zinepal.com. Go online to create your own zines or read what others have already published. 31

• Unique features. – Your online store is specific, you area member of some niche. Most niches will require someadditional functions that Magento doesn’t support bydefault to make the best out of your online store. If youchoose to work with experienced development company,they will be able to provide you with developmentsolutions for your problems. This is something you can’tget with free or premium Magento themes.

There are 2 comments

Creating Custom Shipping Method inMagento - The Tutorial | InchooIn this article I will demonstrate how to write custom shippingmethod in Magento commerce.First we need to write our shipping method, it’s a class in folderapp/code/core/Mage/Shipping/Model/Carrier/.

I called it Inchoocustom.php and it’s based on Flat rateshipping method but you can developed your own class.

< ?php

class Mage_Shipping_Model_Carrier_Inchoocustom extends Mage_Shipping_Model_Carrier_Abstract implements Mage_Shipping_Model_Carrier_Interface{

protected $_code = 'inchoocustom';

public function collectRates(Mage_Shipping_Model_Rate_Request $request) { if (!$this->getConfigFlag('active')) { return false; }

$freeBoxes = 0; if ($request->getAllItems()) { foreach ($request->getAllItems() as $item) { if ($item->getFreeShipping() && !$item->getProduct()->isVirtual()) { $freeBoxes+=$item->getQty(); } } } $this->setFreeBoxes($freeBoxes);

$result = Mage::getModel('shipping/rate_result'); if ($this->getConfigData('type') == 'O') { // per order $shippingPrice = $this->getConfigData('price'); } elseif ($this->getConfigData('type') == 'I') { // per item $shippingPrice = ($request->getPackageQty() * $this->getConfigData('price')) - ($this->getFreeBoxes() * $this->getConfigData('price')); } else { $shippingPrice = false; }

$shippingPrice = $this->getFinalPriceWithHandlingFee($shippingPrice);

if ($shippingPrice !== false) { $method = Mage::getModel('shipping/rate_result_method');

$method->setCarrier('inchoocustom'); $method->setCarrierTitle($this->getConfigData('title'));

$method->setMethod('inchoocustom'); $method->setMethodTitle($this->getConfigData('name'));

if ($request->getFreeShipping() === true || $request->getPackageQty() == $this->getFreeBoxes()) {

$shippingPrice = '0.00'; }

$method->setPrice($shippingPrice); $method->setCost($shippingPrice);

$result->append($method); }

return $result; }

public function getAllowedMethods() { return array('inchoocustom'=>$this->getConfigData('name')); }

}

Pay attention on following lines:

$method->setCarrier('inchoocustom');$method->setCarrierTitle($this->getConfigData('title'));

$method->setMethod('inchoocustom');$method->setMethodTitle($this->getConfigData('name'));

They determine how we will set up our method. Keyword is‘inchoocustom’.In folder app/code/core/Mage/Shipping/etc/ we need to edit

system.xml and config.xml in order to enable our newshipping method.

system.xml:

<inchoocustom translate="label"> <label>Inchoo Custom Shipping Method</label> <frontend_type>text</frontend_type> <sort_order>2</sort_order> <show_in_default>1</show_in_default> <show_in_website>1</show_in_website> <show_in_store>1</show_in_store> <fields> <active translate="label"> <label>Enabled</label> <frontend_type>select</frontend_type> <source_model>adminhtml/system_config_source_yesno</source_model> <sort_order>1</sort_order> <show_in_default>1</show_in_default> <show_in_website>1</show_in_website> <show_in_store>0</show_in_store> </active> <name translate="label"> <label>Method name</label> <frontend_type>text</frontend_type> <sort_order>3</sort_order> <show_in_default>1</show_in_default> <show_in_website>1</show_in_website> <show_in_store>1</show_in_store> </name> <price translate="label"> <label>Price</label> <frontend_type>text</frontend_type> <sort_order>5</sort_order> <show_in_default>1</show_in_default> <show_in_website>1</show_in_website> <show_in_store>0</show_in_store> </price> <handling_type translate="label"> <label>Calculate Handling Fee</label> <frontend_type>select</frontend_type> <source_model>shipping/source_handlingType</source_model>

Page 32: Inchoo s magento posts

September 8th, 2009 Published by: inchoo

Created using zinepal.com. Go online to create your own zines or read what others have already published. 32

<sort_order>7</sort_order> <show_in_default>1</show_in_default> <show_in_website>1</show_in_website> <show_in_store>0</show_in_store> </handling_type> <handling_fee translate="label"> <label>Handling Fee</label> <frontend_type>text</frontend_type> <sort_order>8</sort_order> <show_in_default>1</show_in_default> <show_in_website>1</show_in_website> <show_in_store>0</show_in_store> </handling_fee> <sort_order translate="label"> <label>Sort order</label> <frontend_type>text</frontend_type> </sort_order><sort_order>100</sort_order> <show_in_default>1</show_in_default> <show_in_website>1</show_in_website> <show_in_store>0</show_in_store>

<title translate="label"> <label>Title</label> <frontend_type>text</frontend_type> <sort_order>2</sort_order> <show_in_default>1</show_in_default> <show_in_website>1</show_in_website> <show_in_store>1</show_in_store> </title> <type translate="label"> <label>Type</label> <frontend_type>select</frontend_type> <source_model>adminhtml/system_config_source_shipping_flatrate</source_model> <sort_order>4</sort_order> <show_in_default>1</show_in_default> <show_in_website>1</show_in_website> <show_in_store>0</show_in_store> </type> <sallowspecific translate="label"> <label>Ship to applicable countries</label> <frontend_type>select</frontend_type> <sort_order>90</sort_order> <frontend_class>shipping-applicable-country</frontend_class> <source_model>adminhtml/system_config_source_shipping_allspecificcountries</source_model> <show_in_default>1</show_in_default> <show_in_website>1</show_in_website> <show_in_store>0</show_in_store> </sallowspecific> <specificcountry translate="label"> <label>Ship to Specific countries</label> <frontend_type>multiselect</frontend_type> <sort_order>91</sort_order> <source_model>adminhtml/system_config_source_country</source_model> <show_in_default>1</show_in_default> <show_in_website>1</show_in_website> <show_in_store>0</show_in_store> </specificcountry> <showmethod translate="label"> <label>Show method if not applicable</label> <frontend_type>select</frontend_type> <sort_order>92</sort_order> <source_model>adminhtml/system_config_source_yesno</source_model> <show_in_default>1</show_in_default> <show_in_website>1</show_in_website> <show_in_store>0</show_in_store> </showmethod> <specificerrmsg translate="label"> <label>Displayed Error Message</label> <frontend_type>textarea</frontend_type> <sort_order>80</sort_order> <show_in_default>1</show_in_default> <show_in_website>1</show_in_website> <show_in_store>1</show_in_store>

</specificerrmsg> </fields> </inchoocustom>

config.xml:

<inchoocustom> <active>0</active> <sallowspecific>0</sallowspecific> <model>shipping/carrier_inchoocustom</model> <name>Inchoo Custom Shipping Method</name> <price>5.00</price> <title>Inchoo Custom Shipping Method</title> <type>I</type> <specificerrmsg>This shipping method is currently unavailable. If you would like to ship using this shipping method, please contact us.</specificerrmsg> <handling_type>F</handling_type> </inchoocustom>

Now we need to enable our new shipping method in adminpanel (System->Configuration->Shipping Methods)And we have our custom shipping method.

Enjoy coding.

There are 11 comments

How to make TinyMCE work with MagentoCMS pagesLatest version of Magento, as of time of this writing, is 1.3.2.3.Latest, as well as previous versions come with “half-packed”support for TinyMCE editor. There are however few bugs andfew steps that need to be handled in order to enable wysiwygediting in CMS pages. Personally I am not that big of a fanof wysiwyg editors, mostly because I am developer and like toknow what I write down.

However, most of the store owners are not developers or evennot that much technically savvy people (not that this is abad thing) and they could use wysiwyg editors when adding,modifying content.

Here I will walk you trough few simple steps that will makeyou enable wysiwyg editing by using TinyMCE. You can seethe screenshots of final result below.

Step 1: Download and unpack TinyMCE to root /js folder.Two things to keep in mind here. Download regular version(not jQuery version) of TinyMCE. This is due to the fact thatMagento uses Prototype, so we need to avoid conflicts. Second,watch out for unpack location. Your tiny_mce.js file should beaccessible on js/tiny_mce/tiny_mce.js path.

Step 2: Open the app/code/core/Mage/Adminhtml/Block/Cms/Page/Edit/Tab/Main.php file. Locate the

$fieldset->addField('content', 'editor', array('name' => 'content','label' => Mage::helper('cms')->__('Content'),'title' => Mage::helper('cms')->__('Content'),'style' => 'height:36em;','wysiwyg' => false,'required' => true,));

and change it to

$fieldset->addField('content', 'editor', array(

Page 33: Inchoo s magento posts

September 8th, 2009 Published by: inchoo

Created using zinepal.com. Go online to create your own zines or read what others have already published. 33

'name' => 'content','label' => Mage::helper('cms')->__('Content'),'title' => Mage::helper('cms')->__('Content'),'style' => 'height:36em;','wysiwyg' => true,'theme' => 'advanced','required' => true,));

As you can see, here we changed on existing attribute(’wysiwyg’) value and added new attribute ‘theme’.

Step 3: Open the /lib/Varien/Data/Form/Element/Editor.php file and locate the method getElementHtml().Here we change

$html = '<textarea name="'.$this->getName().'" title="'.$this->getTitle().'" id="'.$this->getHtmlId().'" class="textarea '.$this->getClass().'" '.$this->serialize($this->getHtmlAttributes()).' >'.$this->getEscapedValue().'</textarea><script type="text/javascript">//< ![CDATA[/* tinyMCE.init({mode : "exact",theme : "'.$this->getTheme().'",elements : "' . $element . '",theme_advanced_toolbar_location : "top",theme_advanced_toolbar_align : "left",theme_advanced_path_location : "bottom",extended_valid_elements : "a[name|href|target|title|onclick],img[class|src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name],hr[class|width|size|noshade],font[face|size|color|style],span[class|align|style]",theme_advanced_resize_horizontal : "false",theme_advanced_resizing : "false",apply_source_formatting : "true",convert_urls : "false",force_br_newlines : "true",doctype : \'< !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\'});*///]]></script>';

to

$_storeBaseUrl = str_replace('index.php', '', Mage::getBaseUrl());

//Just to test retrieved url//echo '$_storeBaseUrl: '.$_storeBaseUrl;

$html = '<textarea name="'.$this->getName().'" title="'.$this->getTitle().'" id="'.$this->getHtmlId().'" class="textarea '.$this->getClass().'" '.$this->serialize($this->getHtmlAttributes()).' >'.$this->getEscapedValue().'</textarea><script language="javascript" type="text/javascript" src="'.$_storeBaseUrl.'/js/tiny_mce/tiny_mce.js"></script><script type="text/javascript">//< ![CDATA[Event.observe(window, "load", function() {tinyMCE.init({mode : "exact",theme : "'.$this->getTheme().'",elements : "' . $element . '",theme_advanced_toolbar_location : "top",theme_advanced_toolbar_align : "left",theme_advanced_path_location : "bottom",extended_valid_elements : "a[name|href|target|title|onclick],img[class|src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name],hr[class|width|size|noshade],font[face|size|color|style],span[class|align|style]",theme_advanced_resize_horizontal : "false",theme_advanced_resizing : "false",apply_source_formatting : "true",convert_urls : "false",force_br_newlines : "true",doctype : \'< !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\'});});

//]]></script>';

As you might noticed, I used $_storeBaseUrl in this otherchunk of code to get the valid path to my TinyMCE javascript

file. If you are using store that does not have url rewritesthis is something that needs to be done because yourjavascript file would not be found if you go trough linklike “http://store.local/index.php/js/tiny_mce/tiny_mce.js”.Then you would get TinyMCE shown on CMS page but it wouldbe disabled.

As you can see, there were only three minor changes needed(download, modify, modify) to get the TinyMCE editorworking.

Hope this helps. Cheers.

There are 3 comments

Magento Developer Toolbar prototype |InchooI was playing with some of the Magento controller functionstoday, when I saw my coworker Vedran Subotic strugglingwith turning the Path hints in On and Off every few minutes.Idea cross my mind, and here is the result Inchoo’s MagentoDeveloper Toolbar prototype.

< ?php

class Inchoo_Hints_IndexController extends Mage_Core_Controller_Front_Action{

public function init(){

}

public function indexAction(){$hints = $this->getRequest()->getParam('hints');

$_db = Mage::getSingleton('core/resource')->getConnection('core_write');

if($hints){if($hints == 'on'){$_db->query("UPDATE core_config_data SET value = '".$_SERVER['REMOTE_ADDR']."' WHERE path = 'dev/restrict/allow_ips'; ");$_db->query("UPDATE core_config_data SET value = 1 WHERE path = 'dev/debug/template_hints';");$_db->query("UPDATE core_config_data SET value = 1 WHERE path = 'dev/debug/template_hints_blocks'; ");}

if($hints == 'off'){$_db->query("UPDATE core_config_data SET value = '' WHERE path = 'dev/restrict/allow_ips'; ");$_db->query("UPDATE core_config_data SET value = 0 WHERE path = 'dev/debug/template_hints';");$_db->query("UPDATE core_config_data SET value = 0 WHERE path = 'dev/debug/template_hints_blocks'; ");}}

$_url = Mage::getUrl('');

if(isset($_SERVER['HTTP_REFERER'])) $_url = $_SERVER['HTTP_REFERER'];

$this->getResponse()->setRedirect($_url);}

public function cleanCacheAction(){$_url = Mage::getUrl('');

if(isset($_SERVER['HTTP_REFERER'])) $_url = $_SERVER['HTTP_REFERER'];

Page 34: Inchoo s magento posts

September 8th, 2009 Published by: inchoo

Created using zinepal.com. Go online to create your own zines or read what others have already published. 34

Mage::app()->cleanCache();

$this->getResponse()->setRedirect($_url);}

public function cleanPhotoCacheAction(){$_url = Mage::getUrl('');

if(isset($_SERVER['HTTP_REFERER'])) $_url = $_SERVER['HTTP_REFERER'];

try {Mage::getModel('catalog/product_image')->clearCache();}catch (Exception $e) { }

$this->getResponse()->setRedirect($_url);}}

< ?php //START INCHOO DEVELOPER TOOLBAR ?>

< ?php$_inchoo_db = Mage::getSingleton('core/resource')->getConnection('core_write');$hints_are_on = $_inchoo_db->fetchOne("SELECT value FROM core_config_data WHERE path = 'dev/debug/template_hints'");?>

<div style="line-height: 24px; font-size: 10px; font-family: Arial, Verdana; background: #004400; border-bottom:solid 1px white; color: White; margin-top: -5px;"><div><span style="font-weight: bold; margin-right: 10px; margin-left: 10px;">INCHOO TOOLBAR</span>< ?php if($hints_are_on): ?><a style="text-decoration: none; color: #bbbbbb;" href="<?php echo $this->getUrl('inchoohints/index/index/hints/off') ?>">HINTS OFF</a>&amp;amp;amp;nbsp;&amp;amp;amp;nbsp;< ?php else: ?><a style="text-decoration: none; color: #bbbbbb;" href="<?php echo $this->getUrl('inchoohints/index/index/hints/on') ?>">HINTS ON</a>&amp;amp;amp;nbsp;&amp;amp;amp;nbsp;< ?php endif; ?>

<a style="text-decoration: none; color: #bbbbbb;" href="<?php echo $this->getUrl('inchoohints/index/cleanCache') ?>">CLEAN CACHE</a>&amp;amp;amp;nbsp;&amp;amp;amp;nbsp;<a style="text-decoration: none; color: #bbbbbb;" href="<?php echo $this->getUrl('inchoohints/index/cleanPhotoCache') ?>">CLEAN IMAGE CACHE</a></div></div>< ?php //END INCHOO DEVELOPER TOOLBAR ?>

< ?xml version="1.0"?><config><modules><inchoo_hints><version>1.0.0</version></inchoo_hints></modules><frontend><routers><ihints><use>standard</use><args><module>Inchoo_Hints</module><frontname>inchoohints</frontname></args></ihints></routers></frontend></config>

How to use WordPress home page inMagento home page (CMS page)Simple : ) -Ok, lets get down to business. This one is really,really simple, but powerful. In all it greatness Magentolacks the good content management solution (CMS features).Lot of people are heading down the road of integrating

the WordPress and Magento. Probably everyone in webdevelopment has heard about WordPress. Personaly I likethem, from Joomla, Drupal, Wordpress… But there is thatlittle something that makes WordPress far more loving in theeyes of the client. Not to start a flame here, lets get back tothe topic. Due to the lack of the proper content managementin Magento those who use WordPress can easily manage the(home page in this case) content trough WordPress and makeit accessible in Magento CMS page (that you can set to homepage in Magento).

When would you like to do so?

Imagine you have Magento installed in root of your siteand WordPress under some folder like /articles. By defaultWordPress is accessed via http://mysite.domain/articles andMagento is accessed trough http://mysite.domain. Our goalis to have WordPress Page (that we will title “home“) to beaccessible on http://mysite.domain.

Here are the necessary steps involved:

• Create a WordPress page named “home” (under url likehttp://mysite.domain/articles/wp-content)

• Create a file named cmswp_home.phtml under app/design/frontend/default/yourtheme_or_default_theme/template/inchoo/folder

• Create a Magento CMS page (if it already doesnot exist) name it anyway you want and thenadd {{block type=”core/template” template=”inchoo/cmswp_home.phtml”}} to its content

• Set the newly created Magento CMS page as homepage for Magento under Magento Admin System >Configuration > Web > Default Pages > CMS Home Page

Below is the code you need to copy paste into thecmswp_home.phtml file mentioned in above steps.

< ?php

/*** Pulls the content of post named 'home' from WordPress 'wp_posts' table* @author Branko Ajzele* @license GPL*/

//Fetch database connection$_conn = Mage::getSingleton('core/resource')->getConnection('core_write');

//Set query that retrieves the home page content//THIS GOES IF YOU HAVE WORDPRESS AND MAGENTO IN SAME DATABSE$_findHomePage = "SELECT post_content FROM wp_posts WHERE post_name = 'home' AND post_status = 'publish' AND post_type = 'page'";

//Set default value of home page to null, then do a safe check just to be more user friendly$_homePageContent = null;

try {/*//IF YOU HAVE WORDPRESS AND MAGENTO INSTALLED EACH IN ITS OWN DATABASE; THEN USE$conf = array('host' => 'localhost','username' => 'wordpress_db_username','password' => 'wordpress_db_password','dbname' => 'wordpress_db_name');

Page 35: Inchoo s magento posts

September 8th, 2009 Published by: inchoo

Created using zinepal.com. Go online to create your own zines or read what others have already published. 35

$_resource = Mage::getSingleton('core/resource');//Create new connection to new server and new databse$_conn = $_resource->createConnection('place_some_free_random_resource_name_here', 'pdo_mysql', $conf);*/

$_homePageContent = $_conn->fetchOne($_findHomePage);}

catch (Exception $ex) {

//SEND EXCEPTION INFO TO ADMIN?

/** USE $emailSmtpConf, $transport and $mail->send($transport); in case you need to specify SMTP manualy$emailSmtpConf = array('auth' => 'login','ssl' => 'tls','username' => '[email protected]','password' => 'some_pass_here');

$transport = new Zend_Mail_Transport_Smtp('smtp.gmail.com', $emailSmtpConf);*/

$_sendTo_email = '[email protected]';$_sendFrom_email = '[email protected]';

//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('<h1>Invalid HOME PAGE on site detected</h1><p>There seem to be some issues with home page on your site. Please take a look at it.</p><p>Could be that WordPress page has been disabled and this made the query for page return null.</p>');try {//Try to send email//$mail->send($transport);$mail->send();}catch (Exception $ex) {//echo $ex->getMessage();}

}

?>

< ?php if($_homePageContent): ?>< ?php echo $_homePageContent ?>< ?php else: ?><h1>Home page unavailable</h1><p>Seems like home page is unavailable at the moment. We apologize for the inconvenience.</p>< ?php endif; ?>

That’s it.

If you wish to have more control over what is outputted take alook $_findHomePage variable and the query behind it.

Hope you find this useful.

Cheers.

There are 5 comments

Magento NewsletterIf you’re using Magento you probably noticed by now thatyou have integrated newsletter system with it. By default,

visitors are able to subscribe to your newsletter via MagentoNewsletter subscription form in sidebar.

Besides newsletter subscribers, all of your store’s registeredusers will also appear in your Magento’s newsletter e-maildatabase. This database also contains information on differentstore views, allowing you to easily send multiple variationsof your newsletter to different store view subscribers. Thisfeature is extremely useful when dealing with multiplelanguage web shops.

How to send a Magento Newsletter?Newsletter Template:

The process of sending out Magento Newsletter startswith creation of Newsletter Template. Once you create thistemplate, the template will remain there even after you sendyour newsletter to subscribers, allowing you to change it anduse it multiple times. You can create multiple newslettertemplates with different styling and test them to see which oneattracts the most response from subscribers.

Simply click on “Add new template” button on the right andstart creating your first newsletter template. You will see ascreen with 5 fields. All of the fields are required. You will alsonotice that the largest field (”Template content” field) alreadyhas some sort of code inside. Do not remove this code. Thiscode will generate the unsubscribe link for your newsletter.Make sure that whatever you do this code remains on thebottom.

When creating newsletter template for Magento, note thatyou can actually use HTML in it. This means that if you’renot a tech savvy person, you can simply use some WYSIWYGeditor and copy / paste the code it creates into your newslettertemplate once you’re done. In addition, if you wish to haveWYSWYG editor inside your magento, check out our article onhow to use TinyMCE with Magento.

Newsletter Queue:

If you open this tab in the newsletter top menu, you willnotice that there are no newsletters in queue. In order toqueue a newsletter you need to open “Newsletter Template”screen once again and in the action box next to your templatechoose “Queue Newsletter”. This action will bring up the “EditNewsletter” screen. Notice that you can choose which storeview subscribers are going to receive the newsletter. To selectmultiple store views, hold Ctrl key and left click on store viewsyou wish to use. (this will only be necessary if you’re usingmore then one store view).

Page 36: Inchoo s magento posts

September 8th, 2009 Published by: inchoo

Created using zinepal.com. Go online to create your own zines or read what others have already published. 36

You also need to set a Queue date start. Notices that the dateand time you set are in fact server date and time, not your dateand time. If you wish to send your newsletter immediately, youneed to set it to your current server date and time or set it intopast.

Newsletter Subscribers Export:

If you wish to use some other service for sending yournewsletter you can easily export your Magento newslettersubscribers via admin panel. Access the “NewsletterSubscribers” screen via top menu. On the top right you will seeselect box with options to export your newsletter subscribersin form of CSV or XML. Export it in a form that best fits theimport options of your other newsletter solution.

Can’t send Magento newsletter? Here are some commonproblems:

• Your server time is different then your local time andyou’ve actually queued the newsletter to be sent a fewhours in future and that’s why it’s not sent right now.

• Magento sent only small part of emails? Don’t worry, itwill send them out. Magento has integrated limit on thenumber of emails it can send at once. Eventually, all ofyour emails will be sent.

• You might need to activate your cron job as it’soften a case cron job is causing you problem. Thismeans you will need to visit this address insert-your-magento-store.com/cron.php manually with yourinternet browser.

Remove SID from Magento URLswith .htaccess | InchooMany people wonder why sometimes the SID part appears intheir Magento URLs. This is when your URL has additionalSID query usually at the end. Take a look at the image. Thecuriosity is that it does not appear always. What is the mostcommon scenario it happens? You didn’t access the site withthe same domain variant you entered as your “Base URL” inyour System> Configuration> Web interface.

When you decide to launch the site, you have to decidewhether you will market http://www.domain.com/ URL orhttp://domain.com/. This is an important decision and youshouldn’t change your mind quite often. Search enginesusually treat those two URLs as a different sites and thereforethe Page Rank potential can be split between those two URLs.So, think about whether you will use www or not and stick bythis decision.

Once you decided, go to your System> Configuration> Webinterface and enter the desired form to “Base URL” field. Whenyou access the site you will notice that there are no “SID”swhen the URL matches the value from “Base URL” field andthey appear when it does not.

Now, we want the ability that the site redirects to proper URLonce accessed. Someone can place a wrong link to some forumor blog. We don’t want those links to lead to improper URL

and we don’t want SIDs to appear to those visitors. Mostimportant: We don’t want that search engines index the URLswith SIDs.

NaviGate by MerchantPlus in MagentoSome merchants use NaviGate payment gateway fromMerchatPlus because of the lesser costs than its big brotherAuthorize.net. Interesting this about this payment gateway isits compatibility with Authorize.net. So, if you need to enable itin Magento, you will not have to find someone who will have towrite the module from scratch. You just need to use standardAuthorize.net module, but with some modifications.

So, to use Navigate, you have to enable Authorize.net module.NaviGate is compatible with Authorize.net’s AIM Integrationmethod. This means that any shopping cart or online storesoftware that can connect to Authorize.net via this method canconnect to NaviGate by following this steps:

1. In the Magento Administration panel, go toConfiguration> Payment Methods.

2. Open the Authorize.net module and update the titleas you see fit. Enter your NaviGate username andtransaction key, which you generate under “Profile &Settings” in the NaviGate interface.

3. Change the Gateway URL to: https://gateway.merchantplus.com/cgi-bin/PAWebClient.cgi

4. Enable Credit Card Verification, if you want to use theCVV code.

5. Then, go to your source code and open the file: /app/code/core/Mage/Paygate/Model and find the string“setCardCodeResponseCode” . Change the line to: ->setCardCodeResponseCode($r[38]);

Save the file and you should be good!

To assist your integration, MerchantPlus created the followingdeveloper tools (you will not need them in our case):

For more information on the connection API, seeAuthorize.net’s AIM documentation.

There are 1 comments

Magento Flash Widgets Extension – AMFPointIf you read our previous article where we made it clear we wereworking on something interesting for Magento store owners,you could see this coming.

Page 37: Inchoo s magento posts

September 8th, 2009 Published by: inchoo

Created using zinepal.com. Go online to create your own zines or read what others have already published. 37

amfPoint is a Magento Extension that enables you to serveinteractive flash widgets containing your products whereverand whenever you need them on your Magento store.

Google Analytics eCommerce data fromMagento | InchooSome of you who work with Magento for a long time mightthink that this topic is so clear that it doesn’t need to have anarticle. We get many inquiries to finalize the work somebodyalready started. One of the things we notice is that somedevelopers tend to embed the Google Analytics code directlyin the Magento theme files. Yes, it works and you will see thestandard traffic data in the Google Analytics interface, but itis not a way to go.

In most of the cases, those developers editfooter.phtml in app/design/frontend/default/[your_theme]/template/page/html folder. As I said, the Google Analytics willtrack visitors data properly, but the main issue is that theeCommerce data will not be collected. To enable eCommercedata to be visible, first step is that you let Google Analytics toknow that the profile is actually an E-Commerce site.

You will get to this interface by

1. Logging to Google Analytics

2. Select an account for this site

3. On the list of Account profiles, do not go to the reports,click on Edit instead

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 oneon this image. Let Google Analytics know this is aneCommerce website

Although Google Analytics will tell you to embed the javascriptcode on your website, you don’t have to do that. You just needto see what is the Web Property ID of the profile. One you knowit, go to the Magento administration to the interface: System>Configuration> Google API> Google Analytics. Enable it andinsert that Web Property ID. Viola.

Forums say that older versions of Magento before 1.2 do notproperly track eCommerce data. In case you have older versionof Magento and have this issue, do not install some specialplugins. Upgrade Magento instead.

There are 4 comments

Magento CMS syntax – part1Every Magento user noticed that there is special{{magentocode}} syntax available in cms pages and blocks.We traced a bit to find out which params are available andwhat exactly they do.

As strange as this may sound, processor class that gets called isMage_Core_Model_Email_Template_Filter located at app/code/core/Mage/Core/Model/Email/Template/Filter.php .

There are also some interesting directives in superclassVarien_Filter_Template, but if i’m not mistaken, none ofthem can be used.

There are six replacement codes that can be used and eachtriggers its equivalent Directive function:

skinDirective

Page 38: Inchoo s magento posts

September 8th, 2009 Published by: inchoo

Created using zinepal.com. Go online to create your own zines or read what others have already published. 38

mediaDirective

htmlescapeDirective

storeDirective

blockDirective

layoutDirective

I’ll start with easier and most commonly used and continuewith advanced ones in part two of this article.

1. skinDirective

Description: Used to retrieve path of skin folder and its files,theme fallback respectedExample: {{skin url=’images/image.jpg’ _theme=’blank’}}

Synonym: Mage::getDesign()->getSkinUrl($params['url'],$params)

Params:

url = empty or relative file path

_theme = alternative theme, fallbacks if file not exist

_package = alternative package

_area = alternative area(frontend,adminhtml)

_type, _default etc. = nothing useful, somebody please correctme if i’m wrong

2. mediaDirective

Description: Used to retrieve path of root/media folder and itsfilesExample: {{media url=’image.jpg’}}

Synonym: Mage::getBaseUrl(’media’) . $params['url']

Params:

url = empty or relative file path

3. htmlescapeDirective

Description: Used to escape special html charsExample: {{htmlescape var=’<ahref=”www.inchoo.net”>inchoo</a><b>inchoo</b><i>inchoo</i>’ allowed_tags=’b'}}

Synonym: Mage::helper(’core’)->htmlEscape($params['var'],$params['allowed_tags'])

Params:

var = string to escape

allowed_tags = comma-separated list of allowed tags

4. storeDirective

Description: Used to build magento routes and custom urls

Example: {{store url=’customer/account’ _query_a=’8′}}

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

Params:

url = magento routers url

direct_url = normal url, appended to baseurl

_query_PARAMNAME = adds query param, for example_query_a=’8′ adds a=8 to url

_fragment = adds fragment, for example #comments

_escape = escapes “,’,<,>

custom = if using magento route url param, every customparam added will be appended like /a/8/b/10

I probably missed something in this last one, but it’s very lateand i’m tired of poking through Magento

To be continued ..

There are 10 comments

Magento FLIRFacelift Image Replacement (or FLIR, pronounced fleer)is an image replacement script that dynamically generatesimage representations of text on your web page in fonts thatotherwise might not be visible to your visitors. Let’s see howit behaves in Magento.

1. Download FLIR from FLIR homepage. I was using latest 1.2stable for this article because of simplicity, but if you try you’llfind out that 2.0 beta also works great but requires little moreconfiguration.

2. Unpack FLIR content (cache,fonts,etc.) inside skin/frontend/default/default/faceliftI think it makes perfect sense to put it into skin folder.

3. Open app/design/frontend/yourpackage/yourtheme/template/page/html/head.phtml and append

<script language=”javascript” src=”<?php echo $this->getSkinUrl(’facelift/flir.js’) ?>”></script>

<script type=”text/javascript”>document.observe(”dom:loaded”, function() {

FLIR.init({ path: ‘<?php echo $this->getSkinUrl(’facelift/’) ?>’ }, new FLIRStyle({ mode: ‘wrap’ }) );

FLIR.auto();

});

</script>

If your php error reporting isn’t disabled adderror_reporting(0); somewhere on top of config-flir.php. This

Page 39: Inchoo s magento posts

September 8th, 2009 Published by: inchoo

Created using zinepal.com. Go online to create your own zines or read what others have already published. 39

is main config file from which you can define options andcustom fonts, so examine it.

Refresh your Magento store and you should see the result.

flir.js can also be alternatively included from layout files insidehead 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 availablefrom FLIR homepage, so i won’t go in details on someadvanced FLIR settings, but here are few examples:

//pass selectors as comma separated listFLIR.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’} }) );

//prototype way

$$(’div.box h4′).each( function(el) { FLIR.replace(el); } );

Cya.

Magento product image switcherI just wrote small javascript animation example for productimages and thought someone may find it useful. It’s a fast wayto replace default zoom functionality for the ones that don’tlike it.

I’m actually trying to merge something like this with defaultzoom, but i’m not finished yet. Anyway, i left all javascript andstyling in media.phtml file, so just download the file

and replace it with your own atapp/design/frontend/default/yourtheme/template/catalog/product/view/media.phtml

It was made with default Magento theme. Enjoy.

There are 9 comments

amfPoint - Make your Products Rock inMagento | InchooSomething is happening. People from small town in Croatiacalled Osijek are concerned about Branko Ajzele. They say thathe is spending too much time in front of the computer writingsome code. We tried to call him many times from the officebut got no reply. After a discussion we drew straws to decidewho will go to his place to check his condition. When I came tohis place and knocked, at first there was an absolute silence.I knocked again…

After two attempts, Branko opened the door. First thing Inoticed was a Magento circle on his forehead and a red eyes.Branko didn’t sleep for a very long time.

“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 wasobvious that computer was turned on for a long time. I glancedin the room and I could see the monitor with Magento coloredlight and some animations on it.

“What are you working on man?”

He just stared for a couple of seconds which seemed like aneternity and than he finally spoke…

… To be Continued …

Page 40: Inchoo s magento posts

September 8th, 2009 Published by: inchoo

Created using zinepal.com. Go online to create your own zines or read what others have already published. 40

There are 9 comments

Programatically create Magento blocksand inject them into layoutImagine a scenario where you wish to simply create a view filelike custom-note.phtml and show this view file on some newurl inside the Magento store. One way to do this is to create aCMS page and call that block from within CMS page. But whatif you wish to create and append this block to other areas ofMagento layout that are inaccessible from CMS page interfaceform admin? What if I want to add new div element under thebreadcrumbs and append new block under it?

magento philosophy is to create block class under the /Blockfolder of your module, to create xml layout file under thetheme /layouts folder (or to modify existing layout file) and soon. Anyway you turn it around you either need to have Blockfile or add/modify at least the entry to the layout files.

All this is OK if you are working on your own store so you havefull control over the code. However, what if you are developinga module that will be used on different Magento stores. Myprime concern when building a module is to keep the numberof necessary module files to a minimum.

In code below, you will see how easy it is to call your Core/Template block to show on any area of Magento layout.

Extracted from app/code/local/ActiveCodeline/CustomOutputs/controllers/IndexController.php file.

public function indexAction(){//Get current layout state$this->loadLayout();

$block = $this->getLayout()->createBlock('Mage_Core_Block_Template','my_block_name_here',array('template' => 'activecodeline/developer.phtml'));

$this->getLayout()->getBlock('content')->append($block);

//Release layout stream... lol... sounds fancy$this->renderLayout();}

Most IMPORTANT thing to keep in mind here is the “errorhandling”. If you assign a “invalid” block to ->append(), youwill not (most likely) see an error but “nothing happend”situation.

Anyhow… hope the attached module (extension) will save yousome headaches. I know it took me few hours of tracing andtesting to get the grip of it.

Download ActiveCodeline_CustomOutputs extension.

Cheers.

There are 5 comments

How to escape from EAV in Magento? |InchooOne of the differences between Magento eCommerce platformand lets say WordPress, when looked from developer point ofview, is “avoid raw queries” approach. For a web application,Magento is massive system. His database, although not somassive but surely breathtaking with around 220 tables forcesyou to use “eye candy” EAV model to do even simple things.

For instance, if I were to tell you that I want you to retrieve5 simple products from database that have price in the rangeof 200-600USD you would most likely spent 1-4 hours tryingto work out the query. In the end you would be lucky if youeven get the query that wont break on next Magento upgrade.Let me just remind you on some of the things you need to becareful in example above.

Your query would have to take in consideration the at leastthe following states: is my product visibility such that it canbe seen in Catalog and search result, is my product enabled ordisabled, is is out of stock, which website and store view hasit been assigned, is it assigned to only one category and thatcategory is disabled by some chance, does it have special priceassigned, does it have promotion rules assigned, does it havecontent (descriptions) for multilingual site assigned.

All of those and more are questions that one has to takeinto consideration when doing raw database queries. It makesno sense to create query that fetches product and all itsappropriate info (price, quantity, description…) if that productis disabled or assigned to category that is disabled. Forinstance, if you need “featured” product functionality andyou manually create raw query that extracts one “featured”product to lets say home page. There you create nice blockholding all the necessary info of the product with a link for letssay “Add to cart” or “View product”. Clicking one of those twolink would give you most likely 404 if the product is disableor any other condition that enables the product to be shownis disabled.

So basically, raw SQL queries in Magento are a “no no” formost of the time. Too much work and you never know whatthey will change in future upgrades. Which brings me to thisnew trend of theirs which I like to call “Escape from EAV”.

Page 41: Inchoo s magento posts

September 8th, 2009 Published by: inchoo

Created using zinepal.com. Go online to create your own zines or read what others have already published. 41

EAV, also know as Entity Attribute Value was suppose tobee (or is) the next big thing in OOP. Anyhow, Magento andhis way of EAV have two huge downfalls called LACK OFDOCUMENTATION and WHAT WILL THEY CHANGE INNEXT UPGRADE. The other day I was working on a Magentoshop that had 22 000 products. Almost all of them were simpleproducts, just about 600 were grouped. The store was initiallyinstalled on Magento 1.2 version. Site was pretty much 95%complete from both graphic and development perspective.Anyhow, Magento version 1.3.1 was released and on clientdemand we decide to to upgrade. Important thing to keepin mind is that in version 1.3 Magento introduce “change inphilosophy” concerning the EAV model.

Altough EAV sounds great (and really is great for most ofthe time), it can really slow things down with all thoseJOINS executed on database. So the Magento team decidedto do a little flat tabling. Basically we now have massive dataduplication in MySQL where data is taken from various tablesand copied int one, the flat table. Flat tables were introducedfor both Products and categories, in regards to various websiteand store views.

Basically Magento has the power to “on the fly” create tablesand do the “magical” copying of data from various tables tothe flat tables. I assume they were looking for a faster way to“assemble” Product objects in Magento which in turn shouldboost the speed of collection object i grew so found about. I canlive with duplicated data in database, I mean I am not the onewriting them down. But let me get back to real world scenario.

As I mentioned, store I have been working on had morethan 20 000 products. Due to limitations of both MySQLand PHP failed to do Rebuilt that you can find in System> Configuration > Cache management. This failure causedcorrupted data in database. This manifested with “empty”attributes (attributes not showing up in Layered navigation). Iresolved the issue by “re saving” all of the 20 000 product with

custom script I wrote. After that i noticed the data in flat tablesgot rebuild as well. This of course took several hours. MagentoEAV model seems OK on paper, but with store that hold’s largenumber of products it simply does not work, at least not in wayin which their collection objects are built. Changes introducedin 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 alldata from scattered tables to single flat table”.

Solutions like these are nightmare when it comes to upgradingthe store that already has large number of products in. Systemis 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 transferlive site and database to his dev machine, or make a copy onsome sub folder on live site. Magento’s extreme out of thebox feature rich capabilities, open source philosophy and goodmarketing have made it extremely popular but be careful, freeis such a a loose term.

I am really anxious to see the future path of EAV vs Flat modelin Magento.

There are 8 comments

Updating options of configurable productthat is already in the cart< ?phpif($this->getProduct()->isConfigurable()){$_product = Mage::getModel('catalog/product')->load($this->getProduct()->getId());Mage::getBlockSingleton('catalog/product_view_type_configurable')->unsetData();$_configurable = Mage::getBlockSingleton('catalog/product_view_type_configurable')->setData('product', $_product);$_cdata = json_decode($_configurable->getJsonConfig());$_current = array();foreach((array)$this->getOptionList() as $_option) {$_current[$_option['label']]=$_option['value'];}foreach($_cdata->attributes as $attribute) {?><strong>< ?php echo $attribute->label; ?></strong><select style="width:150px;" name="cart[<?php echo $_item->getId() ?>][option][< ?php echo $attribute->id ?>]">< ?phpforeach($attribute->options as $option) {?><option <?php echo ($_current[$attribute->label]==$option->label) ? ' selected' : '' ?> value="< ?php echo $option->id ?>">< ?php echo $option->label ?> < ?php echo $this->helper('checkout')->formatPrice($option->price+$_item->getProduct()->getPrice()) ?></option>< ?php}?></select>< ?php}} else {// THIS IS PLACE WHERE EXISTING CODE from [*] goes}?>

Now you are done with template and you can style it as youwish as soon as you do few additional steps.

< ?php

class YOUR_FIRM_MODULE_NAME_Model_Card{public function update($e)

Page 42: Inchoo s magento posts

September 8th, 2009 Published by: inchoo

Created using zinepal.com. Go online to create your own zines or read what others have already published. 42

{$_this = $e->cart;$data = $e->info;

foreach ($data as $itemId => $itemInfo) {$item = $_this->getQuote()->getItemById($itemId);

if (!$item) continue;if (!isset($itemInfo['option']) or empty($itemInfo['option'])) continue;

foreach ($item->getOptions() as $option){

if($option->getCode()=='info_buyRequest'){

$unserialized = unserialize($option->getValue());$unserialized['super_attribute'] = $itemInfo['option'];$option->setValue(serialize($itemInfo['option']));

}elseif ($option->getCode()=='attributes'){$option->setValue(serialize($itemInfo['option']));}

}$item->save();}}

}?>

P.S. Yes, I know… before clicking on update cart, we shouldhave some JavaScript price changer, but this is all I have atthis moment since I needed this on card that is autosubmitedon dropdown change.

Magento custom emailsEver wanted to “just send the email” using the built in emailfeatures in Magento? Ever hit the wall trying to do somethingwith Magento? OK, I know the answer to the other one, justhad to ask . Anyhow, sending the emails with Magentoturned out to be a process of “just” a few hours of tracingMagento code.

I cant wait for smart comments like, “few hours, huh itsso easy…”. Yea, thats the beauty of Magento… few hours ofbashing your head against the wall while you are sipping the4th cup of coffee until the solution hits you. Interesting do, justwhen you get the hang of it, Magento gets you this “have youtried this” attitude .

What am I talking about? Scenario: I want to create emailtemplate named activecodeline_custom_email1.html, I wantto pass few variables to it during runtime, I want to send emailsprogrammaticaly. I dont want to create 56 lines of xml file justto call one template.

Here is how.

.../* * Loads the html file named 'custom_email_template1.html' from * app/locale/en_US/template/email/activecodeline_custom_email1.html */$emailTemplate = Mage::getModel('core/email_template') ->loadDefault('custom_email_template1');

//Create an array of variables to assign to template$emailTemplateVariables = array();

$emailTemplateVariables['myvar1'] = 'Branko';$emailTemplateVariables['myvar2'] = 'Ajzele';$emailTemplateVariables['myvar3'] = 'ActiveCodeline';

/**

* The best part * Opens the activecodeline_custom_email1.html, throws in the variable array * and returns the 'parsed' content that you can use as body of email */$processedTemplate = $emailTemplate->getProcessedTemplate($emailTemplateVariables);

/* * Or you can send the email directly, * note getProcessedTemplate is called inside send() */$emailTemplate->send('[email protected]','John Doe', $emailTemplateVariables);...

And here we go again, nothing without xml files -In orderfor above piece of code to work, you need to add an entry toyour config.xml file like shown below.

...<global> <template> <email> <custom_email_template1 module="SampleModule1"> <label>ActiveCodeline custom email module</label> <file>activecodeline_custom_email1.html</file> <type>html</type> </custom_email_template1> </email> </template></global>...

And lets not forget the email template itself, app/locale/en_US/template/email/activecodeline_custom_email1.html.

<!--@subject ActiveCodeline custom email module @-->

<div><h1>ActiveCodeline custom email example by Branko Ajzele</h1><p>Hi there {{var myvar1}} {{var myvar2}} from {{var myvar3}}. This is just some example template to test custom email module.</p></div>

Hope this was helpful. Cheers.

There are 8 comments

Getting started with building Adminmodule in MagentoDue to the “complexity” of Magento’s xml files, developers canwaste great amount of time on “unnecessary” things.When I say “complexity” I say it with purpose. XML files arenot so complex by them selves, but due to extreme lack ofdocumentation and changes Magento pumps in every new“major” release, people are lost among things that shouldreally be sideways. Anyway, in this little article I will show youhow to create basic, startup structure for your module to get itshown under Magento Admin main top menu.

As you can see on the picture below, I am creating a menu itemwith title “ActiveCodeline_SampleModule1″.

Page 43: Inchoo s magento posts

September 8th, 2009 Published by: inchoo

Created using zinepal.com. Go online to create your own zines or read what others have already published. 43

My module is called “SampleModule1″ and it consists of justa few files. As you go over the provided config.xml file youwill see that I used “BigLettersSmallLetters” style. I do thisintentionally because this “naming convention” is anothergreat pitfall for developers when it comes to constructingxml files. I know I too still struggle with “what must be thelowercase” question.

Here is my example of config.xml file

< ?xml version="1.0"?>

<config> <modules> <activecodeline_samplemodule1> <version>0.1.0</version> </activecodeline_samplemodule1> </modules>

<global> <helpers> <samplemodule1> <class>ActiveCodeline_SampleModule1_Helper</class> </samplemodule1> </helpers></global>

<admin> <routers> <samplemodule1> <use>admin</use> <args> <module>ActiveCodeline_SampleModule1</module> <frontname>samplemodule1</frontname> </args> </samplemodule1> </routers> </admin>

<adminhtml> <menu> <menu1 translate="title" module="SampleModule1"> <title>ActiveCodeline SampleModule1</title> <sort_order>60</sort_order> <children> <menuitem1 module="SampleModule1"> <title>Menu item 1</title> <action>samplemodule1/example</action> </menuitem1> </children> </menu1> </menu> <acl> <resources> <admin> <children> <menu1 translate="title" module="SampleModule1"> <title>ActiveCodeline SampleModule1</title> <sort_order>60</sort_order> <children> <menuitem1> <title>Menu item 1</title> </menuitem1> </children> </menu1> </children> </admin> </resources> </acl> </adminhtml>

</config>

My “admin” controller is extremely simple, just anindexAction() method. However it does tell a lot. Below is acode of indexAction() method.

...public function indexAction(){ // "Fetch" display $this->loadLayout();

// "Inject" into display // THe below example will not actualy show anything since the core/template is empty $this->_addContent($this->getLayout()->createBlock('core/template'));

// echo "Hello developer...";

// "Output" display $this->renderLayout();}...

And below are all the files required for this “Admin examplemodule” to work.

Note this is only example, DO NOT USE on live site.

Cheers…

There are 2 comments

How to create Magento AMF serverextensionI have been working on a project, in my own time, that involvesFlex – Magento communication. I decided to test Adobe’sAMF format. In this article I will show you how easy is to createAMF server as an extension in Magento.

So, where to we start?

The idea is to have special Url which will act as AMF endpoint.Since Magento is built on top of Zend, this is extremely easyto do.

For your module to act as a basic AMF server you needonly 3 files. MyCompany_MyModule.xml that goes underthe /app/etc/modules/ folder. Then IndexController.php thatgoes under the /app/code/local/MyCompany/MyModule/controllers/IndexController.php. And last but not leastthe config.xml file that goes under the /app/code/local/MyCompany/MyModule/etc/ folder.

I will not go into the details and show you the fullcontent of each of those files. Important thing is to focuson IndexController.php and config.xml files. Inside yourIndexController.php file you will actualy hold the code for yourAMF server (Zend_Amf).

Here is an example of indexAction from myIndexController.php file:

...public function indexAction(){ //Create AMF server instance

Page 44: Inchoo s magento posts

September 8th, 2009 Published by: inchoo

Created using zinepal.com. Go online to create your own zines or read what others have already published. 44

$server = new Zend_Amf_Server();

//setProduction(false): return exception info $server->setProduction(false);

$server->setClass($class, $class);

//$server->setClassMap("SomeTypedObjectVO", "MyCompany_MyModule_Model_SomeTypedObjectVO"); $server->setClassMap($className, $class);

//Run the AMF server echo $server->handle();

//Just in case so that Magento does not pass anything beyond this point die;}...

The above example is the simplest form of Zend AMF server ican think of, but it should be enough to get your AMF serverresponsive to AMF requests.

And to make all of this accessible via Url, we need to addentry to congig.xml file. Below is the partial example of myconfig.xml file.

... <frontend> <routers> <mymodule> <use>standard</use> <args> <module>MyCompany_MyModule</module> <frontname>myamfserver</frontname> </args> </mymodule> </routers> </frontend>...

Above piece of code sets access to AMF server on Url likehttp://server/store/index.php/myamfserver.

Thats it.

There are 2 comments

Top 5 annoying things in MagentoIf you ask me, there are two important things that makeMagento so attractive. First, its free and open source. Untilmonth ago Magento was fully free, now they have Communityand Enterprise editions. But make no mistake, when it comesto out of the box feature list, Community edition will mostlikely beat any open source cart out there. Rich “out of the box”features are the second thing that make it so attractive.

• Large number of files in system which makes itfully impractical to do installations and backup bytransferring files over FTP

There are more to add to the list, but these are the ones thatcaught my attention for most of the time. We do every dayMagento development, and believe me its quite hard to explainyour client that sometimes it takes you 2-4 times more to

develop a feature for Magento than for some other system outthere.

Magento block cachingRecently we were working on speeding up parts of clientsite which had usual problem of slow page loading causedby complicated configurable products. To solve the problemwe were experimenting with extending core Magento cachingcapabilities.

Magento has built in predifined system of block outputcaching. Its block abstract has Zend_Cache cachingcapabilities that can be modified for your own needs. I’mshowing here an example of caching whole product view block,however this is just a specific example of how things works,problems are different and requires different approach andsolution.

I will start with some external reading and example itself.There is great article on Magento Wiki about this topic, alongwith category cache example on Magento forums.

With my Inchoo_BlockCaching.rar example module thingsshould be little easier to understand.

Magento block caching depends of three things:cache_lifetime => cache lifetime in seconds

cache_tags => cache type identifiers primarly used fordeleting right cache at the right time

cache_key => cache identyfier

You can simply inject this data into construtor of any Magentoblock

protected function _construct(){$this->addData(array('cache_lifetime' => 3600,'cache_tags' => array(Mage_Catalog_Model_Product::CACHE_TAG),'cache_key' => $this->getProduct()->getId(),));}

or if you need some conditional approach like i did in thisexample define equivalent functions

public function getCacheKey(){}public function getCacheLifetime(){}public function getCacheTags(){}

because constructor approach isn’t enough in most scenarios.

There is a general misassumption about cache_lifetime. Ifyou set it to false, Zend cache will get default value of 7200seconds!! If you want infinite never expired cache set itto 9999999999, which is Zend_Cache maximum value, orsomething else big enough.

I believe that best way to activate this is to rewrite specificblock with our own with caching enabled, like shown inexample. You should always try to avoid modifying core files,even copying modified Mage classes to local, because thingsget really messy on updates.

Page 45: Inchoo s magento posts

September 8th, 2009 Published by: inchoo

Created using zinepal.com. Go online to create your own zines or read what others have already published. 45

Generated cached files can be found in usual subfolders of /var/cache folder. Two files are generated, first metadata filewhich contains serialized cache data and second one which iscached html output itself.In my example:

mage—internal-metadatas—PRODUCT_INFO_STORE+ID_PRODUCT+ID

mage—PRODUCT_INFO_STORE+ID_PRODUCT+ID

Note that “Blocks HTML output” option needs to be enabledin Cache Management for this to work.

Many things in Magento can be cached in similar way andthere are predefined mechanism waiting for you to use them.It’s possible that we’ll see more of this implemented in futureMagento versions.

Removing Product Comparison inMagentoAs many things in Magento, removing product comparison isnot available thru the admin interface. Thus, leaving us withthe only option of getting down and dirty with theme filesediting.

This guide is pretty straightforward and is based on theMagento ver. 1.3.1.1

Before beginning of this procedure please Goto: System-> Cache Management and disablecache. You can turn it on after you’re done.

Step 1 – reports.xml

Open: app/design/frontend/deafult/Your Theme name/layout/reports.xml and delete the following lines:

<block type="reports/product_compared" before="right.permanent.callout" name="right.reports.product.compared" template="reports/product_compared.phtml" />

<block type="reports/product_viewed" before="right.permanent.callout" name="right.reports.product.viewed" template="reports/product_viewed.phtml" />

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/sidebar.phtml"/>

Save the files and refresh the page you we’re checking. Productcomparison should not be there but if you click on any of theproducts you ‘ll see that the “Add to compare” text link is stillthere.

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 thefollowing 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></li>< ?php endif; ?>

Oh, of course theif you don’t want to actually delete the codecan always use the following:

<remove name="name_of_the_ol_block"/>

That’s it. You should now be free of product comparison forever and ever

There are 3 comments

Magento duplicated content | InchooMagento has several issues with duplicated content. Of course,you don’t actually have two versions of the same contentin your database, however, in the eyes of search engines,two different URLs serving same content are counted asduplicated content and will cause you lots of problems. Themost obvious problem is that your page rank is leaking ondifferent versions of virtually the same landing page. You alsomight end up with having several versions of the same contentindexed which is bad in so many ways.

First duplicated content problem in Magento occurs whenyou are listing a product in multiple categories. Magento willcreate several URLs that actually contain the same contentsuch as:

The easiest way to avoid this problem is to simply turnof the category based URLs in Magento admin panel. Thisway you will always serve exactly the same URL no matterwhich direction user took to find your product and it will beexample.com/product_name.html.

However, you might actually want to have category basedURLs for both usability and SEO reasons. Don’t worry, thereis a solution for you here, it just involves a little more work todo. What you need to do is put a rel cannonical on the URLswith category base pointing back to the original product URL.This probably sounds like some sort of voodoo but if you reedabout rel canonical it will be piece of cake.

This issue is also easily fixed by use of rel canonical. Simplyput a rel cannonical on all of the products with SID in URL,pointing back to the product’s original URL.