Wednesday, January 25

Magento : How to redirect customer to login page if not logged in

If you are developing a module which needs to give access to its content only to logged in user then the preDispatch function will be very useful. This dispatches event before action.

Just write the following function in your module’s controller and customer log in is checked before each of your controller action.

/**
 * Checking if user is logged in or not
 * If not logged in then redirect to customer login
 */
public function preDispatch()
{
    parent::preDispatch();
 
    if (!Mage::getSingleton('customer/session')->authenticate($this)) {
        $this->setFlag('', 'no-dispatch', true);
    }
}

Ref : http://blog.chapagain.com.np/magento-redirect-customer-to-login-page-if-not-logged-in

Friday, January 20

Magento Admin Login problem

Problem:

I had a new installation of magento. But I was unable to login as an administrator. I went

to the admin login page, entered correct username and password but was redirected to the

same login page. I could not enter the dashboard page. Error message is displayed when I

enter wrong username or password. But nothing is displayed and I am redirected to the same

login page when I insert correct username and password.

Solution:

I googled and found these solutions:-

1) Use 127.0.0.1 instead of localhost in your url, i.e. using

http://127.0.0.1/magento/index.php/admin instead of
http://localhost/magento/index.php/admin . But this didn’t solve my problem.

2) Since I am using Windows XP, I was suggested to open “host” file from
C:\WINDOWS\system32\drivers\etc and have 127.0.0.1 point to something like magento.localhost

or even 127.0.0.1 point to http://www.localhost.com . But this also didn’t work either.

3) This solution finally helped me out of this problem. The solution was to modify the core

Magento code. Open

app/code/core/Mage/Core/Model/Session/Abstract/Varien.php. Comment out the

lines 80 to 83. The line number may vary according to the Magento version. But these lines

are present somewhere near line 80. You have to comment the comma (,) in line: $this-

>getCookie()->getPath()//,

// set session cookie params
session_set_cookie_params(
$this->getCookie()->getLifetime(),
$this->getCookie()->getPath()//,
//$this->getCookie()->getDomain(),
//$this->getCookie()->isSecure(),
//$this->getCookie()->getHttponly()
);

Well, I am out of this problem. Hope, this solution you also help you.

Update (For Magento 1.4.*)

In Magento 1.4, you have to comment code from line 86 to 98 in

app/code/core/Mage/Core/Model/Session/Abstract/Varien.php. Like this:-

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

Ref : http://blog.chapagain.com.np/magento-admin-login-problem/

Enable Cookies problem in Magento

Problem:

When I try to add products to shopping cart, I get redirected to enable-cookies CMS page. Similarly, when I try to login as customer from customer account login, I get redirected to the same (enable-cookies) page.

The enable-cookies page asks me to enable cookies in my browser. The message says “Please enable cookies in your web browser to continue“. The page describes about Cookies and shows step-by-step instruction to enable cookies in browsers like Internet Explorer, Mozilla Firefox, and Opera. :)

When I check my browser options, I see that Cookies are enabled in my browser.

Solution:

I googled the web and found two solutions. Here are they:-

1) Increase Cookie Lifetime

– Go to System –> Configuration –> General –> Web –> Session Cookie Management –> Cookie Lifetime = 5400
– By default, Cookie Lifetime = 3600. You can make it more than 5400 and try if it works.

2) Disable redirect to enable-cookies CMS page

– Go to System –> Configuration –> General –> Web –> Browser Capabilities Detection –> Redirect to CMS-page if cookies are disabled = No

The second one has helped me. After implementing the second solution, I was able to add products to shopping cart page and was also able to login as customer.

Ref : http://blog.chapagain.com.np/magento-enable-cookies-problem

Friday, January 13

How to get list of all special offer products in Magento

Here is the complete details to get display the list of all specila offer products in Magento

There’s a few different attributes that we need to filter to get the proper results.

1. The products visibility must NOT be set to 1. This means that the product is going to be visible individually. If we tried to link to a product that was not visible individually we might get a 404 or even worse, the mage error screen! See this post for a list of visibility options ->addAttributeToFilter(‘visibility’, array(‘neq’=>1))
2. In my case I don’t want to show products that have an empty special price field. ->addAttributeToFilter(‘special_price’, array(‘neq’=>”))
4. I want to set the number of products returned to 8. ->setPageSize(8)
5. Finally I set up my date filters.

<?php
$todayDate  = Mage::app()->getLocale()->date()->toString(Varien_Date::DATETIME_INTERNAL_FORMAT);
$special= Mage::getResourceModel('reports/product_collection')
    ->addAttributeToSelect('*')
    ->addAttributeToFilter('visibility', array('neq'=>1))
    ->addAttributeToFilter('special_price', array('neq'=>''))
    ->setPageSize(8) // Only return 4 products
    ->addAttributeToFilter('special_from_date', array('date' => true, 'to' => $todayDate))
    ->addAttributeToFilter('special_to_date', array('or'=> array(
           0 => array('date' => true, 'from' => $todayDate),
           1 => array('is' => new Zend_Db_Expr('null')))
           ), 'left')
    ->addAttributeToSort('special_from_date', 'desc');
