Sanjoy Roy

[MCM, MCP, SCJP] – Senior PHP Programmer

Tag Archives: Magento

Add a New system variable in Magento


SQL:

INSERT INTO `amwsales_db`.`core_config_data` (
`config_id` ,
`scope` ,
`scope_id` ,
`path` ,
`value`
)
VALUES (
NULL , 'default', '0', 'design/footer/terms_condtn_txt', 'terms and condition text here'

PHP:

$terms_condtn_txt = Mage::getStoreConfig('design/footer/terms_condtn_txt');

How to getBaseUrl in Magento


When developing in Magento and playing arround with Magento Themes there is some functions you should know.
If you want to get the source url of an image, javascript or file, call one of this functions adding your own path at the end.
Under every function there is an example of the output value:

//http://example.com/
echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB);
//http://example.com/js/
echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_JS);
//http://example.com/index.php/
echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_LINK);
//http://example.com/media/
echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA);
//http://example.com/skin/
echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_SKIN);

Deactivate Magento store using .htaccess temporarily


Here is quick snippet of code that we use all the time when upgrading or moving a Magento store. This will stop people from creating accounts, placing orders, etc… while you are in the middle of heavy database work.
Add this to your .htaccess file in your root directory and only your IP address will be able to view your website. All other visitors will get redirected to an “updating” page.
Add this to your .htaccess file (directly after RewriteEngine On):

RewriteCond %{REMOTE_HOST} !^123.45.67.89
RewriteCond %{REQUEST_URI} !/updating.html$
RewriteRule .*$ /updating.html [R=302,L]

Do not forget to create a file called updating.html and put the message that you want visitors to see while your site is down.

Magento Easy Lightbox

Magento – How to create multiple store?

Magento – Creating a Configurable Product

Magento – How to get a product attribute value?


I have created an extra attribute ‘enquiry_only’ in the back-end, this is how I can retrieve the attribute value in the product info template page:
\public_html\app\design\frontend\base\default\template\catalog\product\

$enquiry_only = Mage::getModel('catalog/product')
                            ->load($_product->getId())
                            ->getAttributeText('enquiry_only');

Alternatively we can use like:

$prod = Mage::getModel('catalog/product')->load($_product->getEntityId());
					$prod = $prod->getData(); 								
					$enquiry_only = 'No';		
					$attribute = Mage::getModel('eav/config')->getAttribute('catalog_product', 'enquiry_only');
					foreach ( $attribute->getSource()->getAllOptions(true, true) as $option){
						if ($option['value'] == $prod['enquiry_only'])
							$enquiry_only = $option['label'];
					}	

magento Couldn’t resolve host ‘magento-community’

Magento – How to Enable or Disable Developer’s “Template Path Hints” using phpmyadmin with admin access?


Template Path Hints:

SELECT *
FROM `a39085_db`.`core_config_data`
WHERE (
`config_id` LIKE ‘dev_debug_template_hints’
OR `scope` LIKE ‘dev_debug_template_hints’
OR `scope_id` LIKE ‘dev_debug_template_hints’
OR `path` LIKE ‘dev_debug_template_hints’
OR `value` LIKE ‘dev_debug_template_hints’
)
LIMIT 0 , 30
UPDATE `a39085_db`.`core_config_data` SET `value` = ‘0’ WHERE `core_config_data`.`config_id` = 467 LIMIT 1

Magento – How to order the fields in catalog advance search page.


Steps:
1. Alter the table:`eav_attribute`, use the following command:
ALTER TABLE `eav_attribute` ADD `sort_by` INT( 4 ) NOT NULL DEFAULT ‘500’
2. Edit the /public_html/app/code/core/Mage/CatalogSearch/Model/Advanced.php file:
Function Name: public function getAttributes()
Line no. #98
Change: ->setOrder(‘main_table.attribute_id’, ‘asc’) by ->setOrder(‘main_table.sort_by’, ‘asc’)
3. Done. Reload the ..index.php/catalogsearch/advanced/ page.

Magento Quick Links


