Magento configurable products : display images of sub product

In a previous article, I explored a technique that displays the first image of a sub product when selected in Magento's configurable product page. This time we go one step further by changing the set of thubmnails to display all images associated with the selected sub / simple product. this tutorial requires completion of the the previous one  including the magento wiki 'Change Product Image on View Page to Associated Product's Image' before you go ahead :

  1. in your media.phtml file, the big images are loaded via html. the image id is a collection of images from which only the first one is displayed initially, the other are waiting for the thumbail to be clicked. Simply add here the images collection from associated products,  each image being allocated a css ID built from product id and the increment
            <?//<associated product all images>
                if ($_product->getTypeId() == "configurable") {
            $associated_products = $_product->loadByAttribute('sku', $_product->getSku())->getTypeInstance()->getUsedProducts();
              foreach ($associated_products as $assoc)
                $assocProduct =Mage::getModel('catalog/product')->load($assoc->getId());
                 if (count($assocProduct->getMediaGalleryImages()) > 0) {
                       foreach ($assocProduct->getMediaGalleryImages() as $_image)
                         $imageId=$assoc->getId() . "_" . $i++;?>
                          <div onclick="showZoom('<?=$imageFile?>')" class="jqzoom">
                  <img style="z-index:-1;display:none" id="image<?php echo $imageId; ?>"
                  src="<?php echo $this->helper('catalog/image')->init($assocProduct, 'thumbnail2', $_image->getFile())->resize(350, 250); ?>"
                  alt="<?php echo $this->htmlEscape($assocProduct->getName()) ?>"
                    jqimg="<?php echo $_image->url; ?>"></div>
                } //</associated product all images>
  2. in the same file, below, the images thumbnails are displayed in unordered lists. What you need to do here to create one unordered list per associated product, with a display none styling  :
                <?//<associated product all images>
                if ($_product->getTypeId() == "configurable") {
            $associated_products = $_product->loadByAttribute('sku', $_product->getSku())->getTypeInstance()->getUsedProducts();
              foreach ($associated_products as $assoc)
                $assocProduct =Mage::getModel('catalog/product')->load($assoc->getId());
                 if (count($assocProduct->getMediaGalleryImages()) > 0) { ?><ul id="teckLoom<?=$assoc->getId()?>" style="z-index:-1;display:none">   <?
                       foreach ($assocProduct->getMediaGalleryImages() as $_image)
                         $imageId=$assoc->getId() . "_" . $i++;?>
                <a href="#" onclick="jSelectImage('<?=$imageId ?>'); return false;">
                <img src="<?php echo $this->helper('catalog/image')->init($assocProduct, 'thumbnail', $_image->getFile())->resize(70); ?>" alt="<?php echo $this->htmlEscape($_image->getLabel()) ?>" title="<?php echo $this->htmlEscape($_image->getLabel()) ?>" />
            </a>         </li>
                         }      ?></ul> <?
                }  }
                  //</associated product all images>   ?>
  3. use the select color  function from our previous article to display the associated image set when an option is selected via image click :
    function selectColor(idAttribute, idProduct)
    jQuery(".more-views ul").hide();
    jQuery(".more-views ul#teckLoom" + idProduct).show();
  4. add the following code to js/varien/product.js to let the effect work when an option is selected in the dropdown menu :
    var productNo = intersect(selectedAssocProducts) || selectedAssocProducts[attributeId][0];
    //$('image').attr("src", assocIMG[productNo]);
    jQuery(".more-views ul").hide();
    jQuery(".more-views ul#teckLoom" + productNo).show();
  5. Have a look at the result on ruedesiam's lovely designed multi color loom furniture : try  the chaise giulietta

wp super cache and WP3.0 menus

For those who are running small servers and wish to accelerate their worpdress installation, we recommend the installation of eaccelerator but also the wp-super-cache plugin. There is just a small hack for wordpress 3.0 menu users : the cache should be totally refreshed when a menu is modified, and this is performed via the wp_update_nav_menu action, instantiated in the wp-cache-phase2.php / wp_cache_phase2 function

add_action("wp_update_nav_menu" , 'wp_cache_clear_cache' );

Read more

Magento Configurable products : change product image on thumbnail option

