Magento: jQuery Accordian Menu

Ok here’s how to make a dynamic jQuery sliding accordian menu in Magento, as seen on http://www.waterfrontbathrooms.com/.

Waterfront bathrooms also has a dynamic tree menu system to deal with there being more than 2 levels of categories, but I’ll cover this in a future post.

  1. Upload jQuery
    Upload the latest jQuery version to js/jquery/jqueryfile.js. You can get the latest jQuery file from: http://docs.jquery.com/Downloading_jQuery

  2. Upload ddAccordian
    Upload ddAccordian menu script to js/ddaccordian.js. You can get ddaccordian.js from http://www.dynamicdrive.com/dynamicindex17/ddaccordion.js

  3. Call the javascript files from the page head
    Open app/design/frontend/yourpackage/yourtheme/template/page/html/head.phtml and put the following lines in anywhere after the default lines of code.

    <script type="text/javascript" src="/js/jquery/jqueryfile.js"></script>
    <script type="text/javascript" src="/js/ddaccordion.js"></script>
    
  4. Create the navigation template file
    Create a new phtml file in app/design/frontend/yourpackage/yourtheme/template/catalog/navigation/ You can call this whatever you like, but for the purpose of this post lets call it AccordianMenu.phtml.

    This would be app/design/frontend/yourpackage/yourtheme/template/catalog/navigation/AccordianMenu.phtml.

    In this file you want to put this code. This is what gets all the categories from the database and displays them in a way that ddAccordian can understand.

    <?php
    
    /* Get active categories */
    $_main_categories=$this->getStoreCategories();
    
    /* Get the category that you are in at the moment */
    $_default_category=$this->getCurrentCategory();
    
    ?>
    
    <div id="menu">
    
    <?php
    
    if ($_main_categories):
    
    /* Cycle through categories */
    foreach ($_main_categories as $_main_category):
    
    if($_main_category->getIsActive()):
    
    $cur_category=Mage::getModel('catalog/category')->load($_main_category->getId());
    $layer = Mage::getSingleton('catalog/layer');
    $layer->setCurrentCategory($cur_category);
    
    ?>
    
    <div class="navhead"><?php echo $this->getCurrentCategory()->getName();?></div>
    
    /* Get subcategories and loop through if there are some. */
    <?php $_categories=$this->getCurrentChildCategories()?>
    <?php if($_categories->count()):?>
    
    <div class="navcontent">
    <ul>
    
    <? foreach ($_categories as $_category):?>
    
    <? if($_category->getIsActive()):
    
    $cur_subcategory=Mage::getModel('catalog/category')->load($_category->getId());
    $layer = Mage::getSingleton('catalog/layer');
    $layer->setCurrentCategory($cur_subcategory);
    
    ?>
    <li class="subcat"><a href="<?php echo $this->getCategoryUrl($_category)?>"><?php echo $_category->getName()?></a></li>
    
    <? endif;?>
    
    <?endforeach?>
    /* End loop through sub categories */
    
    </ul>
    </div>
    
    <?endif;?> /* End if child categories */
    
    <?php
    
    endif; /* End if top category is active */
    
    endforeach; /* End cycle through top categories */
    ?>
    
    <?php endif; ?> /* End if there are categories */
    
    <?php $layer->setCurrentCategory($_default_category);  ?> /* Set the category back to whatever category the user is in */
    
    <div class="navhead"><a href="#">Information Page</a></div> /* Additional navigation links if you want something in the navigation other than categories. */
    <div class="navhead"><a href="#">Information Page</a></div>
    <div class="navhead"><a href="#">Information Page</a></div>
    
    </div>
    
  5. Configure ddAccordian settings
    Open your head file again (app/design/frontend/yourpackage/yourtheme/template/page/html/head.phtml) and add the following code underneath where you called the scripts.
    <script type="text/javascript">
    //Initialize first demo:
    ddaccordion.init({
    headerclass: "navhead", //Shared CSS class name of headers group
    contentclass: "navcontent", //Shared CSS class name of contents group
    revealtype: "click", //Reveal content when user clicks or onmouseover the header? Valid value: "click", "clickgo", or "mouseover"
    mouseoverdelay: 400, //if revealtype="mouseover", set delay in milliseconds before header expands onMouseover
    collapseprev: true, //Collapse previous content (so only one open at any time)? true/false
    defaultexpanded: [0], //index of content(s) open by default [index1, index2, etc]. [] denotes no content.
    onemustopen: false, //Specify whether at least one header should be open always (so never all headers closed)
    animatedefault: true, //Should contents open by default be animated into view?
    persiststate: true, //persist state of opened contents within browser session?
    toggleclass: ["", ""], //Two CSS classes to be applied to the header when it's collapsed and expanded, respectively ["class1", "class2"]
    togglehtml: ["none", "", ""], //Additional HTML added to the header when it's collapsed and expanded, respectively  ["position", "html1", "html2"] (see docs)
    animatespeed: "normal", //speed of animation: integer in milliseconds (ie: 200), or keywords "fast", "normal", or "slow"
    oninit:function(expandedindices){ //custom code to run when headers have initalized
    //do nothing
    },
    onopenclose:function(header, index, state, isuseractivated){ //custom code to run whenever a header is opened or closed
    //do nothing
    }
    })
    </script>
    

    You can play with these values to get the desired effect, such as opening the sub categories on mouseover rather than click.

