Monday, May 23, 2011

Get category URL from the URL rewrites

$urlKey =  Mage::getModel('core/url_rewrite')->loadByIdPath('category/3')->getRequestPath();
$url = Mage::getUrl('', array('_direct' => $urlKey)); 

Saturday, May 21, 2011

Call to undefined method Mage_Eav_Model_Mysql4_Entity_Attribute_Collection::addVisibleFilter()

Change
$collection = Mage::getResourceModel('eav/entity_attribute_collection')
            ->setEntityTypeFilter( Mage::getModel('eav/entity')->setType('catalog_product')->getTypeId() )
            ->addVisibleFilter();
to
 $collection = Mage::getResourceModel('eav/entity_attribute_collection')

            ->setEntityTypeFilter( Mage::getModel('eav/entity')->setType('catalog_product')->getTypeId() )

            ->addFilter("is_visible", 1);

Friday, May 20, 2011

Dashboard is blank in magento admin panel after upgrading

ERROR: "SQLSTATE[42S22]: Column not found: 1054 Unknown column ‘created_at’ in ‘field list’"

This may happen version compatible problem. Uninstall SQLi_dashboard or another module which is modify dashboard.

Wednesday, May 18, 2011

Get Customer Shipping/Billing Address

$customerAddressId = Mage::getSingleton('customer/session')->getCustomer()->getDefaultShipping();
if ($customerAddressId){
       $address = Mage::getModel('customer/address')->load($customerAddressId);
}
else
{
 $address = Mage::getSingleton('checkout/session')->getQuote()->getShippingAddress();
}

Thursday, May 12, 2011

Frontend blank after upgrading magento

Last day I tried to upgrade my magento version 1.3.3 to 1.5.X. I did upgrade successfully my backend was working fine. But my frontend was empty. It shows blank page. I stuck up with this issue. After a day spend i went to index.php page and enabled
ini_set('display_errors', 1);
Then I cleared the cache it shows few errors. I resolved all the issues and now my frontend works fine.

Call to a member function toHtml() upgrade problem

The error usually looks like this -

Fatal error: Call to a member function toHtml() on a non-object in \app\code\core\Mage\Core\Model\Layout.php on line 529

Navigate to the page.xml page
\app\design\frontend\default\themename\layout\page.xml

Find the line 


Replace with

Wednesday, May 11, 2011

PEAR ERROR: install failed

Login via ssh and try following comments.
    ./pear mage-setup .
    ./pear install magento-core/Mage_All_Latest
    ./pear upgrade-all
Look here

Show newly added products on a Magento CMS page or Homepage

// new products
{{block type="catalog/product_new" name="home.catalog.product.new" alias="product_homepage" template="catalog/product/new.phtml"}}
// random products
{{block type="catalog/product_list_random" name="product_random" template="catalog/product/list.phtml"}}

Showing products on a Magento CMS page or Homepage

// All products 
{{block type="catalog/product_list" name="home.catalog.product.list" alias="products_homepage" template="catalog/product/list.phtml"}}
// Products from one category
{{block type="catalog/product_list" name="home.catalog.product.list" alias="products_homepage" category_id="4" template="catalog/product/list.phtml"}}

How to show all products image in single page?

Put this code under CMS Page -> Layout Update XML
 <reference name="content">
          <block type="catalog/product" name="imagegallery" template="catalog/product/imagegallery.phtml"/>
  </reference>

app/design/frontend/default/<YOUR THEME>/template/catalog/product/imagegallery.phtml
<?php
    $_productCollection = Mage::getModel('catalog/product')->getCollection()
    ->addAttributeToFilter('visibility', 4)
    ->addAttributeToFilter('status',1)
    //->setPage(1,3)
    ->addAttributeToSort('entity_id', 'DESC');
    $prod_list    =    new Mage_Catalog_Block_Product_List();
    $count        =        4;
?>
<table border="0">
<tbody>
<?php
    foreach($_productCollection as $_product):
    $_product->load($_product->getId());
  if($count % 4 == 0){ echo '<tr style="margin-bottom:20px;">'; }

// Product Image
    echo '<td align="center"><a class="product-image" href='.Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB).$_product->getUrlPath().'><img src='.$_product->getImageUrl().' width="80" height="77"  /></a>';

//Product Name
    echo '<h4 class="product-name">'.$_product->getName().'</h4></td>';
    $count++;
    if($count % 4 == 0){ echo "</tr>"; }
    endforeach;
?>
</tbody>
</table>

