Thursday, November 19, 2015

Get cms page url in magento

<?php
$pageid=1;
echo Mage::helper('cms/page')->getPageUrl($pageid); ?>

Or
In controller or .phtml file:
<?php echo $this->getUrl('whats_new');?>

or
<?php echo Mage::helper('cms/page')->getPageUrl('url_key'); ?>

Or
In CMS Page
{{store _direct="url_key"}}

Wednesday, November 4, 2015

Call Newsletter form anywhere in magento

<?php 
echo $this->getLayout()->createBlock('newsletter/subscribe')->setTemplate('newsletter/subscribe.phtml')->toHtml(); 
?>

Friday, October 16, 2015

Call one .phtml file into another .phtml file in magento

<?php
echo $this->getLayout()->createBlock('core/template')->setTemplate('mobilebanners/index.phtml')->toHtml();

?>

Ratings and Reviews count in magento

<?php
$storeId = Mage::app()->getStore()->getId();
$reviewSummaryData = Mage::getModel('review/review_summary')
->setStoreId($storeId)
->load($_product->getId());
$reviewUrl=Mage::getUrl('review/product/list', array('id'=> $_product->getId()));
?>
<div class="ratings">
<div class="rating-box">
<div class="rating" style="width:<?php echo $reviewSummaryData['rating_summary'] ?>%">
</div>
<?php //echo $reviewSummaryData['reviews_count'];?>
</div>
<span class="amount"> <?php echo $this->__('%d Review(s)', $reviewSummaryData->getReviewsCount()) ?></span>
</div>

Thursday, October 15, 2015

get Product URL by Id

$product_id = 85;
$_product = Mage::getModel('catalog/product')->load($product_id);
$product_url = $_product->getProductUrl();

Redirect to CMS page from phtml file

<?php echo $this->getUrl('privacy-policy'); ?>
privacy-policy is the url-key of your cms page

or
<?php echo Mage::helper('cms/page')->getPageUrl('url_key') ?>


Redirect to Category listing Page

<?php
$category = Mage::getModel('catalog/category')->load(3);
echo $category->getUrl();
?>

Wednesday, September 9, 2015

Magetno - Get add to cart url for any product

$_productId = '1222';
$_product = Mage::getModel('catalog/product')->load($_productId);
$_carturl = Mage::helper('checkout/cart')->getAddUrl($_product);

Log of mysql query in magento

Go to lib/Varien/Db/Adapter/Pdo/Mysql.php

And do as following:
$_debug               = true;
$_logAllQueries       = true;
$_debugFile           = 'var/debug/pdo_mysql.log';

Tuesday, September 8, 2015

Magento Delete Orders

require 'app/Mage.php';

Mage::app('admin')->setUseSessionInUrl(false);                                                                                      
$orderIds=Array = array('100000001','100000002','100000004','200000002');

for($cnt=0;$cnt<count($orderIdsArray);$cnt++)
{
    try
{
$OrderId=$orderIdsArray[$cnt];
        Mage::getModel('sales/order')->loadByIncrementId($OrderId)->delete();  
echo "Order #".$OrderId ." is removed"."<br />";
    }
catch(Exception $e)

        echo 'Error: '.$e->getMessage().'<br />';
}
}

Magento - Getting shipments of the order

$order = Mage::getModel('sales/order')->load($orderID);

foreach($order->getShipmentsCollection() as $shipment)
{
        echo "<pre>";
print_r($shipment->getData());
echo "</pre>";

}

Magento : call block function in another phtml file

$className = Mage::getConfig()->getBlockClassName('Companyname_Modulename_Block_Filename');

$blockObject = new $className();  

$blockData = $blockObject->functionName();

Magento showing wrong product count in category in admin

After importing or updrading database, you may face this problem.

To fix this, you need to run following sql query:

Kindly, take database backup before running query to prevent accident deletes.

DELETE FROM catalog_category_product where product_id NOT IN (SELECT entity_id FROM (catalog_product_entity)) 

Fix the issue of magento importing more rows than found


To fix this issue, you need to empty the table "dataflow_batch_import" in mysql magento database.

Remove 'Add New' button from Admin Grid

 Go to Namespace > Module > Block > Adminhtml > BlockFile.php


  • Add the following code in the constructor of this file.
  • It will be after the call to parent constructor.


