Wednesday, July 27, 2011

How to crop images in magento?

Here is the easiest way to crop image in Magento.
Here goes the code:
$mainImage = Mage::getBaseDir('media') . DS . 'test' . DS . 'sample.jpg';
$image = new Varien_Image($mainImage);
// crop image
$image->crop(10, 10, 10, 10); // crop(top, left, $right, $bottom)
$image->save(Mage::getBaseDir('media'). DS . 'test' . DS . 'new.jpg');
Code Explanation:
In the code above, you can see that I have an image named sample.jpg inside media/test/ directory.

At first, I have cropped the image by 10px from top, left, bottom, and right side.
The new cropped image is saved inside media/test/ directory as new.jpg.

How to remove index.php from URL magento?

If you are using Magento and in your shop URL, if you see “index.php” and wanted to remove it then here is the solution.

- Login to Magento admin panel
- Go to System -> Configuration -> Web -> Search Engines Optimization -> Use Web Server Rewrites
- Select ‘Yes’ from the selection list and Save.
- Goto your site root folder and you can find the .htaccess file. Just edit that. Open it on a text editor and find this line, #Rewrite Base /magento/ . Just replace it with Rewrite Base / .
- Then goto your Cache Management page ( System > Cache Management) and refresh your Cache and also refresh the Web Redirects.

And, you are done. Now, index.php is gone from your Magento shop URL.

Tuesday, July 26, 2011

How to change the default welcome message in magento?

Here is the easier way to change the Default welcome message that appears in header of Magento shop.
When the user is not logged in, by default the message appears as ‘Default welcome msg!‘.

To change the message text, follow steps below:-

- Go to
System -> Configuration -> GENERAL -> Design -> Header -> Welcome Text = YOUR WELCOME TEXT

That’s all. Now, the default welcome message is changed with your custom welcome message.

How to enable maintenance or offline mode in magento?

For Magento version 1.4 and above, You just need to create a file named maintenance.flag in your Magento root. Then, your website automatically goes into maintenance mode. To make the site live again, you can just delete the newly created maintenance.flag file.

You can edit maintenance mode template file. It is present in "errors/default/503.phtml"

For Magento version 1.3 and below,
- create a file called index.html in Magento root and write your maintenance messege in it
- write the following code in the beginning of index.php

// replace with your development IP
if ($_SERVER['REMOTE_ADDR']!=='192.168.2.4') {
  header("Location: /index.html");
  exit;
}

How to send email easily in magento?

Here is a quick code to send email in Magento using the Zend_Mail class.
/**
 * Send email
 */
public function sendEmail()
{
    $fromEmail = "from@example.com"; // sender email address
    $fromName = "John Doe"; // sender name
 
    $toEmail = "to@example.com"; // recipient email address
    $toName = "Mark Doe"; // recipient name
 
    $body = "This is Test Email!"; // body text
    $subject = "Test Subject"; // subject text
 
    $mail = new Zend_Mail();       
    $mail->setBodyText($body);
    $mail->setFrom($fromEmail, $fromName);
    $mail->addTo($toEmail, $toName);
    $mail->setSubject($subject);
 
    try {
        $mail->send();
    }
    catch(Exception $ex) {
        // If you are using this code in your custom module use 'yourmodule' name.
        // If not, you may keep 'customer' instead of 'yourmodule'.
        Mage::getSingleton('core/session')
            ->addError(Mage::helper('yourmodule')
            ->__('Unable to send email.'));
    }
}

Magento: How to get visitor or guest information and ip address?

//Get Visitor's information
  $visitorData = Mage::getSingleton('core/session')->getVisitorData();
 
  // printing visitor information data
  echo "
"; print_r($visitorData); echo "
"; // user's ip address (visitor's ip address) $remoteAddr = Mage::helper('core/http')->getRemoteAddr(true); // server's ip address (where the current script is) $serverAddr = Mage::helper('core/http')->getServerAddr(true);

Magento error "There are no products matching the selection"

After adding products I had a problem. The home page shows "There are no products matching the selection". So I did the following steps and it worked for me.

Solution:

Please check following settings are done for your product

1. The products must be Visible in Catalog.
2. The products must be Enabled.
3. Product must have a stock Quantity.
4. The product must be set to In Stock.
5. If the product is set not to track stock, it still need to have a stock Quantity and be set to In Stock.
6. The product must be assigned to the target Category.
7. If using multi-website mode (or if you imported the products through Data Flow), the products must be assigned to the target Website.
8. You must refresh your “var/Cache” & rebuild all indexes from admin > system > index management

Hope this helps you.

How to get store information in magento?

    // Get store data
    Mage::app()->getStore();

    // Store Id
    Mage::app()->getStore()->getStoreId();

    // Store code
    Mage::app()->getStore()->getCode();

    // Website Id
    Mage::app()->getStore()->getWebsiteId();

    // Store Name
    Mage::app()->getStore()->getName();

    // Is Active
    Mage::app()->getStore()->getIsActive();

    // Store Home Url
    Mage::app()->getStore()->getHomeUrl(); 

Tuesday, July 19, 2011

How to get custom attributes values?

// Get array of items in cart
        $items = Mage::getModel('checkout/session')->getQuote()->getAllItems();

        foreach($items as $item)
        {
            $productId = $item->getProduct()->getId();
            $productList = Mage::getModel('catalog/product')->getCollection()
                ->addAttributeToSelect('my_attribute')
                ->addIdFilter($productId);
            
            foreach($productList as $product)
            {
                continue;
            }
        }
