Using Magento header / footer outside of Magento

November 19, 2011  |  3 Comments  |  by Raj (MagePsycho)  |  Latest, Magento

If you want to include the header and footer of magento outside of it, say for example for third party cms/application then you can use the following trick.

0> Using Magento Code outside of Magento

<?php
/**
 * @author		MagePsycho <info@magepsycho.com>
 * @website		http://www.magepsycho.com
 * @category	using Header / Footer outside of Magento
 */
$mageFilename = 'app/Mage.php';
require_once $mageFilename;
#Mage::setIsDeveloperMode(true);
#ini_set('display_errors', 1);
umask(0);
Mage::app();
Mage::getSingleton('core/session', array('name'=>'frontend'));

1> Getting Head Block

$block				= Mage::getSingleton('core/layout');

# HEAD BLOCK
$headBlock			= $block->createBlock('page/html_head');// this wont give you the css/js inclusion
// add js
$headBlock->addJs('prototype/prototype.js');
$headBlock->addJs('lib/ccard.js');
$headBlock->addJs('prototype/validation.js');
$headBlock->addJs('scriptaculous/builder.js');
$headBlock->addJs('scriptaculous/effects.js');
$headBlock->addJs('scriptaculous/dragdrop.js');
$headBlock->addJs('scriptaculous/controls.js');
$headBlock->addJs('scriptaculous/slider.js');
$headBlock->addJs('varien/js.js');
$headBlock->addJs('varien/form.js');
$headBlock->addJs('varien/menu.js');
$headBlock->addJs('mage/translate.js');
$headBlock->addJs('mage/cookies.js');
# add css
$headBlock->addCss('css/styles.css');
$headBlock->getCssJsHtml();
$headBlock->getIncludes();

2> Getting Header Block

# HEADER BLOCK
$headerBlock		= $block->createBlock('page/html_header')->setTemplate('page/html/header.phtml')->toHtml();

3> Getting Footer Block

# FOOTER BLOCK
$footerBlock		= $block->createBlock('page/html_footer')->setTemplate('page/html/footer.phtml')->toHtml();

Putting it all together

<?php
/**
 * @author		MagePsycho <info@magepsycho.com>
 * @website		http://www.magepsycho.com
 * @category	using Header / Footer outside of Magento
 */
$mageFilename = 'app/Mage.php';
require_once $mageFilename;
#Mage::setIsDeveloperMode(true);
#ini_set('display_errors', 1);
umask(0);
Mage::app();
Mage::getSingleton('core/session', array('name'=>'frontend'));

$block				= Mage::getSingleton('core/layout');

# HEAD BLOCK
$headBlock			= $block->createBlock('page/html_head');// this wont give you the css/js inclusion
// add js
$headBlock->addJs('prototype/prototype.js');
$headBlock->addJs('lib/ccard.js');
$headBlock->addJs('prototype/validation.js');
$headBlock->addJs('scriptaculous/builder.js');
$headBlock->addJs('scriptaculous/effects.js');
$headBlock->addJs('scriptaculous/dragdrop.js');
$headBlock->addJs('scriptaculous/controls.js');
$headBlock->addJs('scriptaculous/slider.js');
$headBlock->addJs('varien/js.js');
$headBlock->addJs('varien/form.js');
$headBlock->addJs('varien/menu.js');
$headBlock->addJs('mage/translate.js');
$headBlock->addJs('mage/cookies.js');
# add css
$headBlock->addCss('css/styles.css');
$headBlock->getCssJsHtml();
$headBlock->getIncludes();

# HEADER BLOCK
$headerBlock		= $block->createBlock('page/html_header')->setTemplate('page/html/header.phtml')->toHtml();

# FOOTER BLOCK
$footerBlock		= $block->createBlock('page/html_footer')->setTemplate('page/html/footer.phtml')->toHtml();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<?php echo $headBlock->toHtml(); ?>
</head>
<body>
<div class="wrapper">
    <div class="page">
        <?php echo $headerBlock; ?>
        <div class="main-container col1-layout">
            <div class="main">
                <div class="col-main">
					<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum sit amet est lectus. Proin rhoncus faucibus mauris sit amet dictum. Donec auctor risus sed quam facilisis feugiat auctor augue mattis. Donec vitae ligula ac ligula scelerisque venenatis. Vestibulum vehicula sem nec justo aliquam lobortis. Vivamus malesuada lorem et diam consequat suscipit. Curabitur dui ante, semper eget imperdiet eu, elementum et leo. Duis id vestibulum lorem. Phasellus pulvinar condimentum urna et egestas. Sed eu orci turpis, sed facilisis lorem. Maecenas vel bibendum tortor. In congue, neque in placerat laoreet, sem lectus sagittis lorem, in pulvinar felis nibh a lorem. Proin viverra libero eu felis feugiat et porttitor enim aliquam. Cras a varius purus.</p>