This article describes a  color chooser for magento product page, a technique that automatically use product attributes from a Magento admin to display color thumbnails that

  • allows end user to choose color option by clicking on thumbnail
  • change product image to associated product image

the technique above is inspired from Magento Wiki page that describes the javascript that catches the Options price select event to modifyu the product image. We've changed a few things though

  1. Read more

WordPress single install / multiple blogs

Yes it is possible to host multiple sites for multiple customers with WordPress. The Multi User feature we expeted in wordpress 3.0 will satisfy bloggers only but we need something more specific. The technique I describe here is similar to the one described here in the sense that it directs the database configuration constants to specific databases instead of table prefixes as seen a lot. The advantage obviously is that you keep a single install of wordpress and only have one codebase to manage , while databases remain independant.

  • create wp-domains folder, and inside one folder for each domain, example wp-domains/
  • add the following code to wp-config.php : this coding allows a defualt domain to remain active even when the configuration file does not exist, at the expense of a loss in performance. But It is useful to show what's missing.

$domain = strtolower( str_replace( "www.", "", $_SERVER["SERVER_NAME"] ) );
$domain = preg_replace('[^a-z0-9\.-]', '', $domain );
$domainDirectory="/wp-domains/" .$domain;
$domainConfig= dirname(__FILE__) . $domainDirectory . "/db-config.php";
if ( file_exists( $domainConfig ) ) {require_once( $domainConfig );} else {
if ($domain!="") echo "missing " .$domainConfig;}

  • replace definitions with variables in wp-config.php

define('DB_NAME', $dbuser);
define('DB_USER', $dbuser);
define('DB_PASSWORD', $dbpwd);

Once this is working with your default  domain, setup virtual hosts  in Apache and try a new domain. Remember on a new install to setup the upload folder in wordpress admin settings.

Multi site config for WordPress : Compatible plugins

I'm running the following plugins and they work perfectly

  • WP Super Cache : works fine because the cache filename coding alogrithm includes the domain name

Prestashop : quote module (devis)


The quote feature  is  an implementation of a shopping cart within prestashop framework, without the price : we have designed this feature for specific groups, for which we deactivate the price display on the shop.

  • Deactivating price display for specific user group (below : group 2) is a long task that involves 2 different steps
    • in init.php : set the smarty variable around line 116
      $priceDisplayConfig = intval(Configuration::get('PS_PRICE_DISPLAY'));
      if($tmpCust->isMemberOfGroup(2)) $priceDisplayConfig = 3;

      And around line 155

      'priceDisplay' => $priceDisplayConfig
    • use the smarty $priceDisplay variable in the templates to hide prices and change the "cart' (panier in french) to "quote" (devis), example from homefeature.tpl
      {if $priceDisplay<3}{l s='Add to cart' mod='homefeatured'}{else} Ajouter au devis {/if}
  • Quote / Devis module and status :
    • Download and install the "devis" module [download id="7"]
    • create the mails/devis.html and mail/devis.txt and change texts according to your business
    • create the order status "devis en cours" in BackOffice >> Orders >> statuses, check the created id (12 here) and add the following line to :
      define('_PS_OS_DEVIS_EN_COURS', 12);
    • You can optionnally deactivate the order confirmation email in classes/PaymentModule.php, line 288-290, replace the send email to customer test by adding a new condition :
      	// Send an e-mail to customer
      if ($id_order_state != _PS_OS_ERROR_ AND $id_order_state != _PS_OS_CANCELED_ AND $customer->id
      AND $id_order_state != _PS_OS_DEVIS_EN_COURS)

How I installed sub labels on gmail

while gmail is certainly one of the most professionnal email readers, I still like to sort messages in folders and sub folders the way I used to do in old outlook clients. Even though google tries to promote its wonderful search capabilities, argumenting they remove the need for hierarchical labelling, I can't get it out of my mind, and I 'm not the only one. As of today, is takes a few minutes to configure your PC / chrome navigator to process sub folders.

  1. download the sub folders script from the adresse below and save it  to chrome's directory :
    Local Settings\Application Data\Google\Chrome\User Data\Default\User Scripts
  2. enable user script on your chrome application by using the --enable-user-scripts command line tag,a s sexplained here

Magento : how to learn from free templates

