5 Useful code snippets for Magento Developers

Feb 13, 2014, by admin

When developing with Magento I have maintain a library of most used code snippets. These code snippets are very useful when developing theme or custom module since they save your precious time. You can just use this code snippet as it is without making any major change. Here I’m sharing those super useful Magento snippets that I’ve collected over the past year. Enjoy!

Check stock availability of product

protected function _isAvailable(Mage_Sales_Model_Order_Item $orderItem, $qty)
{
    if ($orderItem->getProductId()) {
        $stockItem = Mage::getModel(‘catalog/product’)
                  ->load($orderItem->getProductId())
                  ->getStockItem();

        if ($stockItem->getIsInStock() && (int)$stockItem->getQty() >= $qty) {
            return true;
        }
    }
    return false;
}

Display New Products On Home Page

{{block type=“catalog/product_new” name=“home.catalog.product.new”
alias=“product_homepage” template=“catalog/product/new.phtml”}}

Display New Products from Specific Category On Home Page

{{block type=”catalog/product_list” category_id=”10″ name=”home.catalog.product.new”
alias=”product_homepage” template=”catalog/product/new.phtml”}}

Get Attribute Option Labels

public function getOptionsLabels($attribute_code)
{
    $options = Mage::getModel(‘eav/entity_attribute’)
        ->loadByCode(‘catalog_product’, $attribute_code)
        ->getSource()->getAllOptions(true, true);

    $labels = array();
    foreach($options as $option) {
        if (trim($option[‘label’]) != ”) {
           $labels[] = $option[‘label’];
        }
    }
    return $labels;
}

Generate a CSV file

$file_path = “/your_dir_path/sample.csv”;
//file path of the CSV file in which the data to be saved
$mage_csv = new Varien_File_Csv();
//product ids whose data to be written
$products_ids = array(1,2,3);
//get products model
$products_model = Mage::getModel(‘catalog/product’);
$products_row = array();
foreach ($products_ids as $pid)
{
$prod = $products_model->load($pid);
$data = array();
$data[‘sku’] = $prod->getSku();
$data[‘name’] = $prod->getName();
$data[‘price’] = $prod->getPrice();
$products_row[] = $data;
}
//write to csv file
$mage_csv->saveData($file_path, $products_row);

Hope you all like the post visit our website and check our latest eCommerce and other templates

Click Here To Visit Our Website