Now hopefully with a bit of styling you should be in business. If you have any questions/problems with this, leave a comment and I’d be happy to help.

Ben
Creative Lead
MS Internet

Magento – Show cart quantity

If you’re putting a shopping cart area anywhere other than the standard cart side block, then you’ll probably want to show how many items are in the cart at any one time. Here’s how:

$cart = Mage::getModel('checkout/cart')->getQuote()->getData();

if(isset($cart['items_qty'])){

if($cart['items_qty'] != 1) {
echo "You have " . (int)$cart['items_qty'] . " items in your shopping cart";
} else {
echo "You have " . (int)$cart['items_qty'] . " item in your shopping cart";
}

} else {
echo "You have 0 items in your shopping cart"
}

Magento – Handy code snippets

Here’s a short list of magento codes to do some of the simple stuff. It’s a little empty at the moment but I’ll keep adding to it over time.

  • Check if customer is logged in
    <?php
    $_customer = Mage::getSingleton('customer/session')->isLoggedIn();
    
    if ($_customer) {
    // do stuff
    }
    ?>
    
  • Get product image
    <?php echo $this->helper('catalog/image')->init($_product, 'image'); ?>
    
  • Show image using current skin path (PHTML)
    <img src="<?php echo $this->getSkinUrl('images/logo.png');?>" alt="logo" />
    
  • Show image using current skin path (CMS)
    <img src={{skin url="images/logo.png"}}  />
    
  • Show a custom block (CMS)
    {{block type="catalog/product_featured" name="product_featured" as="product_featured" template="catalog/product/featured.phtml"}}
    
  • Show a custom block (XML)
    <block type="catalog/navigation" name="catalog.myblock" after="-" template="catalog/navigation/myblock.phtml"/>
    
  • Show CMS block (PHTML)
    <?php echo $this->getLayout()->createBlock('cms/block')->setBlockId('my_block_identifier')->toHtml() ?>
    
  • Show short version of review summary
    <?php echo $this->getReviewsSummaryHtml($_link,"short",true) ?>
    

Suggestions for any more helpful code snippets are more than welcome!

Ben
Creative Lead
MS Internet

Magento – Show image from a random product in a specific category