parent::__construct(); 
$this->_removeButton('add');

Wednesday, August 5, 2015

Get all invoices of order in magento

 $orderId=10001;
$order = Mage::getModel('sales/order')->load($orderId);
if ($order->hasInvoices())
{
$invoiceArray = array();

foreach ($order->getInvoiceCollection() as $invoice)
{
//to see details of  invoice
echo "<pre>";
print_r($invoice);
echo "</pre>";
$invoiceArray[] = $invoice->getIncrementId();
}
}

Load Product by ID or SKU or Name

//Load by ID
$ID=1; //ID of the product
$_product = Mage::getModel('catalog/product')->load($ID);  

// Load by SKU  
$_product = Mage::getModel('catalog/product')->loadByAttribute('sku', 'myproduct'); 

// Load by Name
$_product = Mage::getModel('catalog/product')->loadByAttribute('name', 'my product');  

add hours, days, weeks, months to any date in magento

      $date = date("Y-m-d");

      $mydate = strtotime(date("Y-m-d", strtotime($date)) . " +3hours");

      $mydate = strtotime(date("Y-m-d", strtotime($date)) . " +1 day");

      $mydate = strtotime(date("Y-m-d", strtotime($date)) . " +1 week");

      $mydate = strtotime(date("Y-m-d", strtotime($date)) . " +30 days");

      $mydate = strtotime(date("Y-m-d", strtotime($date)) . " +1 month");

Get current datetime in magento

$current_datetime=date("Y-m-d H:i:s", Mage::getModel('core/date')->timestamp(time()));

Thursday, July 9, 2015

Magento direct SQL queries

Step 1: Initialize a resource object that will communicate with the database.

// To read from the database
$readObject = Mage::getSingleton( 'core/resource' )->getConnection( 'core_read' );

// To write to the database
$writeObject = Mage::getSingleton( 'core/resource' )->getConnection( 'core_write' );

Step 2: Set table name with it's prefix
$dbTable = Mage::getSingleton( 'core/resource' )->getTableName( 'custom_product' );

Step 3: Prepare query
$sql = "SELECT additional_description FROM " . $dbTable . " WHERE id:productId";
$filters = array(
'productId' => $productId
);

Step 4: Run your query.
$result = $readObject->query( $sql, $filters );
while ( $row = $result->fetch() ) {
echo 'Additional Description ' . $row['additional_description'] . '<br />';
}

Make admin form field read only in magento

     $fieldset->addField(
            'additional_description',
            'text',
            array(
                'label' => Mage::helper('custom_favourites')->__('Additional Description'),
                'name'  => 'additional_description',
            'required'  => false,
            'readonly' => true,
            'class' => 'required-entry',
           )
        );

Get MSRP of the product

<?php echo Mage::helper('core')->currency($_product->getMsrp(),true,false); ?>

Saturday, March 28, 2015

Magento Error: You cannot define a correlation name 'my_attribute' more than once

When you call "catalog/layer_view" module twice, this type of error is generated.

You need to search 'type="catalog/layer_view"' in your xml files and remove the block which you don't need. This will fix the error that 'You cannot define a correlation name 'my_attribute' more than once'.

Redirect to cms page after subscription of Newsletter

You can redirect to any page after subscription of newsletter.


Copy 
app\code\core\Mage\Newsletter\controllers\SubscriberController.php
to
app\code\local\Mage\Newsletter\controllers\SubscriberController.php


Open created file and search this code: $this->_redirectReferer();

and replace it to following code to redirect to your cms page.

$this->_redirectUrl(Mage::getBaseUrl().'cms-page-Identifier');


you can redirect it to base url by using following code instead of above.

$this->_redirectUrl(Mage::getBaseUrl());

Delete/Remove System Attribute

There is no option to delete or remove system attribute in magento admin.

I would suggest not to delete any system attribute. But as per client's requirement if you want to remove some attribute then you need to do following settings:

1) Go to PhpMyAdmin.
2)  Go to your database.
3) Go to eav_attribute table.
4) Search your attribute_code.
5) Edit that attribute_code's row.
6) Set 1 in 'is_user_defined' column.
7) After setting 1, you can go to magento admin. Here, you will find that the attribute which is set 1 for 'is_user_defined'  is no longer remain system attribute.so you are now able to delete it.