Add Main Category Images to Homepage

Put this code in your CMS homepage
{{block type="catalog/product_list" template="catalog/image.phtml"}}

Create a new file under app/design/frontend/default/<your theme="">/template/catalog/image.phtml
<?php
    //to get category id & name
    $helper     = Mage::helper('catalog/category');
        $collection = $helper->getStoreCategories('position', true, false);
       $array      = $helper->getStoreCategories('name', false, false);
    $categoryCount    =    0;
    //    echo "<pre>";print_r(get_class_methods($collection));
    echo "<table width='750' cellpadding='0' cellspacing='0' border='0' align='center'>";
    foreach ($collection as $cat):
    $Mcategory = Mage::getModel('catalog/category')->load($cat->getEntityId());

    if(($Mcategory->getLevel() == 2) && ($Mcategory->getImageUrl()))
    {
        if($categoryCount    %    4    ==    0)
        {
            echo "<tr>";
        }
   
        $categoryCount++;
    echo "<td width='245'>";
               
                  echo       "<div>
                            <a href=". $cat->getUrl() ." ><img src=".$Mcategory->getImageUrl()." align='middle' width='125px' height='105px' /></a>
                        </div>
                        <p><a style='color:#5C5C5C; font-weight:bold; text-decoration:underline; font-size:13px;' href=".$cat->getUrl()." >". $cat->getName()."</a></p>
                        <td>";
   
    if($categoryCount    %    4    ==    0)
    {
        echo "</tr>";
    }}
    endforeach;
    echo "</table>";
?>

Tuesday, May 10, 2011

Invalid method Mage_Wishlist_Model_Item::canConfigure(Array)

Try the following.

1. Copy wishlish.xml in base/default/layout to [your template]/layout
2. Copy wishlist folder in base/default/template to [your template]/template
3. Refresh Cache

Magento load products by sku

Mage::getModel('catalog/product')->loadByAttribute('sku', 'product-01-sku');

hide the price for users that are not logged on?

Go to
magento\app\design\frontend\default\\template\catalog\product\price.phtml

 if(Mage::getSingleton('customer/session')->isLoggedIn()): 
//just above 
 if (!$_product->isGrouped()): 
//and close it at the end of the file 
 endif; /* if ($this->isCustomerLoggedIn()): */ 

Showing products in a specific category

{{block type="catalog/product_list" category_id="10"}} 
where 10 is your featured category id.

If you are going to use in a phtml file you can use magento object to filter
$category = Mage::getModel('catalog/category')->load(10); 
$product = Mage::getModel('catalog/product') ->getCollection() ->addCategoryFilter($category); 
print_r($product);

Show featured products in home page

Download a free featured product extension here

Put it in CMS Home page content {{block type="featuredproducts/listing" template="inchoo/block_featured_products.phtml"}}

Go to admin menu and click on: Catalog > Featured Products
Configuration Options You will be able to choose layout for Featured product lising interface, use SEO features, Choose the number of products in the block and choose default sort order.

Adding Static Block content to right or left sidebar

You need to update a layout xml file located in app/design/frontend/DEFAULT/*DEFAULT*/layout/. Which xml file depends on exactly where you will be updating.

If you want this static block to show up on every single you will need to update the default handle in page.xml. Or, even better, create your own local.xml file as described here, and put this in the contents.

  
    
      
    
  

Adding Static Block content to a Page

Add Magento static blocks to your page easily! Simply copy this line of code below where you want the static block to appear and change the 'identifier' to the identifier of the static block you created. That's it!
$this->getLayout()->createBlock('cms/block')->setBlockId('identifier')->toHtml()
Alternative method:
{{block type="cms/block" block_id="my_block" template="cms/content.phtml"}}

Add additional shipping cost based on weight - Magento module

Description:
In this shipping module i added additional cost to the shipping cost based on cart weight. For example if the shipping cost is 5$ and cart weight is less than 18 pounds means i added additional 7$ to the shipping cost. So the total shipping cost would be 12$. You can also use this code for only particular product or for particular shipping methods.

app/etc/modules/Fixed_Shipping.xml


  
      
          true
          local
      
  

app/code/local/Fixed/Shipping/etc/config.xml

    
        
            0.7.4
        
    




Fixed_Shipping_Model_Rate





app/code/local/Fixed/Shipping/Model/Rate.php
class Fixed_Shipping_Model_Rate extends Mage_Sales_Model_Quote_Address_Rate

{

