Wednesday, January 12, 2011

Useful Codes in magento

Redirection in Magento Controllers.

Mage::app()->getResponse()->setRedirect(Mage::getUrl('customer/account/login')); 

How to run an custom query in magento?



$sql = "SELECT * FROM your_table"; 
$getData = Mage::getSingleton('core/resource') ->getConnection('core_read')->fetchAll($sql); 
 
foreach($getData as $row) { 
    echo $row['name'] . "\n"; 
} 
 
// fetch write database connection that is used in Mage_Core module 
$write = Mage::getSingleton('core/resource')->getConnection('core_write'); 
// now $write is an instance of Zend_Db_Adapter_Abstract 
$write->query("insert into yourtablename values ('val1','val2')");
 
//or you can do it like this 
$write = Mage::getSingleton('core/resource')->getConnection('core_write'); 
$sql  = "insert into yourtablename values (?, ?)"; 
$write->query($sql, array('val1','val2'));
 


Get Customer Data



$customerData = Mage::helper('customer')->getCustomer()->getData());

Tuesday, January 4, 2011

Some Code Samples In Magento

Get CMS Page ID
$pageId = Mage::getBlockSingleton('cms/page')->getPage()->getIdentifier();

How to get product attributes?
<?php echo $_product->getResource()->getAttribute('attribute name')->getFrontend()->getValue($_product) ?>

How to show breadcrumbs in magento?
<?php echo $this->getLayout()->getBlock("breadcrumbs")->toHtml(); ?>

How to show Static Blocks?
<?php /* $this->block_code2call, static block code name - the one added under CMS > Static Blocks */ $_block = Mage::getModel('cms/block') ->setStoreId(Mage::app()->getStore()->getId()) ->load($this->getLayout()->createBlock('cms/block')->setBlockId($this->block_code2call)->getBlockId()); ?>

Get current category
Mage::getModel('catalog/layer')->getCurrentCategory()->getName()

Saturday, November 6, 2010

Magento Custom Category Listing Block

<?php
$cats = Mage::getModel('catalog/category')->load(2)->getChildren();
$catIds = explode(',',$cats);
?>
<ul>
<?php foreach($catIds as $catId): ?>
<li>
<?php
$category = Mage::getModel('catalog/category')->load($catId);
echo $category->getName();
$subCats = Mage::getModel('catalog/category')->load($category->getId())->getChildren();
$subCatIds = explode(',',$subCats);
?>
<?php if(count($subCatIds) > 1):?>
<ul>
<?php foreach($subCatIds as $subCat) :?>
<li>
<?php
$subCategory = Mage::getModel('catalog/category')->load($subCat);
echo $subCategory->getName();
?>
</li>
<?php endforeach;?>
</ul>
<?php endif; ?>
</li>
<?php endforeach; ?>
</ul>


The XML Block Code:

<block type="catalog/navigation" name="catalog.category" template="catalog/navigation/category.phtml" />

Saturday, September 25, 2010

How to check current page is Homepage in magento

<?php if(Mage::getSingleton('cms/page')->getIdentifier() == 'home' && Mage::app()->getFrontController()->getRequest()->getRouteName() == 'cms') :
echo “Home Page”;
else:
echo “Not Home Page”;
endif;
?>

Sunday, August 29, 2010

Adding Products To The Home Page Of Magento

You will need to add some code to your home page in order to display all products you have specified as new. Go to CMS->Manage Pages and select the home page to edit.

Add this code to underneath your page title.

{{block type=”catalog/product_new” name=”home.catalog.product.new” alias=”product_homepage” template=”catalog/product/new.phtml”}}

Go check your homepage and your product will be displayed there.
For more please visit the below link.
How To - Display products on home page

Sunday, July 25, 2010

Code to get store's skin to create a full url

$this->getSkinUrl('images/img_name.jpg')

OR

<img scr="{{skin url=images/img_name.jpg}}” width="220" height="180"/>

Sunday, June 6, 2010

Magento Admin Login not working on Localhost.

Here is the simple fix to override this problem.
This is for Magento v1.3.2.4 :

Open this file,
app/code/core/Mage/Core/Model/Session/Abstract/Varien.php
and find the    session_set_cookie_params(line-78) and replace your code with this ;