I will suggest you that do not delete any attribute if you don't want. Better to remove it only from desired attribute set if you don't require it.

Set session time out limit for magento frontend

You can set session time out limit from magento admin for front end by doing following settings:

Go to System->Configuration->Advanced->Admin->Security and set the session lifetime.This time is number of seconds.

Authorize.net gateway Test Account Setup

Once you have test account of authorize.net, you need to do following settings in magento admin.

Magento admin > System > Configuration >sales > Payment method > expand Authorize.net

Here, you need to enter your test account's Login Id and Transaction key.

The most important configuration is Gateway URL for test account.

For Test account Gateway URL is:

If you do not change gateway url for test account then magento will show following error and you will not able to finish transaction:
The merchant login ID or password is invalid or the account is inactive.

The server is temporarily unable to service your request due to maintenance downtime or capacity problems. Please try again later.

While development of magento application,  many times we get following error:

The server is temporarily unable to service your request due to maintenance downtime or capacity problems. Please try again later.

You need to delete  maintenance.flag file in root folder of magento to fix this problem.

When Magento is performing certain tasks, it temporarily creates maintenance.flag file which should be deleted automatically once processing  task get finished but sometimes this file don't get deleted and remain on root folder which causes above error. So, simply delete  this file to get back to development again!


Saturday, February 21, 2015

Redirect to Same Page in magento

In your controller's action means in module/controller/action,call following function:
$this->_redirectReferer();

call newsletter block in footer in magento

You can do this in local.xml

I had done following code for local.xml

<?xml version="1.0"?>
<layout version="0.1.0">
    <default>
<!-- remove the newsletter block from left navigation -->
        <remove name="left.newsletter" /> 
        <!-- call newsletter block in footer -->
        <reference name="footer">
            <block type="newsletter/subscribe" name="newsletter" as="newsletter" template="newsletter/subscribe.phtml" before="-" />
        </reference>
    </default>
</layout>

change layout of category page in magento

You can do this either in catalog.xml or in local.xml

I had done following code for local.xml

<?xml version="1.0"?>
<layout version="0.1.0">
   <catalog_category_default translate="label">
    <reference name="root">
        <action method="setTemplate"><template>page/2columns-left.phtml</template></action>
    </reference>
   </catalog_category_default>
</layout>

call static block in magento

You can call static blocks by using following ways:
1) In CMS page or block:
{{block type="cms/block" block_id="custom_block_id"}}

2) In PHP code:
<?php echo $this->getLayout()->createBlock('cms/block')->setBlockId('custom_block_id')->toHtml(); ?>

3) In XML file:
<block type="cms/block" name="custom_block_id" after="-">
      <action method="setBlockId"><block_id>custom_block_id</block_id></action>
</block>

Remove block from magento left or right column

In your layout.xml
<remove name="block.name" />

Following code will remove default sidebar blocks:

<default>

<remove name="customer_account_navigation"/><!--Customer navigation-->
<remove name="sale.reorder.sidebar"/><!--Sales reorder sidebar when customer logged in Dashboard-->

<remove name="catalog.product.related"/><!--Related products sidebar-->
<remove name="catalog.compare.sidebar"/><!--Compare product sidebar-->
<remove name="catalog.leftnav"/><!--Layered navigation-->
<remove name="catalogsearch.leftnav"/><!--Layered navigation on search result page-->

<remove name="right.permanent.callout"/><!--Right Callout Sample Data-->
<remove name="right.reports.product.viewed"/><!--Recently Viewed Products-->
<remove name="right.reports.product.compared"/><!--Compared Products-->
<remove name="right.poll"/><!--Poll-->

<remove name="left.newsletter"/><!--Sidebar Newsletter-->
<remove name="left.permanent.callout"/><!--Left Callout Sample Data-->

<remove name="wishlist_sidebar"/><!--Wishlist Sidebar-->
<remove name="paypal.partner.right.logo"/><!--Paypal logo Sample Data-->

<remove name="tags_popular"/><!--Popular Tags-->
<remove name="cart_sidebar"/><!--Cart sidebar-->

</default>

Fatal error: Class Zend\Stdlib\Parameters contains 1 abstract method... magento 2

Fatal error: Class Zend\Stdlib\Parameters contains 1 abstract method and must therefore be declared abstract or implement the remaining met...