   public function importShippingRate(Mage_Shipping_Model_Rate_Result_Abstract $rate)

    {

        if ($rate instanceof Mage_Shipping_Model_Rate_Result_Error) {

            $this

                ->setCode($rate->getCarrier().'_error')

                ->setCarrier($rate->getCarrier())

                ->setCarrierTitle($rate->getCarrierTitle())

                ->setErrorMessage($rate->getErrorMessage())

            ;

        } elseif ($rate instanceof Mage_Shipping_Model_Rate_Result_Method) {

   $items = Mage::getSingleton('checkout/cart')->getQuote()->getItemsCollection()->getItems();

   $product = Mage::getModel('catalog/product');

   $total_weight=0; $additional_price = 0;

   foreach ($items as $item) 

   { 

    $product->load($product->getIdBySku($item->getSku()));

    $qty = $item->getQty();

    $weight = $item->getWeight();

    if($product->isConfigurable()){

     $total_weight+=($weight*($qty-1));

    } else {

     $total_weight+=($weight*$qty);

    }

   }
$var1 = Mage::getModel('core/variable')->loadByCode('ship_cond_1') ->getData(html_value);

//Shipping method codes -> flatrate, FEDEXGROUND, GROUNDHOMEDELIVERY, GND, 3DS, 2DA, 1DP, 1DA, 1DM

   if($total_weight <= 18)

   $additional_price = 7;

   else if($total_weight > 18 && $total_weight <= 43 )

   $additional_price = 10;

   else if($total_weight > 43 && $total_weight <= 61 )

   $additional_price = 14;

   else if($total_weight > 61 && $total_weight <= 80 )

   $additional_price = 16;

   else if($total_weight > 80 && $total_weight <= 1000 )

   $additional_price = 22;

   

   $price =$additional_price + $rate->getPrice();

            $this

                ->setCode($rate->getCarrier().'_'.$rate->getMethod())

                ->setCarrier($rate->getCarrier())

                ->setCarrierTitle($rate->getCarrierTitle())

                ->setMethod($rate->getMethod())

                ->setMethodTitle($rate->getMethodTitle())

                ->setMethodDescription($rate->getMethodDescription())

                ->setPrice($price)

            ;

        }

Mage::log($rate->getMethod());

        return $this;

    }


}

Magento: Check if current page is homepage?

if($this->getIsHomePage()) {
    echo 'You are in Homepage!';
} else {
    echo 'You are NOT in Homepage!';
}
Below is an alternative way to check for homepage:-
$routeName = Mage::app()->getRequest()->getRouteName();
$identifier = Mage::getSingleton('cms/page')->getIdentifier();
 
if($routeName == 'cms' && $identifier == 'home') {
    echo 'You are in Homepage!';
} else {
    echo 'You are NOT in Homepage!';
}

Monday, May 9, 2011

Check customer is logged in or not?

Mage::getSingleton('customer/session')->isLoggedIn());

How to use mysql select query in magento?

$cat_count = Mage::registry('current_category');
$query = 'SELECT COUNT(catalog_category_product_index.category_id) AS count FROM catalog_category_product_index WHERE catalog_category_product_index.category_id = '.print_r($cat_count['entity_id']).' GROUP BY catalog_category_product_index.category_id';
$query = Mage::getSingleton('core/resource')->getConnection('core_read')->query($query);
//and now you can build up your array or do anything you want (:
while($row=$query->fetch()) {
    $catCount[$row['category_id']]=$row['count'];
echo $row['count'];
} 

set or get magento session

//Setting session
Mage::getSingleton('core/session')->setMySessionVariable('value');
//Getting session
Mage::getSingleton('core/session')->getMyDesignProductVariable()
//Unset session
Mage::getSingleton('core/session')->setTestingMagento();

//(Use customer or core session in frontend. Use adminhtml session in the backend.)
Core Session:- Mage::getSingleton(‘core/session’)
Customer Session:- Mage::getSingleton(‘customer/session’)
Admin Session:- Mage::getSingleton(‘adminhtml/session’) 

Get Order Increment Id in Magento

$order = Mage::getModel('sales/order');
$order->load(Mage::getSingleton('sales/order')->getLastOrderId());
$lastOrderId = $order->getIncrementId();
Last real order id
Mage::getSingleton('checkout/session')->getLastRealOrderId();

Get Last Insert Id in magento