session_set_cookie_params(
$this->getCookie()->getLifetime(),
$this->getCookie()->getPath()
//$this->getCookie()->getDomain(),
//$this->getCookie()->isSecure(),
//$this->getCookie()->getHttponly()  

also remove the comma from end of getPath().

This is for Magento v1.4.0.1 :Open up Varien.php at magentoappcodecoreMageCoreModelSessionAbstract and find the following snippet starting at line 77:

// session cookie params
$cookieParams = array(
'lifetime' => $cookie->getLifetime(),
'path' => $cookie->getPath(),
'domain' => $cookie->getConfigDomain(),
'secure' => $cookie->isSecure(),
'httponly' => $cookie->getHttponly()
);

if (!$cookieParams['httponly']) {
unset($cookieParams['httponly']);
if (!$cookieParams['secure']) {
unset($cookieParams['secure']);
if (!$cookieParams['domain']) {
unset($cookieParams['domain']);
}
}
}

if (isset($cookieParams['domain'])) {
$cookieParams['domain'] = $cookie->getDomain();
}
  Now comment out the relevant parts like so:// session cookie params
$cookieParams = array(
'lifetime' => $cookie->getLifetime(),
'path' => $cookie->getPath(),
'domain' => $cookie->getConfigDomain(),
'secure' => $cookie->isSecure(),
'httponly' => $cookie->getHttponly()
);

/* if (!$cookieParams['httponly']) {
unset($cookieParams['httponly']);
if (!$cookieParams['secure']) {
unset($cookieParams['secure']);
if (!$cookieParams['domain']) {
unset($cookieParams['domain']);
}
}
}

if (isset($cookieParams['domain'])) {
$cookieParams['domain'] = $cookie->getDomain();
}*/

  

Wednesday, December 23, 2009

How to show new products on home page?

There are many ways to show products on home page.

Go to "CMS - Manage Pages" and select "Home Page" from the list of pages.

Use this code to show products as "New Products" on your home page:

{{block type="catalog/product_new" name="home.catalog.product.new" alias="product_homepage" template="catalog/product/new.phtml"}}

(Note that you must have some new products in your catalogue for anything to show when you do this. In this context new doesn’t mean that you’ve recently added them; only products explicitly marked as new using ‘Set Product as New from Date’ and ‘Set Product as New to Date’ options in the ‘General’ product information page in the admin tool will be shown.)

Sunday, December 13, 2009

Code to get the Categories list in magento.

Below code can be used to get the categories tree in magento

require_once $_SERVER[‘DOCUMENT_ROOT’]."/app/Mage.php";
Mage::app(’1’);

function nodeToArray(Varien_Data_Tree_Node $node)
{
$result = array();
$result[’category_id’] = $node->getId();
$result[’parent_id’] = $node->getParentId();
$result[’name’] = $node->getName();
$result[’is_active’] = $node->getIsActive();
$result[’position’] = $node->getPosition();
$result[’level’] = $node->getLevel();
$result[’children’] = array();

foreach ($node->getChildren() as $child) {
$result[’children’][] = nodeToArray($child);
}

return $result;
}
function load_tree() {

$tree = Mage::getResourceSingleton(’catalog/category_tree’)
->load();
$store = 1;
$parentId = 1;
$tree = Mage::getResourceSingleton(’catalog/category_tree’)
->load();

$root = $tree->getNodeById($parentId);

if($root && $root->getId() == 1) {
$root->setName(Mage::helper(’catalog’)->__(’Root’));
}

$collection = Mage::getModel(’catalog/category’)->getCollection()
->setStoreId($store)
->addAttributeToSelect(’name’)
->addAttributeToSelect(’is_active’);

$tree->addCollectionData($collection, true);
return nodeToArray($root);

}

function print_tree($tree,$level) {
$level ++;
foreach($tree as $item) {
echo str_repeat("    ", $level).$item[’name’]."<br>";
print_tree($item[’children’],$level);
}
}

$tree = load_tree();
print_tree($tree[’children’],0);

Saturday, November 28, 2009

Use of getModel and getData methods

getModel

See the code below:
$model = Mage::getModel(‘catelog/product’);
Let me explain the things, basically we have created an instance of Mage_Catelog_Model_Product class.

This means that our $model variable is actually an instance of Mage_Catalog_Model_Product class. This matches the class name contained inside the app/code/core/Mage/Catalog/Model/Product.php file. Inside this Product.php file we can clearly see that Mage_Catalog_Model_Product class extends the Mage_Catalog_Model_Abstract class. What this means is that our $model can use all of the methods (functions) declared inside the Mage_Catalog_Model_Product class plus those declared inside the Mage_Catalog_Model_Abstract class.

To iterate and echo out the available method names like
echo ‘<ul>’;
foreach (get_class_methods(get_class($model)) as $method) {
echo ‘<li>’ . $method . ‘</li>’;
}
echo ‘</ul>’;

Now you can see lot of userful methods like getName, getPrice, getTypeId, getStatus which we can execute on our $model variable like

echo ‘Product name: ‘ . $model->getName();
echo ‘Product price: ‘ . $model->getPrice();

The above will not show anything, what you have to do is call the load function as follows before above code.

$model->load(13); 

getData

getData is just one of multiple available methods for $model. getData can be executed with or without any parameters passed to it. If you execute it without any parameters you get the array variable as a result.

echo ‘<pre>’;
print_r($model->getData());
echo ‘</pre>’;

Now if you want to get product name or price, you can use getData method as below.

echo $model->getData(’sku’);
or
$modelData = $model->getData();
echo $modelData->sku;

Now from above discussion you come to know how to use getModel and getData methods.