you can call attribute functions as follows:

$product->getMyAttribute();

Get root categories in magento

$collection = Mage::getResourceModel('catalog/category_collection');
$collection->addAttributeToSelect('name')
    ->addPathFilter('^1/[0-9]+$')
    ->load();

$options = array();
foreach ($collection as $category) {
    $options[] = array(
       'label' => $category->getName(),
       'value' => $category->getId()
    );
}
print_r($options); 

How do I use more than two decimal places for prices?

To get 4 decimals accurancy for all prices in magento.
In /lib/Zend/Currency.php line 74
'precision' => 4,
Override in app/code/locale the Mage core files and make some changes :
Mage/Core/Model/Store.php line 790
public function roundPrice($price)
    {
        return round($price, 4);
    }
Mage/Directory/Model/Currency.php line 197
public function format($price, $options=array(), $includeContainer = true, $addBrackets = false)
    {
        return $this->formatPrecision($price, 4, $options, $includeContainer, $addBrackets);
    }
Hope that helps !

Monday, July 18, 2011

Which Ecommerce shopping cart software to use?

I am a real fan of Open Source software, and there are some great projects around, however up till now the e-commerce category has missed out. Nearly all of the open-source e-commerce systems I have checked out are just big piles of spaghetti code, that not only make development and maintenance of online shops a headache, I consider them to be grave security risks.

Magento has actually been designed - that has got to count for something! While with other projects I wince when I look under the hood, with Magento I am being pleasantly surprised by each new aspect I look at. In fact, I think there is a lot I can learn from this well implemented system. It is now only a preview release, and it is already light-years ahead.

Magento is a professional product, and you see that in both the development cycle and the quality of the code. In the forums the Magento team (at least so far) has been professional and responsive, not paranoid and elitist (osC) or whiny (Zen Cart). And Magento has features every store needs, which ZC just doesn’t. (osC doesn’t either, but then development essentially stopped on osC years ago . . . at least development that makes it to the public). ZC misses some core functionality that I can’t continue to live without and don’t feel like programming myself. I’m tired of wading through hacked-up code; it makes my hands itch to fix it, but I’m definitely not reinventing the wheel. Magento is a breath of fresh air there; the code has a solid, well-programmed feel and from what I can tell, it’s modular in a way ZC never will be (because osC wasn’t).

Magento is waaaaay easier to install than Zen Cart and osC (or at least it was for me). CharliesBooks is right in that an installation guide covering possible stumbling blocks (such as having mod_rewrite enabled, and how on earth you fix that if you’re *not* a technical person) is vital for software that caters to a general public. From what I’ve seen, Magento has every intention of providing that kind of assistance to its users; it’s just early in the game.

Magento has better functionality and the GUI look professional even with the default theme, like everyone else said create a better overall user experience and be the pioneer in using Magento.

How to get attribute name and value in Magento?

Here is the code to get attribute code and value for any product
Let as assume the attribute code is "my_attribute"
/**
 * get attribute collection
 */
$attribute = $_product->getResource()->getAttribute('my_attribute');
/**
 * get attribute type
 */
$attribute->getAttributeType();
/**
 * get attribute Label
 */
$attribute->getFrontendLabel();
/**
 * get attribute default value
 */
$attribute->getDefaultValue();
/**
 * check if the attribute is visible
 */
$attribute->getIsVisible();
/**
 * check if the attribute is required
 */
$attribute->getIsRequired();
/**
 * get attribute value
 */
$attributeValue = Mage::getModel('catalog/product')->load($_product->getId())->getMyAttribute();

Here is the code to fetch value from a select box attribute
$attributeValue = Mage::getModel('catalog/product')
                            ->load($_product->getId())
                            ->getAttributeText('my_attribute');

Add a Image Slider Banner in Magento Home page

We can Implement from Admin->CMS->Pages->Home Page


Magento Ban or lock the user

- Create a custom customer attribute of boolean type say: is_banned_customer
- Then set the value of is_banned_customer = 1 if that customer retries more than a threshold times.
- Then during login in check for that custom attribute as:
Mage_Customer_AccountController::loginPostAction()
public function loginPostAction()
    {
        if ($this->_getSession()->isLoggedIn()) {
            $this->_redirect('*/*/');
            return;
        }
        $session = $this->_getSession();

        if ($this->getRequest()->isPost()) {
            $login = $this->getRequest()->getPost('login');
            if (!empty($login['username']) && !empty($login['password'])) {
                try {
                    $session->login($login['username'], $login['password']);

                    /* check if user is banned::start */
                    if($session->getCustomer()->getIsBannedCustomer()){
                        //logout and redirect to info page or any page you like
                        $session->logout();
                        $this->_redirect('*/*/');
                        return;
                    }
                    /* check if user is banned::end */

                    if ($session->getCustomer()->getIsJustConfirmed()) {
                        $this->_welcomeCustomer($session->getCustomer(), true);
                    }
                } catch (Mage_Core_Exception $e) { 

How to get attributes on front end?

$_product->getData(’attribute_code’); 

Friday, July 1, 2011

Get customer groupid in magento

$groupid = Mage::getSingleton('customer/session')->getCustomerGroupId();