How to enhance Sales order grid for magento admin?

Enhance Sales Order Grid in magento

How can we add customer group column in sales order grid?
First of all we need to override Mage_Adminhtml_Block_Sales_Order_Grid class

Create custom module name Company_Enhancegrid

Module config file in magento/etc/modules/Company_Enhancegrid.xml and add content as follow:

<?xml version="1.0"?>
<config>
<modules>
<Company_Enhancegrid>
<active>true</active>
<codePool>local</codePool>
</Company_Enhancegrid>
</modules>
</config>


Second step is to add magento/app/code/local/ “Company” folder, create config.xml file inside Company/etc folder and add content as follow:


<?xml version="1.0" encoding="utf-8"?>
<config>
<modules>
<Company_Enhancegrid>
<version>1.0.1</version>
</Company_Enhancegrid>
</modules>
<global>
<blocks>
<enhancegrid>
<class>Company_Enhancegrid_Block</class>
</enhancegrid>
<adminhtml>
<rewrite>
<sales_order_grid>Company_Enhancegrid_Block_Adminhtml_Sales_Order_Grid</sales_order_grid>
</rewrite>
</adminhtml>
</blocks>
</global>
</config>

Now you need to re-write Grid block,create Company_Enhancegrid_Block_Adminhtml_Sales_Order_Grid class inside magento/app/code/local/Company/Block/Adminhtml/Sales/Order/Grid.php for the same:

<?php
class Company_Enhancegrid_Block_Adminhtml_Sales_Order_Grid extends Mage_Adminhtml_Block_Sales_Order_Grid
{
protected function _preparePage()
{

     $this->getCollection()
->getSelect()
->join( array(‘customer’=> ‘customer_entity’), ‘customer.entity_id = main_table.customer_id’, array(‘customer.group_id’));
return parent::_preparePage();
}

     protected function _prepareColumns()
{

     $groups = Mage::getResourceModel(‘customer/group_collection’)
->addFieldToFilter(‘customer_group_id’, array(‘gt’=> 0))
->load()
->toOptionHash();
$this->addColumn(‘customer_group’,
array(
‘header’=> Mage::helper(‘sales’)->__(‘Customer Group’),
‘width’ => ’70px’,
‘index’ => ‘group_id’,
‘type’ => ‘options’,
‘options’ => $groups,
));

          $this->addColumnsOrder(‘customer_group’, ‘shipping_name’);
return parent::_prepareColumns();
}
}
?>

I hope above description will help to adding customer group column in Magento Admin >> Sales >> Order grid.

How to add one column in sales order grid in admin?

How to add Order Type field in sales order grid in admin?

1) We have to create one install sql file with below code.


<?php
/* @var $installer Mage_Sales_Model_Entity_Setup */
$installer = $this;
$installer->startSetup();
$installer->run("
ALTER TABLE `{$installer->getTable('sales/order')}` ADD `order_type` VARCHAR(255) NOT NULL;
ALTER TABLE `{$installer->getTable('sales/order_grid')}` ADD `order_type` VARCHAR(255) NOT NULL;
ALTER TABLE `{$installer->getTable('sales/quote')}` ADD `order_type` VARCHAR(255) NOT NULL;
");
$installer->endSetup();
?>

2) Override Mage_Adminhtml_Block_Sales_Order_Grid file and add below code in it.


<?php

class Mycompany_Mymodule_Block_Adminhtml_Sales_Order_Grid extends Mage_Adminhtml_Block_Sales_Order_Grid
{
protected function _prepareColumns()
{

$options = array(
'ordertypeID1' => 'order type label1',
'ordertypeID2' => 'order type label2',
'ordertypeID3' => 'order type label3',
);
$this->addColumn('order_type', array(
'header' => Mage::helper('customer')->__('Order Type'),
'width' => '100',
'index' => 'order_type',
'type' => 'options',
'options' => $options
));
$this->addColumnsOrder('order_type', 'grand_total');
return parent::_prepareColumns();
}
}
?>

3) Create one observer event to add/update order type field value

Open your module/etc/config.xml