A website we developed recently required some boxes on the homepage that link through to a specific category each, and each box needed to show an image from a random product from within that category. If you would like to do the same, here’s how it’s done:

  1. Create a PHTML file in your template folder, such as app/design/frontend/yourpackage/yourtheme/template/catalog/navigation/box.phtml
  2. Put this code in the file:
    $images = array();
    
    $catId=37; // put your category ID in here
    $products =  Mage::getModel('catalog/product')->getCollection()
    ->addAttributeToSelect('image')
    ->addCategoryFilter(Mage::getModel('catalog/category')->load($catId));
    
    Mage::getSingleton('catalog/product_status')->addSaleableFilterToCollection($products); // Only select products that are salable
    
    $products->load();
    
    
    foreach($products as $product){
    $images[] = $product->getImageUrl();
    }
    
    
    if (sizeof($images) > 1) {
    $random_image = array_rand($images, 1);
    } else {
    $random_image = 0;
    }
    
    echo "<div class='box'><img src='" . $images[$random_image] . "'/></div>";
    

    You can find the ID for your category by logging into the admin area and going to Catalog > Manage Categories and clicking on a category. You should see the ID come up next to the category name in the editable area.

  3. All you need to do now is specify where the box is shown. Open a layout file, such as app/design/frontend/yourpackage/yourtheme/layout/catalog.xml and use this layout update:
    <reference name="left"><!-- change left to any structural block you want to target, such as right or content. -->
    <block type="catalog/navigation" name="catalog.box"  template="catalog/navigation/box.phtml"/> <!--change the template path to wherever you put the template file -->
    </reference>
    

And that’s it! You should now have a block that shows an image from a random product within a specific category. You’ll need to do some styling to get it looking right mind but I hope this helps.

Ben
Creative Lead
MS Internet

Magento – Swap product image on thumbnail click

One of the most frequent requests we get for Magento sites is to tame what the thumbnails do on the product page. Of course there are plenty of plugins for adding a lightbox of some sort, but if you simply want to swap out the image in the zoomer window for one of the thumbnails, here’s what you’ll need to do:

  • Open app/design/frontend/yourpackage/yourtheme/template/catalog/product/view/media.phtml
  • Go down to line 71 and change:
    <li>
    <a href="#" onclick="popWin('<?php echo $this->getGalleryUrl($_image) ?>', 'gallery', 'width=300,height=300,left=50,top=50,location=no,status=yes,scrollbars=yes,resizable=yes'); return false;">
    <img src="<?php echo $this->helper('catalog/image')->init($this->getProduct(), 'thumbnail', $_image->getFile())->resize(56); ?>" alt="<?php echo $this->htmlEscape($_image->getLabel()) ?>" title="<?php echo $this->htmlEscape($_image->getLabel()) ?>" />
    </a>
    </li>

    to

    <li>
    <a href="<?php echo $this->helper('catalog/image')->init($this->getProduct(), 'image', $_image->getFile()); ?>" title="<?php echo $_product->getName();?>" onclick="$('image').src = this.href; return false;">
    <img src="<?php echo $this->helper('catalog/image')->init($this->getProduct(), 'thumbnail', $_image->getFile())->resize(70, 70); ?>" alt="<?php echo $this->htmlEscape($_image->getLabel()) ?>" title="<?php echo $this->htmlEscape($_image->getLabel()) ?>"/>
    </a>
    </li>
    

And that’s it! Your product image should now swap out for whichever thumbnail you click.

Credit to Scott from http://www.magentocommerce.com/boards/viewthread/6402/#t61131

Ben
Creative Lead
MS Internet

Magento SagePay Form

Today we finally got our integration of Sage Pay Form for Magento. Sage Pay is the UK and Ireland’s most popular payment gateway and Magento is rapidly gaining popularity. We will be submitting our integration to Magento as a community app but it will be available from us until then.

UPDATE

The extension is now live in Magento Connect at http://www.magentocommerce.com/extension/3060/sagepay-formerly-protx-form as a free community extension.

To install enter the key in Magento Connect (from the page above) and the extension should install completely.

You will need a Sagepay account. You can get one HERE.

Then you need to enter the details in Magento > Admin > System > Configuration > Payment Methods > SagePay Form.

Next you must run a transaction in test mode using a SagePay test card found HERE and successfully refund this.

The , all you have to do is ask SagePay to let you “Go Live” and change the server target from “Test” to “Live”.

This is currently tested in v1.3.2.4 so we would be interested to hear whether it runs ok in other versions. There is no reason why it should not.

Happy Trading!

MS Internet Magento Easy Pre-Installer