$special->load();
?>
 
<ul class="list clearfix clear" id="special">
    <?php $x = 1; ?>
    <?php foreach ($special as $product): ?>
        <li class="span-1 left a-center <?php if ($x ==8) : echo 'last'; endif; ?>">
            <a href="<?php echo $product->getProductUrl() ?>" title="<?php echo $product->getName() ?>"><img class="a-center" src="<?php echo $this->helper('catalog/image')->init($product, 'small_image')->resize(120); ?>"/></a>
            <a href="<?php echo $product->getProductUrl() ?>" title="<?php echo $product->getName() ?>"><h2><?php echo $product->getName(); ?></h2></a>
            <strong><?php echo $this->getPriceHtml($product, true); ?></strong>
        </li>
<?php $x++;
    endforeach; ?>
</ul>

Hope it Helps.... Thanks....

Fatal Error : call to a member function addMessages() on a non-object app/code/core/mage/cms/helper/page.php on line no 125

Here is the step by step to resolve the problem in Magento

Go to System->Tools ->Compilation
Disable the compilation mode

if the above method will not resolve your problem follow the another method

open the includes/config.php in magento root folder. and comment the following lines

#define('COMPILER_INCLUDE_PATH', dirname(__FILE__).DIRECTORY_SEPARATOR.'src');
#define('COMPILER_COLLECT_PATH', dirname(__FILE__).DIRECTORY_SEPARATOR.'stat');

now your problem solved...

for more details contact nmohanswe@gmail.com


hope it helps..... Thanks...

Wednesday, January 4

How to Create custom Reports in Magento Admin

I was looking to generate the Report for the Products sold along with the name of the Artist to whom the product belongs to.

These are the steps to be followed.

1. The title of the report is: ‘Artist Sold Works’. To add the new item under the Reports -> Products.

Open the ‘app/code/core/Mage/Reports/etc/config.xml’

Add the followind code in the ‘children of ‘products’ (near line 221).
<title>Artist Sold Works</title>
adminhtml/report_product/artistsold

Add the followind code in the line (near line 370).
<title>Artists Sold Works</title>

2. Copy files

app/code/core/Mage/Adminhtml/Block/Report/Product/Sold.php to app/code/core/Mage/Adminhtml/Block/Report/Product/Artistsold.php.

3. Copy directories

app/code/core/Mage/Adminhtml/Block/Report/Product/Sold to

app/code/core/Mage/Adminhtml/Block/Report/Product/Artistsold

app/code/core/Mage/Reports/Model/Mysql4/Product/Sold to

app/code/core/Mage/Reports/Model/Mysql4/Product/Artistsold

4. In the file Artistsold.php, change the class name from

Mage_Adminhtml_Block_Report_Product_Sold to Mage_Adminhtml_Block_Report_Product_Artistsold.

Change the lines
$this->_controller = 'report_product_sold';
$this->_headerText = Mage::helper('reports')->__('Products Ordered');
to
$this->_controller = 'report_product_artistsold';
$this->_headerText = Mage::helper('reports')->__('Artist Sold Works');

5. Add/Modify the columns in the

app/code/core/Mage/Adminhtml/Block/Report/Product/Artistsold/Grid.php

Here in my case:
$this->addColumn('artistId', array(
    'header'    =>Mage::helper('reports')->__('Artist'),
    'width'     =>'120px',
    'index'     =>'artistname',
));  

$this->addColumn('sale_percentage', array(
    'header'    =>Mage::helper('reports')->__('Artist Share'),
    'width'     =>'60px',
    'index'     =>'sale_percentage',
    'align'     =>'right'
));

$this->addColumn('base_price_total', array(
    'header'    =>Mage::helper('reports')->__('Total Product Base Price ($)'),
    'width'     =>'60px',
    'index'     =>'base_price_total',
    'align'     =>'right',
    'total'     =>'sum',
    'type'      =>'number'

));

$this->addColumn('artist_earned', array(
    'header'    =>Mage::helper('reports')->__('Artist Earned ($)'),
    'width'     =>'60px',
    'index'     =>'artist_earned',
    'align'     =>'right',
    'total'     =>'sum',
    'type'      =>'number'
));
6. Add new functions to

app/code/core/Mage/Adminhtml/controllers/Report/ProductController.php
public function artistsoldAction()
{
    $this->_initAction()
        ->_setActiveMenu('report/product/artistsold')
        ->_addBreadcrumb(Mage::helper('reports')->__('Artists Sold Works'), Mage::helper('reports')->__('Artists Sold Works'))
        ->_addContent($this->getLayout()->createBlock('adminhtml/report_product_artistsold'))
        ->renderLayout();
}