<config>
<adminhtml>
<events>
<adminhtml_sales_order_create_process_data>
<observers>
<modulename>
<class>Mycompany_Mymodule_Model_Adminhtml_Observer</class>
<method>adminhtml_sales_order_create_process_data</method>
</modulename>
</observers>
</adminhtml_sales_order_create_process_data>
<sales_convert_quote_to_order>
<observers>
<modulename>
<type>model</type>
<class>Mycompany_Mymodule_Model_Adminhtml_Observer</class>
<method>sales_convert_quote_to_order</method>
</modulename>
</observers>
</sales_convert_quote_to_order>
</events>
</adminhtml>
</config>

4) Create one observer file of class Mycompany_Mymodule_Model_Adminhtml_Observer


<?php
class Mycompany_Mymodule_Model_Adminhtml_Observer
{
public function adminhtml_sales_order_create_process_data(Varien_Event_Observer $observer)
{
try {
$requestData = $observer->getEvent()->getRequest();

if (isset($requestData['order']['order_type'])) {
$observer->getEvent()->getOrderCreateModel()->getQuote()
->addData($requestData['order'])
->save();
}

} catch (Exception $e) {
Mage::logException($e);
}
return $this;
}


/**
*
* @param Varien_Event_Observer $observer
* @return Mycompany_Mymodule_Model_Adminhtml_Observer
*/
public function sales_convert_quote_to_order(Varien_Event_Observer $observer)
{
if ($ordertype = $observer->getEvent()->getQuote()->getOrderType()) {
try {
$observer->getEvent()->getOrder()
->setOrderType($ordertype);

} catch (Exception $e) {
Mage::logException($e);
}
}

return $this;
}
}
?>

I hope above solution works like charm.

Thanks,

Bijal Bhavsar :)

TO RESOLVE BESTSELLER RESOURCE COLLECTION ISSUE WITH FLAT CATALOG

TO RESOLVE BESTSELLER RESOURCE COLLECTION ISSUE WITH FLAT CATALOG PRODUCT

You need to override MAGENTOSITEDIRECTORY\app\code\core\Mage\Reports\Model\Resource\Product\Collection.php

public function addOrderedQty($from = ”, $to = ”)

Rewrite resource Model Mage_Reports_Model_Resource_Product_Collection
Add below function to custom rewrite model

getConnection();
        $compositeTypeIds     = Mage::getSingleton('catalog/product_type')->getCompositeTypes();
        $orderTableAliasName  = $adapter->quoteIdentifier('order');

        $orderJoinCondition   = array(
            $orderTableAliasName . '.entity_id = order_items.order_id',
            $adapter->quoteInto("{$orderTableAliasName}.state <> ?", Mage_Sales_Model_Order::STATE_CANCELED),

        );
        
 
        $productJoinCondition = array(
            $adapter->quoteInto('(e.type_id NOT IN (?))', $compositeTypeIds),
            'e.entity_id = order_items.product_id',
            $adapter->quoteInto('e.entity_type_id = ?', $this->getProductEntityTypeId())
        );

        if ($from != '' && $to != '') {
            $fieldName            = $orderTableAliasName . '.created_at';
            $orderJoinCondition[] = $this->_prepareBetweenSql($fieldName, $from, $to);
        }

        $this->getSelect()->reset()
            ->from( 
                array('order_items' => $this->getTable('sales/order_item')),
                array(
                    'ordered_qty' => 'SUM(order_items.qty_ordered)',
                    'order_items_name' => 'order_items.name'
                ))
            ->joinInner(
                array('order' => $this->getTable('sales/order')),
                implode(' AND ', $orderJoinCondition),
                array());
        if ($this->isEnabledFlat()) { /*If condition Added for flat catalog*/
        	 $this->getSelect()->joinLeft(
	                array('e' => Mage::getResourceSingleton('catalog/product_flat')->getFlatTableName()),
	               "e.entity_id = order_items.product_id"  );
        } else {
	          $this->getSelect()->joinLeft(
	                array('e' => $this->getProductEntityTableName()),
	                implode(' AND ', $productJoinCondition),
	                array(
	                    'entity_id' => 'order_items.product_id',
	                    'entity_type_id' => 'e.entity_type_id',
	                    'attribute_set_id' => 'e.attribute_set_id',
	                    'type_id' => 'e.type_id',
	                    'sku' => 'e.sku',
	                    'has_options' => 'e.has_options',
	                    'required_options' => 'e.required_options',
	                    'created_at' => 'e.created_at',
	                    'updated_at' => 'e.updated_at'
	                ));
	        }
            $this->getSelect()->where('parent_item_id IS NULL')
            ->group('order_items.product_id')
            ->having('SUM(order_items.qty_ordered) > ?', 0);
        return $this;
    }