$connection    = Mage::getSingleton(’core/resource’)->getConnection(’core_write’);
$sql         = "INSERT INTO `table` SET field1 = ?, field2 = ?, ...";
$connection->query($sql, array($field1_value, $field2_value, ...));
$lastInsertId = $connection->lastInsertId();
echo $lastInsertId; 

Get current Url of the page in magento

$this->helper('core/url')->getCurrentUrl();

Get CMS Page ID in magento

function getCurrentCmsPage() {
$pageId = Mage::getBlockSingleton('cms/page')->getPage()->getIdentifier();
return $pageId;
}

List of getBaseUrl() parameters

* Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_JS);
http://magesite.extension/js/

* Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_LINK);
http://magesite.extension/index.php/

* Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA);
http://magesite.extension/media/

* Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_SKIN);
http://magesite.extension/skin/

* Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB);
http://magesite.extension/

If you don’t provide any parameters to getBaseUrl() function you would retrieve the same path as with URL_TYPE_LINK parametar.

Remember, you need to echo out these statements to the browser, because they each return a string, so you need to output that string like
echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB);

Where can i find the .htaccess file in magento?

The .htaccess file should be in the root of your magento.

To view hidden files in linux system
Go to Magento root folder -> In the menu bar click view tab and then check show hidden files.

To view hidden files in windows

1. Double-click on the magento root folder.
2. Select the Tools menu and click Folder Options.
3. After the new window appears select the View tab.
4. Put a checkmark in the checkbox labeled Display the contents of system folders.
5. Under the Hidden files and folders section select the radio button labeled Show hidden files and folders.
6. Press the Apply button and then the OK button.

Upgrade magento pear