The power of Magento is great but it requires long days of learning and suffering to get through relative simple features, such as the now common front page slide banner. I had a quick look at magento free templates on google and was conquered by Magento 's classic theme, the kind of  stuff that's really given free of charge when I would have paid for it. It actually comes with an interesting development of Magento's block systems, and demonstrates how to add a custom block between navigation and content : the prototype glider that scrolls images is defined a cms static block, which is then called in the home page CMS  custom xml definition, with a reference to the slider block that's positionned in phtml files and declared in the xml layouts as a core/text_list type . Impressive stuff : that's pure  magento design and illustrates how versatile the system is.

Links : 25 free templates for Magento

Use Zend_Form to create SQL table

A quick code snippet that uses a Zend form (in the case below, with subforms) to generate a SQL table create statement. Useful for scaffolding : create your form with Zend Form Elements then the SQL table automatically.

Prestashop, how to transfer cart to order manually

Prestashop has a nice feature that allows administrator to view a customer's shopping cart : while the shopping cart is relatively easy to use for novices, the number of steps involved in completing the transaction can discourage some users, who might be tempted to ask you for help. What can you do apart from helpinog the guy to fill in forms ? The technique below illustrates how to simulate a payment using the Cheque payment type, via the creation of a hard coded validation page. Be careul, this is for good PHP coders only as you have to interfere with low level classes from Prestashop.

  1. go to Modules / cheque / validation.php and duplicate the file to validationManual.php
  2. Paste the  code blow under the includes  to instanciante the shopping cart using the ID of the shopping cart you want to transfer to an order, here we have the id 9304
  3. change the currency id to reflect the currency you want to use, you'll find the currency id in the currency module of the prestashop administration interface
  4. call the module/cheque/validationManual.php from the browser, s if it was called after a valid paymen
  5. Go to Prestashop administration interface to check that the order has been created
  6. you might be wise to try to place a new order for testing that the manual process has not disturbed prestashop's database integrity
    // 1 . get currency ID
    $currency = new Currency(1);
    // 2 get cart id
    $cart = new Cart( 9304);
    $total = floatval(number_format($cart->getOrderTotal(true, 3), 2, '.', ''));
    $mailVars =    array(
    '{cheque_name}' => Configuration::get('CHEQUE_NAME'),
    '{cheque_address}' => Configuration::get('CHEQUE_ADDRESS'),
    '{cheque_address_html}' => nl2br(Configuration::get('CHEQUE_ADDRESS')));
    $cm = new Cheque();
    $cm->validateOrder($cart->id, _PS_OS_CHEQUE_, $total, $cm->displayName, NULL, $mailVars, $currency->id);
    $order = new Order($cm->currentOrder);

Make site maps from HTML lists with slickmaps


It's amazing what one can do these days with jsut HTML and CSS. Slick map css builds a visually attractive sitemap that could also be used to build organigrams, straight from a single line of ul / li HTML tags. It formats ul tags up to three levels of page navigation and additional utility links – and can easily be customized to meet your own individual needs, branding, or style preferences. Designed by Matt Everson, Minnesota.

Tip : convert mac fonts to TTF

Handling mac to ttf conversino is a simple task but necessary when working with designers. CrossFont v5.4, developped by actute systesm INC in ILLINOIS (USA) does a nice job converting any mac format even when it's been transferred to a PC via zip files.

Magento one page checkout : display shopping cart details in sidebar


There are a lot of discussions going on about Magento's one page checkout procedure : it is supposed to enhance customer payment experience by probviding ajax based single page order progress. But there are alos some discussions in the forum on how to enhance this process which is quite unusual and might discourage some customers. In a previous post I reviewed the code that produces sidebar shopping cart in default pages with right margin. The solution below explains how to add a full shopping cart display for the customer's that trying to complete an order.

Read more

Magento custom attributes display on product page

The flexibility created by the attribute feature in Magento allows limitless possibilities : vairous product types can be created and each of them can go with specific attributes, meaning specific form fields for the admin, that are inserted in the product view (template/product/view.phtml) for public display. The functions availble for each user defined attributes are very simple to guess : they are dynamically created for each attribute create using , as explained in the Pratthost developer zone blog...
Read more