Change Logo:
skin/frontend/default/default/images/
01. logo.gif
02. logo_email.gif

Main Templates:
/public_html/app/design/frontend/base/default/template/page

Side boxes:
/public_html/app/design/frontend/base/default/template/callouts

Majento Product Details Page:
/public_html/app/design/frontend/base/default/template/catalog/product/view.phtml

header:
/public_html/app/design/frontend/base/default/template/page/html/header.phtml
/public_html/app/design/frontend/default/f001/template/page/html

Search box:
/public_html/app/design/frontend/base/default/template/catalogsearch

Footer:
/public_html/app/design/frontend/base/default/template/page/html/header.phtml
in static blocks

remove footer links
/public_html/app/design/frontend/base/default/layout/catalog.xml
/public_html/app/design/frontend/base/default/layout/contacts.xml
/public_html/app/design/frontend/base/default/layout/catalogsearch.xml

Featured:
/public_html/app/design/frontend/default/default/template/inchoo

Compare Products:
/public_html/app/design/frontend/base/default/template/catalog/product/compare

Newsletter Box:
/public_html/app/design/frontend/base/default/template/newsletter

Installed Modules:
/public_html/app/design/frontend/default/default/template

Free themes:

21 Free Magento Themes for Your E-commerce Store

MODULES: /public_html/app/design/frontend/default/default/template

Slider : Simple Banners
magento-community/Banners
http://www.magentocommerce.com/magento-connect/Free+Magento+Extensions/extension/3382/banners

{{block type=”banners/banners” name=”banners” template=”banners/banners.phtml”}}

app\design\frontend\default\default\template\banners
app\design\frontend\default\default\layout\banners.xml

Side Blocks:
magento-community/AsiaConnect_FreeCMS

sidebar-right-top
sidebar-right-bottom
sidebar-left-top
sidebar-left-bottom
content-top
menu-top
menu-bottom
page-bottom

Featured:
magento-community/Inchoo_FeaturedProducts

index.php/featured-products/ (store link)

{{block type=”featuredproducts/listing” template=”inchoo/block_featured_products.phtml”}}

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

/public_html/app/design/frontend/default/f001/template/catalog/product
/public_html/app/design/frontend/base/default/template/catalog/product
/public_html/app/code/core/Mage/Catalog/Block/Product/new.php

Best Seller:
magento-community/Luxe_Bestsellers

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

Default: {{block type=”bestsellers/list” name=”home.bestsellers.list” alias=”product_homepage” template=”catalog/product/list.phtml””}}
Path: /public_html/app/design/frontend/base/default/template/catalog/product/list.phtml

Popular:
magento-community/Luxe_MostViewed”}}

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

Include static block:

{{block type=”cms/block” block_id=”home-page-promo”}}
<?php echo $this->getLayout()->createBlock(‘cms/block’)->setBlockId(‘footer_links’)->toHtml() ?>

Magento – Turning on the debug mode for filename path of templates and blocks


This is a handy options for the designer and developer of Magento. It can save you hours & hours of your time of finding where you need to make changes.

System->Current Configuration Scope->Main Website->Developer->Debug->Template Path Hints->Yes
System->Current Configuration Scope->Main Website->Developer->Debug->Add Block Names to Hints->Yes

Magento – Minimum Qty Allowed in Shopping Cart


Go to backend and make chanegs to:
Catelog->products->select a product->Inventory->Minimum Qty Allowed in Shopping Cart->set to any value

Magento Fontis ANZ eGate


Provides integration with the ANZ eGate gateway interface. Only payments and refunds are allowed; void or pre-authorisation are not currently included in the extension. For more information, including screenshots, version history and instructions on configuration and usage, please see the Fontis ANZ eGate Magento extension page. To stay up-to-date with the latest releases, follow us on Twitter and subscribe to our blog. If you’d like to link to this extension, please use our extension page rather than this Connect listing. To see the other extensions we have available, visit our Magento extension page for a complete list. The development of this extension is commercially supported by Fontis. We welcome any feedback and suggestions from the community on the ongoing development of the extension. We can also provide customisation and development services upon request.