?>


I hope above solution works like charm.

Thanks,

Bijal Bhavsar :)

How to increase size of import file in phpmyadmin?

Hello All,

 

How to increase size of import file in phpmyadmin?

You need to change some settings value in php.ini file.

C:wampbinapacheapache2.2.8binphp.ini
Find:
post_max_size = 8M
upload_max_filesize = 2M
max_execution_time = 30
max_input_time = 60
memory_limit = 8M

Change to:
post_max_size = 750M
upload_max_filesize = 750M
max_execution_time = 5000
max_input_time = 5000
memory_limit = 1000M

Then restart wamp for effect.

 

Thanks,

Bijal Bhavsar :)

How to remove php tag using javascript regular expression?

Hello Everyone,

 

After a long search i found solution to validate php tags using javascript from input values in magento.

 

I have modified magento/js/prototype/validation.js file and added new class to validate php tags:

You can review below code inside ‘Validation.addAllThese’ array  to add new class to validate php tags.


['validate-no-php-tags', 'PHP tags are not allowed', function(v) {

return  !/<?[=|?php]?[sS]*??>/.test(v) && !/<?[=|php]?[sS]*?/.test(v) && !/?[sS]*?/.test(v) ;

}],

you can use ‘validate-no-php-tags’  css class in input tag in magento.

Above validation will validate tags like ‘<?php’, ‘<?’, ‘?>’, ‘<?php ?>’, ‘<? ?>’.

I hope above solution works like  charm.

 

Thanks,

Bijal Bhavsar

Solution: SQLSTATE[42S22]: Column not found: 1054 Unknown column ‘main_table.custom_design_apply’ in ‘field list’

Hello Guys,

Today i m going to show you the ways to resolve error “SQLSTATE[42S22]: Column not found: 1054 Unknown column ‘main_table.custom_desiwegn_apply’ in ‘field list’”

How this error occurs?

The above error occurs when we enable Flat catalog category settings from admin  >> System  >> Configuration >> Catalog  >> Frontend >> “Use Flat Catalog Category” set to “Yes”

How to resolve above error?

There are two ways to resolve above error specified below:

First Solution: 

Rewrite file  ”YourProjectappcodecoreMageCatalogModelResourceCategoryFlat.php ” to do change in function getDesignUpdateData we need to comment code “  ‘main_table.custom_design_apply’,” from function.

Second Solution:

To resolve above error we will create category attribute , create one file in root and paste below code and than execute that file once:

<?php
error_reporting(E_ALL | E_STRICT);
define('MAGENTO_ROOT', getcwd());
$mageFilename = MAGENTO_ROOT . '/app/Mage.php';
require_once $mageFilename;
Mage::setIsDeveloperMode(true);
ini_set('display_errors', 1);
umask(0);
$setup = new Mage_Eav_Model_Entity_Setup('core_setup');
// below code will add text attribute
$setup->addAttribute('catalog_category','custom_design_apply',
	 array(
            'type'              => 'int',
            'label'             => 'Apply To',
            'frontend'          => '',
            'table'             => '',
            'input'             => 'select',
            'class'             => '',
            'source'            => 'core/design_source_apply',
            'global'            => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_STORE,
            'visible'           => true,
            'required'          => false,
            'user_defined'      => false,
            'default'           => '',
            'searchable'        => false,
            'filterable'        => false,
            'comparable'        => false,
            'visible_on_front'  => false,
            'unique'            => false,
            'group' => 'design',
	    'sort'  => 20
        )
);