Magento simple ssh install

The magento wiki has a good article that details how to install Magento with the help of PEAR downloader. We don't need that, just want to install magento via ssh in a few commands, here is the detail. Before you install, make sure you check requirements, especially innoDB option for mysql.


  • go to your root folder and download magento :
  • unzip tar and delete it :
     tar xvzf magento-1.2.1.tar.gz 
    rm magento-1.2.1.tar.gz
  • copy files back to your root folder, including htaccess, then remove the magento dir
     mv magento/* .  

    mv magento/.ht* .
    rmdir magento/


  • chmod / chuser files in order to let apache do its job
    chown magento:users * -R
     for i in $( find . -type d ); do chmod 755 $i; done  

     for i in $( find . -type f ); do chmod 644 $i; done

Not that you mightr have to specify your own permissions in the last command. If you've got there, That's it, you're ready to run the installer, GOOD LUCK. Core upgrades can be done via the Magento Downloader.

MDI viewer

MDI , a high resolution, tag-based graphics format, is supported only by the Microsoft Office 2003 version of Microsoft Office Document Imaging. If you plan to share files with people who are using Office Document Imaging 2002, or another document imaging program, it's best if you save your files in TIFF format for compatibility. If by luck you happen to receive MDI files, the best option if you have been greedy enough to save on M$ Office (prefer openoffice), is to try products from Buysoft, that provides MDI tools and a free MDI reader that will print your MDI file in less than a minute.

Jquery picasa album scroller

Is it necessary to build an alternative picasa viewer when picasa itself provides nice flash gallery viewers ? for webmasters it turns out that sometimes it can be necessary to hide picasa details, and thanks to picasa itself providing various remote server access, you can use your albums within any kind of rss or json enabled application. We provide here an example of a JSON - jquery powered slideshow that takes input from any picasa album. The advantage of using picasa over hosted or specific applications such as famous menalto's gallery of coppermine is that picasa does resizing jobs for you, and offers up to 1 GB of free online image storage which largely enough for any small website presentation.

Read more

Laying text over title image in wordpress

Used by many news portals, the technique above is a great example of how to optimize layout of breaking news. We have gone the simple way with the image above, using a combination of Photoshop layers over a background image. The way it is implemented for WordPress platform by Derek Punsalan illustrates the power of wordpress custom fields, and also the limits of this input system. We would like to have image custom input fields, such as file browser or color selector. The popular custom field GUI plugin handles select, checkboxes and radio buttons but would require extensions to handle more advanced input types. There is hack on WordPress forums for that plugin  that handles Wysiwyg fields, but I would not expect it to be maintained over future versions of WordPress. The "More Fields" Plugin is a bit more flexible and is worth having a look at too.

Online Image editing : jquery’s way

My last article on Silvesrtripe CMS online image editing feature led me to investigate alternative solution for websites and software developers that wish to implement this kind of component for their backoffice.. Surfing on CAKEPHP framework homepage turned out to illustrate perfectly the kind of component that should be standard on all CMS : resizing is now pretty common, and what we want now is cropping. There is actually a plugin for jquery that does the interface job, ImgAreaSelect. ImgAreaSelect come with loads of configuration options that make it a perfect tool for cropping images : the selection area is responsive, draggable, and can be adjusted to work only within specified limits or predefined aspect ratio. What's missing in Jquery is the server side of things, and you'll find that either on webmotionUK for pure PHP or on CAKEPHP's site for Cake integration.

Create url for mod_rewrite

Creating urls with Search engine optimized keywords from database records involves more than just mod_rewrite and htaccess synchronization. The first step of a good search engine indexing strategy is to take one of your database fields as index (title is a good one) , transform it by removing spaces, special characters, and if necessary append record unique identifier to the generated string. Here is a sample function that transforms a string to make it file compliant using a regular expression to discard non alphanumeric characters and replace spaces with dashes :

function make_url($string){

$pattern = "([^[[:alnum:]|[:space:]|[:blank:]])+";
$anchor = ereg_replace($pattern, '', strtolower($string));
$pattern = "([[:space:]]|[[:blank:]])+";
$anchor = ereg_replace($pattern, '-', $anchor);
return short_name($anchor); // return the short filtered name
} # end function