At MS Internet we are proud to use Magento as the base of the majority of our e-commerce projects. As a software Magento is very thoroughly built and provides a plethora or functions. The following is taken from the Magento site:

Marketing Promotions and Tools

  • Flexible Coupons (pricing rules) with ability to restrict to stores, customer groups, time period, products, and categories.
  • Catalog Promotional Pricing

View Full Offering

Analytics and Reporting

  • Admin Dashboard for Report Overview
  • Abandoned Shopping Cart Report
  • Best Customers Report by Total and Number of Orders

View Full Offering

Search Engine Optimization

  • Google Site Map
  • URL Rewrites give full control of URL’s
  • Meta-information for products and categories

View Full Offering

Site Management

  • Control multiple websites and stores from one Administration Panel with ability to share as much or as little information as needed
  • Web Services API for easy integration between Magento and any third-party application
  • One-Click Upgrades
  • Google Website Optimizer Integration for A/B and Multivariate Testing

View Full Offering

Catalog Management

  • Batch Import and Export of catalog
  • Google Base Integration
  • Downloadable/Digital Products
  • Advanced Pricing Rules and support for Special Prices (see marketing tools)

View Full Offering

Catalog Browsing

  • Layered / Faceted Navigation for filtering of products in Categories
  • Layered / Faceted Navigation for filtering of products in Search Results
  • Product comparisons
  • Product Reviews

View Full Offering

Product Browsing

  • Multiple Images Per Product
  • Product Image Zoom-in Capability

View Full Offering

International Support

  • Multi-Lingual
  • Support for Multiple Currencies

View Full Offering

Checkout

  • One-Page Checkout
  • Checkout without account/Guest Checkout
  • Shipping to multiple addresses in one order

View Full Offering

Shipping

  • Shipping to multiple addresses in one order
  • Multiple shipments per order
  • Free Shipping

View Full Offering

Payment

  • Integrated with Google Checkout (Level 2)
  • Payment Extensions Available through Magento Connect
  • Configurable to authorize and charge, or authorize only and charge on creation of invoices

View Full Offering

Customer Service

  • Feature-rich Customer Accounts
  • Order Tracking from Account

View Full Offering

Customer Accounts

  • Re-orders from account
  • Downloadable Products
  • Recently ordered items

View Full Offering

Order Management

  • View, edit, create and fulfill orders from admin panel.
  • Create one or multiple invoices, shipments and credit memos per order to allow for split fulfillment

View Full Offering

The downside of Magento is that it is a huge application with almost 10,000 files. This makes the task of installing the base software quiet time consuming. If you have SSH access this can be done much more quickly than via ftp but many hosts will not allow this. So, we have created this Magento Pre-Installer to get and unpack the files and install the sample data.

DOWNLOAD

This zip file contains one PHP script. To run simply upload to your web root. If you provide database credentials you can also install the sample data. This script fetches Magento version 1.3.2.4.

“Best in Class” Interactive Media Award for www.ehsmithfacades.co.uk

Our Award Icon

Awards are always good and I have to say that an award is a really nice way to round off a successful year. We have won a “Best in Class” Interactive Media Award for the site we made for EH Smith Specialist Facades at www.ehsmithfacades.co.uk.

This award brings our tally to three for the last quarter of 2009 with two for Trident Housing Association’s website.

EH Smith Facades Website

EH Smith Facades Website

The site is aimed at architects so we planned a very visual website. The usual content management features were required to run the site. We were fortunate that EH Smith had some fantastic photos of some of the buildings that had used their products so we decided to make a feature of these and placed a large image in the background of the site. We also added a fade-down feature for the site to expose the photo fully.

The notification we recieved said:

Congratulations! We are happy to announce that your entry into the IMA competition, the EH Smith Specialist Facades website (entered October 15, 2009), under the category ‘Building/Construction’, has won the IMA Best in Class Award with an overall score of 483.

The Best in Class award is the highest honor bestowed by the Interactive Media Awards. It represents the very best in planning, execution and overall professionalism. In order to win this award level, your site had to successfully pass through our comprehensive judging process, achieving very high marks in each of our judging criteria – an achievement only a fraction of sites in the IMA competition earn each year.