Login via ssh
./pear mage-setup .
./pear install magento-core/Mage_All_Latest
rm -rf downloader/pearlib/cache/* downloader/pearlib/download/*

You also might need to clear your cache directory out after an upgrade:
rm -rf var/cache/*

CONNECT ERROR: Couldn't resolve host 'magento-core'

The problem happens because of the Magento connect versions

use this in front of the extension key name:

"http://connect20.magentocommerce.com/community/"
instead of "magento-community/"

example:

"http://connect20.magentocommerce.com/community/AW_Blog"

To find which version of magento connect to use look here

How to find which version of Magento Connect Manager to use?

The only versions of Magento which carry 2.0 are:

* Enterprise Edition 1.9-RC3 & later
* Professional Edition 1.9 & later
* Community Edition 1.4.2.0-RC1 only
* Community Edition 1.5 & later

Remains uses the connect manager version 1.0

Note: Magento 1.4.2.0-RC1 was considered a “Release Candidate” and was released in a beta state. Beta versions are not intended for production use.

Magento MySQL database backup through terminal

If you don’t have phpMyAdmin installed but you have shell access you can use mysqldump tool. The syntax is as follow
mysqldump -h HOST -u USER -p DATABASENAME > FILENAME.sql
Where:
HOST -> is the database server hostname.

USER -> user with full privileges to the Magento database.

DATABASENAME - is the full name of the database which Magento is running.

FILENAME - can be anything you find suitable for the backup file.

How to set up a blog in Magento

Many of them feel to use blog in magento. However, blog functionality is not included by default and you will have to use a custom extension.

You can search blog extension through magentocommerce that will fully suit your needs. One of the popular free extensions that you can use is the Magento Blog – Community Edition.

Get the extension key and install through magento connect manager.

Once the extensions is installed, you can notice one additional section "Blog" in the top menu of your Magento admin area. From there you can start your blog post. Good luck.

How to speed up Magento?

Many Magento users faces the site loading problem. If we have larger amount of data the magento site becomes down. The recommended way to speed up Magento's performance is to enable its Compilation function. The performance increase is between 25%-50% on page loads.

You can enable Magento Compilation from your Magento admin panel > System > Tools > Compilation.

How to reset Magento Admin Password

To change your Magento admin password use the below query,
UPDATE admin_user SET password=CONCAT(MD5('mynewpass'), ':sG') WHERE username='AdminUsername';
Note: You should know your username.

Redirect Magento url to open through www

Sometimes we may want to open our site only through www (http://www.yourdomain.com).

To do this in Magento, you should edit the .htaccess file which is in the magento root folder. Locate the RewriteEngine in htaccess file then insert the below lines after the RewriteEngine :
RewriteCond %{HTTP_HOST} ^yourdomain.com$ [NC]
RewriteRule ^(.*)$ http://www.yourdomain.com/$1 [R=301,L]
After this go to admin area > System > Configuration -> web.

Change the Base URL option from http://yourdomain.com to http://www.yourdomain.com.

Save the changes and your Magento will start working through www.yourdomain.com only!

Invalid mode for clean() method in magento

To solve it just wipe out everything (Backend-folder, etc) in /app/code/core/Zend/Cache/

And try again.

add a Contact Us form anywhere in Magento

Magento includes contact form functionality by default. You can add a contact form on any page.

All you need to do is:

-> Log in to the admin area.
-> Go to CMS > Manage Pages.
-> Create a new cotact us page.

Paste the following code in the content area:

{{block type='core/template' name='contactForm' template='contacts/form.phtml'}}
Save the changes and the contact form will appear on the desired page.

Error 404 Not Found in Magento Admin Login Page

This error happens because admin values may changed in few tables.
SET FOREIGN_KEY_CHECKS=0;
UPDATE `core_store` SET store_id = 0 WHERE code='admin';
UPDATE `core_store_group` SET group_id = 0 WHERE name='Default';
UPDATE `core_website` SET website_id = 0 WHERE code='admin';
UPDATE `customer_group` SET customer_group_id = 0 WHERE customer_group_code='NOT LOGGED IN';
SET FOREIGN_KEY_CHECKS=1;

please alse see here

Moving local files to live Server : can not login into admin panel

Last night i tried to move files from local to live server. Everything was fine but I couldnt login to admin side. So I went through the live website database and local database I noticed that admin values are changed for the below tables.

core_store
core_store_group
core_website
customer_group

SET FOREIGN_KEY_CHECKS = 0;
UPDATE `core_store` SET `store_id` = '0' WHERE `store_id` = 1 LIMIT 1 ;
UPDATE `core_store` SET `store_id` = '1' WHERE `store_id` = 2 LIMIT 1 ;

UPDATE `core_store_group` SET `group_id` = '0' WHERE `group_id` = 1 LIMIT 1 ;
UPDATE `core_store_group` SET `group_id` = '1' WHERE `group_id` = 2 LIMIT 1 ;

UPDATE `core_website` SET `website_id` = '0' WHERE `website_id` = 1 LIMIT 1 ;
UPDATE `core_website` SET `website_id` = '1' WHERE `website_id` = 2 LIMIT 1 ;

UPDATE `customer_group` SET `customer_group_id` = '0' WHERE `customer_group_id` = 1 LIMIT 1 ;
UPDATE `customer_group` SET `customer_group_id` = '1' WHERE `customer_group_id` = 2 LIMIT 1 ;
UPDATE `customer_group` SET `customer_group_id` = '2' WHERE `customer_group_id` = 3 LIMIT 1 ;
UPDATE `customer_group` SET `customer_group_id` = '3' WHERE `customer_group_id` = 4 LIMIT 1 ;
SET FOREIGN_KEY_CHECKS = 1;

Moving to another Server: Duplicate entry ‘1’ for key 1

Method 1:
SET FOREIGN_KEY_CHECKS = 0;
UPDATE `core_website` SET `website_id` = 0 WHERE `core_website`.`code` = 'admin'  LIMIT 1 ;
UPDATE `core_store` SET `store_id` = 0 WHERE `core_store`.`code` = 'admin' LIMIT 1 ;
SET FOREIGN_KEY_CHECKS = 1; 

Method 2:
* Go to table `core_website` through phpmyadmin and set `website_id` = 0 for admin.
* Go to `core_store` and SET `store_id` = 0 for admin.

Magento Admin login problem

Problem:

I installed magento few days back. 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) 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();
} */

cache_dir must be a directory

Make a directory named "tmp" in the root of the magento installation that wil solve the problem.

Friday, May 6, 2011

Difference between magento enterprise and community edition?

Key points Community Edition Professional Edition Enterprise Edition
CMS+ (Enhanced Content Management System) No No Yes
Search with Solr (alternative search engine) No No Yes
Automated Email Marketing Reminders No No Yes
PCI Data Security Standard (PA-DSS) Compliant No Yes Yes
Reward Points System No Yes Yes
Gift Certificates/Cards (Physical and Virtual) No Yes Yes
Gift Registries No No Yes
Customer Store Credits No Yes Yes

What is magento?

Magento is an feature-rich open source  ecommerce web application. It was created by Varien, building on components of the Zend Framework launched on March 31, 2008. Magento comes in three different packages: Community, Professional and Enterprise Editions. The Community Edition is free to download it has limitations. The Professional and Enterprise Editions have more features but do require a yearly license fee.
A demo is available at Details