Don’t forget to do re-index from Admin panel, System >> Index Management

I hope above solution works like  charm.

Thanks,

Bijal Bhavsar :)

Add Affiliate code in checkout success page in magento

Hello Guys,

Today i’ll show you how to add affiliate code in checkout success page.

Below is the code for Product Specific Campaign setup for magento.

Open success.phtml from PATH:  Yourproject/app/design/frontend/package/theme/template/checkout/success.phtml.

Add Below code at the end of file.

We need to display below image code at checkout success page.

<img src="http://yourdomain.directtrack.com/i_prod/yourdomainname/PRODUCT_STRING/TRANSACTION_ID/OPTIONAL_INFO">  
<?php /****** START::  Affiliate  *******/?>
<?php  if($_orderID = $this->getOrderId()) {
$url = 'https://yourdomain.directtrack.com/i_prod/yourdomainname/';
$_order =  Mage::getModel('sales/order')->loadByIncrementId($_orderID);?>
<?php  $_items = $_order->getItemsCollection(); ?>
<?php $querystring='';
foreach ($_items as $_item):  ?>
<?php $querystring .='prod:'.$_item->getSku().':qty:'.$_item->getQtyOrdered();?>
<?php endforeach; ?>
<?php $querystring.= '/'.$_orderID;?>
<?php $url = $url.$querystring;?>
<img src="<?php echo $url?>" />
<?php }?>
<?php /****** END *********/?>

Thanks,
Bijal Bhavsar :)

Why Magento custom module frontend url is forced to https.?

Hello,

Today i’ll show you how to resolve issue of custom module frontend url is forced to https. instead of http. If you have used module creator to create module. Than you will definetly find below code in config.xml


<admin>
       <routers>
         <[ModuleName]>
            <use>admin</use>
            <args>
                <module>[NameSpace_ModuleName]</module>
                <frontName>[frontName]</frontName>
            </args>
        </[ModuleName]>
    </routers>
</admin>

To resolve issue of redirection to https instead of http, you need to comment above code from module config.xml file Path: app/code/(codepool)/(NameSpace)/(ModuleName)/etc/config.xml OR you can add different “frontName” for <admin> and <frontend> routers. Eg.:


<admin>
       <routers>
         <[ModuleName]>
            <use>admin</use>
            <args>
                <module>[NameSpace_ModuleName]</module>
                <frontName>[frontName]</frontName>
            </args>
        </[ModuleName]>
    </routers>
</admin>

<frontend>
       <routers>
         <[ModuleName]>
            <use>standard</use>
            <args>
                <module>[NameSpace_ModuleName]</module>
                <frontName>[frontName1]</frontName>
            </args>
        </[ModuleName]>
    </routers>
</frontend>

As per above code admin url will be http://yourdomain.com/index.php/frontName/adminhtml_moduleName/ and  frontend url will be like: http://yourdomain.com/index.php/frontName1

I hope above content is useful to you. Thanks for visiting my blog. Feel free to ask questions, if you have doubt.

Thanks,
Bijal Bhavsar :)

Log Cleaning manually via phpmyadmin or mysql client in magento

Hello,

Magento maintains several tables for logging. These tables log things such as customer accesses and which products have been compared. Magento has a mechanism for cleaning these logs regularly, but unfortunately this feature is disabled by default and most customers do not turn it on.

The following tables are managed by Magento’s Log Cleaning function:


TRUNCATE `dataflow_batch_export`;
TRUNCATE `dataflow_batch_import`;
TRUNCATE `log_customer`;
TRUNCATE `log_quote`;
TRUNCATE `log_summary`;
TRUNCATE `log_summary_type`;
TRUNCATE `log_url`;
TRUNCATE `log_url_info`;
TRUNCATE `log_visitor`;
TRUNCATE `log_visitor_info`;
TRUNCATE `log_visitor_online`;
TRUNCATE `report_viewed_product_index`;
TRUNCATE `report_compared_product_index`;
TRUNCATE `report_event`;
TRUNCATE `index_event`;

