Sandbox Script

Sometimes you want to run some code to see what it does, dump an object out or check a class but the thing you want to run/dump/check is hidden deep in the bowels of the code somewhere, and you feel it might be easier to run a bit of PHP to check just that one thing, without having to fire up or your browser, or wait for cron to run - that's where this sandbox script comes in.

To use either of the examples below, save them into a file in the root of your magento install called sandbox.php, then either browse to the directory and run `php ...

Overriding A Controller

<config>
    <frontend>
        <routers>
            <checkout>
                <args>
                    <modules>
                        <your_module before="Mage_Checkout">Your_Module</your_module>
                    </modules>
                </args>
            </checkout>
        </routers>
    </frontend>
</config>

Formatting A Price For The Current Locale

$price = 500;
$formattedPrice = Mage::helper('core')->currency($price, true, false);

Resizing A Product Image

$helper = Mage::helper('catalog/image');
$helper->init($product, 'image');
$helper->resize(216, 161);

// the helpers __toString() method outputs the url
echo $helper;

Controller Methods

A list of controller methods

Collection Manipulation (Filtering, Limiting, etc)

A list of collection methods, similar to this

Where

OR:

You have to first specify an array of attributes in the filter, then a two dimensional array, with each second dimension have the filters for attribute n, as below:

$this->addFieldToFilter(
    array('email', 'customer_id'),
    array(
        array('eq' => $customer->getEmail()), // filters for e-mail
        array('eq' => $customer->getId()), // filters for...

Restoring console.log

To do this permanently by altering your JS files, comment out this code on line 637 of js/varien/js/js:

if (!("console" in window) || !("firebug" in console))
{
    var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
    "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];

    window.console = {};
    for (var i = 0; i < names.length; ++i)
        window.console[names[i]] = function() {}
}

Or, you could paste this into your layout somewhere (...

Product Types

Type Composite[^1] Inventory[^2] Description Example
Simple - Yes The most basic form of product Example
Grouped Yes No Several simple products displayed together, customer selection determines one or more simple products to be added to the basket, which are shown in the basket as seperate products Example
Configurable Yes No Allows choosing of options which determin...

Sending Transactional E-Mails

$email = Mage::getModel('core/email_template');

$email->sendTransactional(
    'some_email_template',                                                 // template
    array('name' => 'Your Company', 'email' => 'contact@yourcompany.com'), // sender details
    'joe@joebloggs.com',                                                   // recipient email
    'Joe Bloggs',                                                          // recipient name
    array('customerName' => 'Joe Bloggs'),                                 /...

Various Link Types

Todo - this card should detail where links can be generated from (Mage, Mage_Core_Model_Store) and which methods generate them, and differentiate between web, link, direct link, skin, js and media links

Setting And Getting Cookies

To set cookies:
Mage::getModel('core/cookie')->set('cookie_name', 'cookie_value', 0); # session cookie
Mage::getModel('core/cookie')->set('cookie_name', 'cookie_value', 60); #lasts 60 seconds

To get cookies:
Mage::getModel('core/cookie')->get('made_productalerts_stock');

In Stock Product Collection

This snippet provides a collection of in-stock products, or products which do not have stock management enabled on them

$productCollection = Mage::getResourceModel('catalog/product_collection');
Mage::getSingleton('cataloginventory/stock')->addInStockFilterToCollection($productCollection);

Magento Model Diagram

This is a high-level view of the Magento Model, Resource Model and Resource Collection Model structure

Cause FPC To Cache A Route

<config>
    <frontend>
        <cache>
            <requests>
                <frontname>
                    <controller>
                        <action>enterprise_pagecache/processor_category</action>
                    </controller>
                </frontname>
            </requests>
        </cache>
    </frontend>
</config>

Adding Breadcrumbs

Via code (usually in a controller):

$crumbs = Mage::app()->getLayout->getBlock('breadcrumbs');
$crumbs->addCrumb('home', array(
    'label' => 'Home',
    'title' => 'Go to Home Page',
    'link' => Mage::getUrl('')
));

Via Layout XML:

<reference name="breadcrumbs">
    <action method="addCrumb">
        <crumbname>Home</crumbname>
        <crumbinfo>
            <label>Home</label>
            <title>Go to Home Page</title>
            <link>/</link>
        </crumbinfo>
    </a...

Getting A Database Adapter (Read or Write)

To read:

Mage::getSingleton('core/resource')->getConnection('core_read');

To write:

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

Product Attribute Addition

This code shows all possible configuration options for an attribute that I know of, you need not include all of these when adding an attribute (although it won't hurt)

$installer = Mage::getResourceModel('catalog/setup', 'catalog_setup');

if (!$installer->getAttributeId(Mage_Catalog_Model_Product::ENTITY, 'attribute_name')) {
    $installer->addAttribute(Mage_Catalog_Model_Product::ENTITY, 'attribute_name', array(         // TABLE.COLUMN:                                       DESCRIPTION:
        'label'                    ...

Enabling MySQL Query Logging

In /lib/Varien/Db/Adapter/Pdo/Mysql.php change this property to true:

/**
 * Write SQL debug data to file
 *
 * @var bool
 */
protected $_debug               = false;

To enable logging for queries slower than a certain time, alter this property:

/**
 * Minimum query duration time to be logged
 *
 * @var float
 */
protected $_logQueryTime        = 0.05;

To log all queries, set this property to true:

/**
 * Log all queries (ignored minimum query duration time)
 *
 * @var bool...

Enabling The Profiler

In index.php uncomment this line:
#Varien_Profiler::enable();

In the admin enable the profiler output:

Set System > Configuration > Advanced > Developer > Debug > Profiler to yes

To enable the Zend_Db profiler add the following node to your app/etc/local.xml file. It can be added into your database connection configuration. The output will also be displayed if the admin setting above is set to true.

<global>
    <resources>
        <default_setup>
            <connection>
                <profiler>tr...

Boilerplate Admin Controller

/**
 * Yourcompany.com
 *
 * PHP Version 5
 *
 * @category  Namespace
 * @package   Namespace_Module
 * @author    Your Name <your.name@yourcompany.com>
 * @copyright 2012 yourcompany.com
 * @license   http://www.yourcompany.com/license.txt Your license
 * @link      N/A
 */

/**
 * A description of the controller
 *
 * @category Namespace
 * @package  Namespace_Module
 * @author   Your Name <your.name@yourcompany.com>
 * @license  http://www.yourcompany.com/lice...

Converting A Quote Attribute To An Order

<config>
    <global>
        <fieldsets>
            <sales_convert_quote>
                <some_attribute>
                    <to_order>*</to_order>
                </some_attribute>
            </sales_convert_quote>
        </fieldsets>
    </global>
</config>