7. Open the file

app/code/core/Mage/Reports/Model/Mysql4/Product/Artistsold/Collection.php.

Rename the class name from

Mage_Reports_Model_Mysql4_Product_Sold_Collection to

Mage_Reports_Model_Mysql4_Product_Artistsold_Collection

Customize the function setDateRange() in the as per your need.
public function setDateRange($frmdate, $todate)
  {
      $this->_reset()
          ->addAttributeToSelect('*')
          ->addOrderedQtyForArtistSold($frmdate,$todate);
return $this;
  }

8. To get the new fields, to alter the sql query I copied the function addOrderedQty() to addOrderedQtyForArtistSold() in the file

app/code/core/Mage/Reports/Model/Mysql4/Product/Collection.php

And I did changes in the functions as per my need to get the extra columns.

Here in my case:

public function addOrderedQtyForArtistSold($frm = '', $to = '')
   {
 if(key_exists('report',$_SESSION)) {
     $artistId = $_SESSION['report']['artistid'];
 }
 else {
  $artistId ='';
 }

       $qtyOrderedTableName = $this->getTable('sales/order_item');
       $qtyOrderedFieldName = 'qty_ordered';

       $productIdTableName = $this->getTable('sales/order_item');
       $productIdFieldName = 'product_id';

 $productEntityIntTable = (string)Mage::getConfig()->getTablePrefix() . 'catalog_product_entity_varchar';
 $adminUserTable = $this->getTable('admin_user');
 $artistsTable = $this->getTable('appartists');
 $eavAttributeTable = $this->getTable('eav/attribute');

       $compositeTypeIds = Mage::getSingleton('catalog/product_type')->getCompositeTypes();

       # This was added by Dev1 to get the configurable items in the list & not to get the simple products
       $compositeTypeIds = Array (
         '0' => 'grouped',
         '1' => 'simple',
         '2' => 'bundle'
      );

       $productTypes = $this->getConnection()->quoteInto(' AND (e.type_id NOT IN (?))', $compositeTypeIds);

       if ($frm != '' && $to != '') {
           $dateFilter = " AND `order`.created_at BETWEEN '{$frm}' AND '{$to}'";
       } else {
           $dateFilter = "";
       }

       $this->getSelect()->reset()->from(
          array('order_items' => $qtyOrderedTableName),
          array('ordered_qty' => "SUM(order_items.{$qtyOrderedFieldName})",'base_price_total' => "SUM(order_items.price)")
       );

       $order = Mage::getResourceSingleton('sales/order');

       $stateAttr = $order->getAttribute('state');
       if ($stateAttr->getBackend()->isStatic()) {

           $_joinCondition = $this->getConnection()->quoteInto(
               'order.entity_id = order_items.order_id AND order.state<>?', Mage_Sales_Model_Order::STATE_CANCELED
           );
           $_joinCondition .= $dateFilter;

           $this->getSelect()->joinInner(
               array('order' => $this->getTable('sales/order')),
               $_joinCondition,
               array()
           );
       } else {

           $_joinCondition = 'order.entity_id = order_state.entity_id';
           $_joinCondition .= $this->getConnection()->quoteInto(' AND order_state.attribute_id=? ', $stateAttr->getId());
           $_joinCondition .= $this->getConnection()->quoteInto(' AND order_state.value<>? ', Mage_Sales_Model_Order::STATE_CANCELED);

           $this->getSelect()
               ->joinInner(
                   array('order' => $this->getTable('sales/order')),
                   'order.entity_id = order_items.order_id' . $dateFilter,
                   array())
               ->joinInner(
                   array('order_state' => $stateAttr->getBackend()->getTable()),
                   $_joinCondition,
                   array());
       }

       $this->getSelect()
           ->joinInner(array('e' => $this->getProductEntityTableName()),
               "e.entity_id = order_items.{$productIdFieldName}")
            ->group('e.entity_id')
           ->having('ordered_qty > 0');

       $artistIdConcat = $artistId != '' ? " AND artistId=$artistId" : "";

       $this->getSelect()
           ->joinInner(
               array('pei' => $productEntityIntTable),
               "e.entity_id = pei.entity_id",
               array())
           ->joinInner(
               array('ea' => $eavAttributeTable),
               "pei.attribute_id=ea.attribute_id AND ea.attribute_code='artistid'",
               array())
           ->joinInner(
               array('au' => $adminUserTable),
               "au.user_id=pei.value",
               array("artistname" => "CONCAT(firstname, ' ',lastname)"))
           ->joinInner(
               array('ar' => $artistsTable),
               "ar.artistId=au.user_id".$artistIdConcat,
               array("sale_percentage" => "CONCAT(sale_percentage,'%')","artist_earned" => "((SUM(order_items.price)) * (sale_percentage)) / 100"));

       return $this;
   }



Hope it Helps... Thanks...