You can use below script file and use it by scheduling cronjob. Filename will be cleanup.php


<?php
$xml = simplexml_load_file('./app/etc/local.xml', NULL, LIBXML_NOCDATA);

$db['host'] = $xml->global->resources->default_setup->connection->host;
$db['name'] = $xml->global->resources->default_setup->connection->dbname;
$db['user'] = $xml->global->resources->default_setup->connection->username;
$db['pass'] = $xml->global->resources->default_setup->connection->password;
$db['pref'] = $xml->global->resources->db->table_prefix;

if($_GET['clean'] == 'log') clean_log_tables();
if($_GET['clean'] == 'var') clean_var_directory();

function clean_log_tables() {
	global $db;

	$tables = array(
		'dataflow_batch_export',
		'dataflow_batch_import',
		'log_customer',
		'log_quote',
		'log_summary',
		'log_summary_type',
		'log_url',
		'log_url_info',
		'log_visitor',
		'log_visitor_info',
		'log_visitor_online',
		'index_event',
		'report_event',
		'report_compared_product_index',
		'report_viewed_product_index',
		'catalog_compare_item',
		'catalogindex_aggregation',
		'catalogindex_aggregation_tag',
		'catalogindex_aggregation_to_tag'
	);

	mysql_connect($db['host'], $db['user'], $db['pass']) or die(mysql_error());
	mysql_select_db($db['name']) or die(mysql_error());

	foreach($tables as $v => $k) {
		@mysql_query('TRUNCATE `'.$db['pref'].$k.'`');
	}
}

function clean_var_directory() {
	$dirs = array(
		'downloader/.cache/*',
		'downloader/pearlib/cache/*',
		'downloader/pearlib/download/*',
		'var/cache/',
		'var/locks/',
		'var/log/',
		'var/report/',
		'var/session/',
		'var/tmp/'
	);

	foreach($dirs as $v => $k) {
		exec('rm -rf '.$k);
	}
}
?>

Save the file to the root directory of Magento code.

Next, open cPanel and click on the Cron Manager link.

In the Add Cron Job section, select Once a day from the Common Settings dropdown list. In the Command field, enter the following line of code, making sure to replace the yourdomain name with your own:


curl -s -o /dev/null http://www.yourdomain.com/cleanup.php?clean=log

Once you have this set at your preferred interval, click the Add Cron Job button.

Repeat the same steps as you did before, but change the Common Settings dropdown selection to 1st and 15th, and add the following line of code to the Command field:


curl -s -o /dev/null http://www.yourdomain.com/cleanup.php?clean=var

Now click the Add Cron Job button.

I hope above content is useful to you. Thanks for reading my blog.

Thanks,
Bijal Bhavsar :)

Error: Can’t initialize indexer process – When we do reindex in magento

Hello,

Sometimes when we do re-index in magento, it shows error like “Can’t initialize indexer process”. And this error occurs while re-indexing “Product Prices”, than you can’t able to save product from admin too.

To resolve the above error you need to run below query. Probably it removes only 1 record.
This solution was taken from Magento forum. Here is the direct link:
http://www.magentocommerce.com/boards/viewthread/176845/



DELETE cpop.* FROM catalog_product_option_price AS cpop
INNER JOIN catalog_product_option AS cpo
ON cpo.option_id = cpop.option_id
WHERE
cpo.type = ‘checkbox’ OR
cpo.type = ‘radio’ OR
cpo.type = ‘drop_down’;DELETE cpotp.* FROM catalog_product_option_type_price AS cpotp
INNER JOIN catalog_product_option_type_value AS cpotv
ON cpotv.option_type_id = cpotp.option_type_id
INNER JOIN catalog_product_option AS cpo
ON cpotv.option_id = cpo.option_id
WHERE
cpo.type  ‘checkbox’ AND
cpo.type  ‘radio’ AND
cpo.type  ‘drop_down’; 


I hope above content is useful to you. Thanks for reading my blog.

Thanks,
Bijal Bhavsar