I am very pleased with this award as we have worked very hard, not only on this site, this year so it shows we are obviously doing something right. Hopefully we will be able to build on this next year to have a fantastic 2010!

How to get ImageMagick to Convert pdf’s with GhostScript

Ok, this is one for the nerds. I have spent most of today trying to figure out how to get ImageMagick to convert a pdf file to an image.

First I installed ImageMagick fine:

> wget ftp://ftp.imagemagick.org/pub/ImageMagick/ImageMagick.tar.gz

> tar xvfz ImageMagick.tar.gz

> cd ImageMagick-6.5.8

> ./configure

> make

> make install

Then I installed the Imagick PECL module in cPanel.
I ran a test on the command line:

> /usr/local/bin/convert test.pdf test.jpg

And like Magick we had a jpg!

So, simple I thought, run an exec() function on the above and it will do the job. However…

Basically it didn’t work. It wouldn’t work with an Imagic script either:


<?php


try

{

$im = new Imagick();
$im->readImage( "test.pdf" );
$im->pingImage("test.pdf");
$im->readImage( $image );
$im->setImageFormat( "jpg" );
$im->writeImage( 'test.jpg' );
echo 'Image Converted';
}

catch(Exception $e)
{
echo $e->getMessage();

}

?>

Hmmm!?

So, I tried to simplify the situation and converted a jpg to a png whit the script as above and both worked perfectly. So I checked the Apache error log and found that aparently “gs” did not exist. So I installed Ghostscript (which is apparently required for converting pdf’s and ps’s with exact same procedure as for Imagemagick except with the appropriate ghostscript tar.gz file. And…

Still nothing!

So, I did a bit of trawling and it turned out that Apache did not have the path to Ghostscript in the environmental path. To cut a fairly long story short I could not get httpd.conf, php.ini or .htaccess to cooperate in adding the path so I created a symbolic link from a directory already in the Apache path (/usr/bin/) to the actual location with:

> ln /usr/local/bin/ /usr/bin/

And by some minor miracle it worked!

So, if you have Imagemagick and Ghostscript installed and images work fine but pdf’s will not convert (like about 100 people I found in google-land), find your path with:


<?php

echo getenv("PATH");

?>

Then run:

> whereis gs

To find GhostScript (gs)

and run:

> ln /usr/local/bin/ /usr/bin/

Or equivalent.

Enjoy!

Top 10 Starfish Facts!

Is a starfish a fish?

No of course it isn’t! But here are 10 true facts about starfish (or more scientifically named sea stars):

1 ) Sea stars are echinoderms, and are close relatives to the sea cucumber and sea urchins.

2 ) There are over 2000 species of Sea Star.

3 ) Sea stars do not always have the standard 5 arms; the sun star (a fairly redundant name) has up to 40 arms!!

See full size image

4 ) A sea star can regenerate one of its arms! some sea stars drop off their arms as a distraction to predators. not the best idea but it must work to some extent.

See full size image

5 ) A severed arm can grow into another sea star, as the majority of their organs are placed within the arm.

6 ) The majority of sea stars have a hard protective layer on the top of them. these is made of calcium carbonate which is a common substance found in rock. This protects them from their prey which are birds, large carnivorous fish and sea otters.

7 ) There isn’t a drop of blood within a sea star, they use a ater vascular system. they pull water in through a sieve plate. They also use this to move as they propel water to tips of their arms pushing them around.

8 ) Sea Stars digest their food on the outside of their body. This is incredible. It latches on to a clam or muscle, prises it open, slides its stomach outside its mouth and into the gap in the shell and digests what’s inside. This allows the sea star to eat a larger organism than what could fit into its mouth on its underside. Once the stomach is retracted back into its body, it transfers from the one stomach (cardiac) to another internal stomach (Pyloric) to fully digest.

See full size image

9 ) Sea stars have eyes at the end of each arm, they do not have great vision but they are used.

10 ) the largest (widest diameter) discovered starfish found was erasterias echinisoma which was measured at over a meter long. thromidia catalai is the world record breaker for the heaviest weighing over 6kg See full size image