<p>
Integer accumsan ligula sed lorem vehicula vitae rhoncus dolor ullamcorper. Curabitur vestibulum diam ac diam tincidunt quis adipiscing nisi placerat. Ut convallis consequat quam id imperdiet. Morbi ac risus sem. Curabitur egestas neque hendrerit felis sollicitudin ut vehicula enim mollis. Suspendisse sed leo nec risus scelerisque porttitor sed eget urna. Fusce id erat leo.</p>
                </div>
            </div>
        </div>
        <?php echo $footerBlock; ?>
    </div>
</div>
</body>
</html>

And you can see the output as depicted below:

Using Magento Header/Footer Externally

Hope this article was helpful.
Yes? Then don’t forget to jot your valuable comments.

Happy E-Commerce!

Playing with Attribute Set in Magento

November 18, 2011  |  6 Comments  |  by Raj (MagePsycho)  |  Latest, Magento

Introduction

An attribute set is a collection of attributes which can be created/edited from Catalog -> Manage Attribute Sets in backend.

Some useful snippets regarding Attribute Set.

1> Getting Attribute Set Details

$attributeSetModel = Mage::getModel('eav/entity_attribute_set');
$attributeSetId	   = 9; // or $_product->getAttributeSetId(); if you are using product model
$attributeSetModel->load($attributeSetId);
print_r($attributeSetModel->getData());

2> Getting Attribute Set Id by Name

$entityTypeId = Mage::getModel('eav/entity')
				->setType('catalog_product')
				->getTypeId();
$attributeSetName	= 'Default';
$attributeSetId		= Mage::getModel('eav/entity_attribute_set')
					->getCollection()
					->setEntityTypeFilter($entityTypeId)
					->addFieldToFilter('attribute_set_name', $attributeSetName)
					->getFirstItem()
					->getAttributeSetId();
echo $attributeSetId;

Note that the following code doesn’t work

$attributeSetId = Mage::getModel('eav/entity_attribute_set')
->load($attributeSetName, 'attribute_set_name')
->getAttributeSetId();

Because if you refer to eav_attribute_set table then you can see there are lots of rows with same attribute set name(for example: Default)

3> Getting all Attribute Sets by Entity Type(catalog_product)

$entityTypeId = Mage::getModel('eav/entity')
				->setType('catalog_product')
				->getTypeId();
$attributeSetCollection = Mage::getModel('eav/entity_attribute_set')
				->getCollection()
				->setEntityTypeFilter($entityTypeId);
foreach($attributeSetCollection as $_attributeSet){
	print_r($_attributeSet->getData());
}

Alternatively, you can also use:

$attributeSets = Mage::getModel('catalog/product_attribute_set_api')->items();
foreach($attributeSets as $_attributeSet){
	print_r($_attributeSet);
}

4> Getting all attributes in an Attribute Set

$attributes = Mage::getModel('catalog/product_attribute_api')->items($attributeSetId);
foreach($attributes as $_attribute){
	print_r($_attribute);
}

5> Filtering Products by Attribute Set

$productCollection = Mage::getModel('catalog/product')
					->getCollection()
					->addAttributeToSelect('*')
					->addFieldToFilter('attribute_set_id', $attributeSetId);
foreach($productCollection as $_product){
	print_r($_product->getData());
}

Hope you will find these snippets useful/helpful.
Please do share if you have any useful code snippets regarding Attribute Set.

Thanks for reading!

Magento utility function: How to easily create select box for drop-down attributes?

November 13, 2011  |  12 Comments  |  by Raj (MagePsycho)  |  Latest, Magento

From now onward i will be sharing custom utility functions on regular basis which will make your programming life easier to some extent at least in case of Magento 🙂

Here i am going to share an utility function which will help you to create select box for drop-down attributes(manufacturer, color, size etc.) of a product.

Utility Function:

function getSelectBox($attributeCode, $label = '', $defaultSelect = null, $extraParams = null){
	$options			= array();
	$product			= Mage::getModel('catalog/product');
	$attribute			= $product->getResource()->getAttribute($attributeCode);
	if($attribute->usesSource()){
		$options = $attribute->getSource()->getAllOptions(false);
		array_unshift($options, array('label' => $label, 'value' => ''));
	}

	$select = Mage::app()->getLayout()->createBlock('core/html_select')
			->setName($attributeCode)
			->setId($attributeCode)
			->setTitle($label)
			->setValue($defaultSelect)
			->setExtraParams($extraParams)
			->setOptions($options);
	return $select->getHtml();
}

Now you can easily draw select box for any drop-down attribute (for example: manufacturer) by simply calling the above function as:

<?php echo getSelectBox('manufacturer', 'Select Manufacturer'); ?>

Output:

Select Box - Manufacturer

Note: You can also pass default value to be selected, extra parameter like css class, javascript event handlers etc via function arguments. Or you can customize the function easily as per your requirements.

You can define the above function in your Helper class and can call from anywhere within your application in order to create select box for any drop-down attributes of product.

Happy Coding!!

Upgrading Magento from 1.6.0.0 to 1.6.1.0 via diff file

November 10, 2011  |  4 Comments  |  by Raj (MagePsycho)  |  Latest, Linux, Magento

Uprading in Magento has never been an easy task for me. But this time I successfully upgraded the Magento(from 1.6.0.0 to 1.6.1.0) with minimum no of tries. And I’m going to share the success story 🙂

First, I tried with the following series of SSH commands but unluckily didn’t work for me:

rm -rf var/cache var/session
rm -rf downloader/pearlib/cache/* downloader/pearlib/download/*
rm -f downloader/pearlib/pear.ini
chmod 550 ./mage
./mage mage-setup .
./mage config-set preferred_state stable
./mage list-installed
./mage list-upgrades
./mage install http://connect20.magentocommerce.com/community Mage_All_Latest --force
php shell/indexer.php reindexall

I went through all the above steps successfully but when i tried to logout and re-login at the backend, version number didn’t change in the admin footer. It means there was no effect of above code at least for me.

After that I tried the following SSH commands:

rm -rf var/cache/* var/session/*
rm -rf downloader/pearlib/cache/* downloader/pearlib/download/*
rm -f downloader/pearlib/pear.ini
wget http://www.magentocommerce.com/downloads/assets/1.6.1.0/1.6.0.0-1.6.1.0.diff.gz
zcat 1.6.0.0-1.6.1.0.diff.gz > 1.6.0.0-1.6.1.0.diff
patch -p0 -f < 1.6.0.0-1.6.1.0.diff

Notes:
– Deleting pear.ini is important in case If you have copied the same magento from another location. Else updates will be installed in your source location instead of current location.
– You need to run the above commands from the root of your Magento installation.

After successfully applying the above commands, I refreshed the magento page but got the following error:

“Error in file: “…/app/code/core/Mage/Sales/sql/sales_setup/upgrade-1.6.0.3-1.6.0.4.php” – SQLSTATE[42S01]: Base table or view already exists: 1050 Table ‘sales_order_aggregated_updated’ already exists”

and this error was easily removed just by renaming the following file:

app/code/core/Mage/Sales/sql/sales_setup/upgrade-1.6.0.3-1.6.0.4.php

Besides i didn’t get any error and hence upgrading Magento task was successfull.
This is the first time i upgraded via applying the .diff file and was so happy that it worked for me 🙂

Cheers!!

Happy Upgrading!

printing xml of System > Configuration settings in Magento

November 9, 2011  |  3 Comments  |  by Raj (MagePsycho)  |  Magento

Magento uses system.xml(app/code/[codePool]/[namespace]/[module]/etc/) for defining configuration section (System > Configuration) in backend.
It searches for the file(system.xml) in each module’s /etc folder and merge all those during parsing process. Here i am going to share the code for printing the XML as a result of merging system.xml from all active Magento modules.

Code:

<?php
$mageFilename = 'app/Mage.php';
require_once $mageFilename;
Mage::setIsDeveloperMode(true);
ini_set('display_errors', 1);
umask(0);
Mage::app('admin');
header('Content-Type: text/xml');
echo $config = Mage::getConfig()
->loadModulesConfiguration('system.xml')
->getNode()
->asXML();
exit;

Place the above code in separate php file and run it from browser, you will see the xml code responsible for generating System > Configuration setting fields.

Happy XML Parsing!!