Magento how to remove minimum quantity allowed for purchase validation error


Just comment the line below: (Lines from #499 to #505)
/public_html/app/code/core/Mage/CatalogInventory/Model/Stock/Item.php

if ($this->getMinSaleQty() && ($qty) getMinSaleQty()) {
            $result->setHasError(true)
                ->setMessage(Mage::helper('cataloginventory')->__('The minimum quantity allowed for purchase is %s.', $this->getMinSaleQty() * 1))
                ->setQuoteMessage(Mage::helper('cataloginventory')->__('Some of the products cannot be ordered in requested quantity.'))
                ->setQuoteMessageIndex('qty');
            return $result;
        }

Magento how to change default quantity add to cart?


<input name="qty" type="text" class="input-text qty” id="qty" maxlength="12" value="<?php echo $this->getMinimalQty($_product)== null?1:$this->getMinimalQty($_product) ?>"/>

put this code on \app\design\frontend\default\modern\template\catalog\product\view\type/sipmle.html
and check the there will appear the 1 on text box

Where is Magento’s advanced search link?

Magento where is database configuration file?


Find the local.xml in local \\\magento\app\etc\local.xml
<pre class="brush:xml">
<config>

<db>
<table_prefix><![CDATA[]]></table_prefix>
</db>
<default_setup>
<connection>
<host><![CDATA[localhost]]></host>
<username><![CDATA[bobjaneg_user]]></username>
<password><![CDATA[tES@A$pGtOF&]]></password>
<dbname><![CDATA[bobjaneg_cmsdb]]></dbname>
<active>1</active>
</connection>
</default_setup>

</config>
</pre>

Magento storing in session


$storage = array('a'=>'b');

// store data so we can fetch it in subtotal methods
Mage::getSingleton('core/session')->setRbanhShipping(serialize($storage));

// get data
$rbanhShipping = Mage::getSingleton('core/session')->getRbanhShipping(); 
$rbanhShipping = unserialize($rbanhShipping);

Magento how to get shipping quote per item in cart


foreach ($session->getQuote()->getAllItems() as $item) 
{
    $output .= "

"; $output .= $item->getWeight(); $output .= "
"; $output .= $item->getName() . "
"; $output .= "QTY:" . $item->getQty() . " | $" . number_format($item->getPrice(), 2); $output .= "

"; $temp_product = Mage::getModel('catalog/product') ->setCurrentStore(1) ->load($item->getProduct()->getId()); $quote2 = Mage::getModel('sales/quote'); //$quote2->setDestPostcode($session->getQuote()->getShippingAddress() ->getPostcode()); //$quote2->getShippingAddress()->setCountryId('US'); $quote2->setShippingAddress($session->getQuote() ->getShippingAddress()); $temp_product->getStockItem()->setUseConfigManageStock(false); $temp_product->getStockItem()->setManageStock(false); $quote2->addProduct($temp_product); $quote2->setPackageWeight($item->getWeight()); $quote2->getShippingAddress()->setCollectShippingRates(true); $quote2->getShippingAddress()->collectTotals(); $rates = $quote2->getShippingAddress()->getShippingRatesCollection(); //$rates = $quote2->getShippingAddress()->getAllShippingRates(); //var_export($rates); foreach ($rates as $rate) { $output .= " rbanh = ".$rate->getPrice()." " . $rate->getCode() . " END
"; } }

Magento auto add product custom options


// *Special note: make sure you check your sql table name, 
//  and change the option title from what i have below.

// rbanh special methods
private function rbanh_get_custom_option_id($product_id)
{
    $sql = "
        select 
            o.option_id 
        from 
            catalog_product_option o
        inner join
            catalog_product_option_title t on t.option_id = o.option_id
        where
            t.title = 'Shipping Description'
            and o.product_id = '".$product_id."'
        limit 1
            ";
    $data = Mage::getSingleton('core/resource') ->getConnection('core_read')->fetchAll($sql);
    if (count($data) > 0)
    {
        return current($data[0]);
    }
    return false;
}

// rbanh special methods
private function rbanh_add_custom_option($product_id)
{
    // make the option active
    //$write = Mage::getSingleton('core/resource')->getConnection('core_write');
    //$write->query("update catalog_product_entity set has_options = 1 where entity_id='$product_id'"); 
    $write = Mage::getSingleton('core/resource')->getConnection('core_write');
    $sql  = "update catalog_product_entity set has_options = 1 where entity_id=?";
    $write->query($sql, $product_id); 
    
    $product = Mage::getModel('catalog/product');
    $product->load($product_id);
    $opt = Mage::getModel('catalog/product_option');
    $opt->setProduct($product);
    $option = array(
        'is_delete' => 0,
        'is_require' => false,
        'previous_group' => 'text',
        'title' => 'Shipping Description',
        'type' => 'field',
        'price_type' => 'fixed',
        'price' => '0.0000'
    );
    $opt->addOption($option);
    $opt->saveOptions();
    
    return $this->rbanh_get_custom_option_id($product_id);
}

Magento How to add new products



require_once 'app/Mage.php';
Mage::app();
 
// instatiate Product
$product = Mage::getModel('catalog/product');
 
$product->setWebsiteIds(array(1));
$product->setSku('rand-sku-' . rand());
$product->setPrice(rand(100,2000));
$product->setAttributeSetId(4); 
$product->setCategoryIds(array(3));
$product->setType('Simple Product');
$product->setName('Product Name'.rand(1,200000));
$product->setDescription('The Product Description');
$product->setShortDescription('Brief Description');
$product->setStatus(1);	
$product->setTaxClassId('2');
$product->setWeight(0);				
$product->setCreatedAt(strtotime('now'));
 
/* ADDITIONAL OPTIONS 
 
   $product->setCost();
   $product->setInDepth();
   $product->setKeywords();
 
*/
 
$product->save();
 
// "Stock Item" still required regardless of whether inventory
// control is used, or stock item error given at checkout!
 
$stockItem = Mage::getModel('cataloginventory/stock_item');
$stockItem->loadByProduct($product->getId());
$stockItem->setData('is_in_stock', 1);
$stockItem->save();
 
header("Location: /checkout/cart/add/product/".$product->getId()."/); 

Magento observer sales order



/**
 * Register an event trigger after the order has been saved
 *
 * Is triggered by sales_order_save_after event 
 *
 */
public function hookSalesOrderSaveAfter ($observer)
{
    $order = $observer->getEvent()->getOrder(); // returns the Mage_Sales_Model_Order Object
    Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID); // Magento can only save attributes in admin mode
    $order->setVendor('LoremIpsum');
    $order->getResource()->saveAttribute($order, "vendor");
    $order->setCallToAction('ANC');
    $order->getResource()->saveAttribute($order, "call_to_action");
    $order->setKeycode('0x7474');
    $order->getResource()->saveAttribute($order, "keycode");
    return $this;
}

Magento displaying store id

Display Magento sub categories


    $currentCat = Mage::registry('current_category');

    if ( $currentCat->getParentId() == Mage::app()->getStore()->getRootCategoryId() )
    {
        // current category is a toplevel category
        $loadCategory = $currentCat;
    }
    else
    {
        // current category is a sub-(or subsub-, etc...)category of a toplevel category
        // load the parent category of the current category
        $loadCategory = Mage::getModel('catalog/category')->load($currentCat->getParentId());
    }
    $subCategories = explode(',', $loadCategory->getChildren());

    foreach ( $subCategories as $subCategoryId )
    {
        $cat = Mage::getModel('catalog/category')->load($subCategoryId);

        if($cat->getIsActive())
        {


            echo 'getURL().'">'.$cat->getName().'
'; echo $cat->getDescription(); echo 'getImage().'">'; } }

Magento cart total + items


getSummaryQty(); ?>
There are  items  in your cart
					getQuote()->getAllItems() as $item) {
    $output .= "

"; $output .= $item->getName() . "
"; $output .= "QTY:" . $item->getQty() . " | $" . number_format($item->getPrice(), 2); $output .= "
"; } print $output;?>

Magento shopping cart total

Magento – How to load static block?

Modify Magento TAX Calculation


Change the following file: magento\app\code\core\Mage\Tax\Model\Calculation.php

/**
     * Calculate rated tax abount based on price and tax rate.
     * If you are using price including tax $priceIncludeTax should be true.
     *
     * @param   float $price
     * @param   float $taxRate
     * @param   boolean $priceIncludeTax
     * @return  float
     */
    public function calcTaxAmount($price, $taxRate, $priceIncludeTax=false, $round=true)
    {
        $taxRate = 10;
		$taxRate = $taxRate/100;
		$this->insertInLog('taxRate', $taxRate);
		$this->insertInLog('price', $price);
        if ($priceIncludeTax) {
            $amount = $price*(1-1/(1+$taxRate));
        } else {
            $amount = $price*$taxRate;
        }
		$this->insertInLog('Amount', $amount);
        if ($round) {
            return $this->round($amount);
        } else {
            return $amount;
        }
    }


    /**
     * Insert in to Log Table. It helps to trace and stores in table
     *
     * @param   varchar $title
     * @param   varchar $desc
     */

	function insertInLog($title, $desc){		
		mysql_connect("localhost","root","");
		mysql_select_db("magento");
		$sql = "insert into log_tbl values('".$title."', '".$desc."', '".date("Y-m-d h:i:s")."')";
		mysql_query($sql);
	}

How to retrieve customer name/firstname in Magento


require_once 'app/Mage.php';
umask(0);
Mage::app('default');
$session = Mage::getSingleton('customer/session');
if($session->isLoggedIn()) {
   $customer = $session->getCustomer();
   echo $customer->getName();
   echo $customer->getFirstname();
}

Magento isRecurring


    /**
     * Whether there are recurring items
     *
     * @return bool
     */
    public function hasRecurringItems()
    {
        foreach ($this->getAllVisibleItems() as $item) {
            if ($item->getProduct() && $item->getProduct()->isRecurring()) {
                return true;
            }
        }
        return false;
    }

Magento Indexing Problem and solution


Stock Status Index process is working now. Please try run this process later.

I have resolved the indexing problem. Problem was with the permission and ownership  to /public_html/var/locks directory.
#chown -R owner_name:group_name directory
e.g [/home/spsimpo/public_html/var]# chown -R spsimpo:spsimpo locks
N.B MUST BE THE SAME OWNER AND GROUP OF /VAR
Also need to chmod 777 to all files under /public_html/var/locks
[/home/spsimpo/public_html/var]# chmod -R 777 locks

All the files under /public_html/var/locks has to be like below:

-rwxrwxrwx 1 spsimpo spsimpo   31 Jan 24 11:05 index_process_1.lock*
-rwxrwxrwx 1 spsimpo spsimpo   31 Jan 24 11:05 index_process_2.lock*
-rwxrwxrwx 1 spsimpo spsimpo   31 Jan 24 11:05 index_process_3.lock*
-rwxrwxrwx 1 spsimpo spsimpo   31 Jan 24 11:17 index_process_4.lock*
-rwxrwxrwx 1 spsimpo spsimpo   31 Jan 24 11:09 index_process_5.lock*
-rwxrwxrwx 1 spsimpo spsimpo   31 Jan 24 11:07 index_process_7.lock*
-rwxrwxrwx 1 spsimpo spsimpo   31 Jan 24 11:05 index_process_9.lock*

 

Magento 1.4 Localhost Admin login problem and solution


Comment code from starting line 86 to 98 in app/code/core/Mage/Core/Model/Session/Abstract/Varien.php.
e.g.

/*  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();
} */

Magento installation problem in localhost – [validate-url] – Please enter a valid URL. Protocol is required…


Replace line no. #500 to #503 in \magento-1.4.2.0\js\prototype\validation.js file by code below:

[‘validate-url’, ‘Please enter a valid URL. Protocol is required (http://, https:// or ftp://)’, function (v) {
//return Validation.get(‘IsEmpty’).test(v) || /^(http|https|ftp):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d+))?\/?/i.test(v)
return true;
}],