10 Super Useful code snippets for Magento Developers

Posted on

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

Really very useful code to 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;
}

Source: http://magento-code-snippets.tumblr.com/post/5840964583/check-stock-availability-of-product

Creating a Invoice

Use this code to create invoice for an order in Magento.

$order = Mage::getModel('sales/order')->loadByIncrementId('100000001');
try {
if(!$order->canInvoice())
{
Mage::throwException(Mage::helper('core')->__('Cannot create an invoice.'));
}

$invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice();

if (!$invoice->getTotalQty()) {
Mage::throwException(Mage::helper('core')->__('Cannot create an invoice without products.'));
}

$invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_ONLINE);
//Or you can use
//$invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_OFFLINE);
$invoice->register();
$transactionSave = Mage::getModel('core/resource_transaction')
->addObject($invoice)
->addObject($invoice->getOrder());

$transactionSave->save();
}
catch (Mage_Core_Exception $e) {

}

Source: http://excellencemagentoblog.com/useful-code-snippets

Check if there are any shipping methods available

This is useful function to know that there is any shipping method available.

public function haveShippingMethods()
{
	if (count(Mage::getSingleton('checkout/session')->getQuote()->getShippingAddress()->getShippingRatesCollection())) {
		return true;
	}
	return false;
}

Source: http://magento-code-snippets.tumblr.com/post/8016917192/check-if-there-are-any-shipping-methods-available

Get an array of billing addresses and shipping addresses

Just use this code to get an array of billing address and shipping address.

$all_data = array();
$customer = Mage::getModel(‘customer/session’)->getCustomer();
foreach($customer->getAddressesCollection() as $customer_address)
{
$all_data[] = $customer_address;
}
var_dump($all_data);

Source: https://www.phpzag.com/get-an-array-of-billing-addresses-and-shipping-addresses-in-magento/

Display New Products On Home Page

Use this code snippets to display new products on home page.

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

Source: https://www.phpzag.com/magento-display-new-products-on-home-page/

Create a Shipment

Very handy code to create a shipment for an order in Magento.

$order = Mage::getModel('sales/order')->loadByIncrementId('100000001');
try {
    if($order->canShip()) {
        //Create shipment
        $shipmentid = Mage::getModel('sales/order_shipment_api')
                        ->create($order->getIncrementId(), array());
        //Add tracking information
        $ship = Mage::getModel('sales/order_shipment_api')
                        ->addTrack($order->getIncrementId(), array());       
    }
}catch (Mage_Core_Exception $e) {
 print_r($e);
}

Source: http://excellencemagentoblog.com/useful-code-snippets#Create Shipment

Display New Products from Specific Category On Home Page

Use this code to display new products from a particular 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"}}

Source: https://www.phpzag.com/magento-display-new-products-from-specific-category-on-home-page/

Get Attribute Option Labels

Useful code 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;
}

Source: http://magento-code-snippets.tumblr.com/post/5840079213/get-attribute-option-labels

Creating customer in Magento

Just use this precious code to create a customer account in Magento.

$customer = Mage::getModel('customer/customer');
$password = 'test1234';
$email = 'dtest@gmail.com';
$customer->setWebsiteId(Mage::app()->getWebsite()->getId());
$customer->loadByEmail($email);
if(!$customer->getId()) {
    $groups = Mage::getResourceModel('customer/group_collection')->getData();
    $groupID = '3';

    $customer->setData( 'group_id', $groupID );
    $customer->setEmail($email);
    $customer->setFirstname('test');
    $customer->setLastname('testing');
    $customer->setPassword($password);

    $customer->setConfirmation(null);
    $customer->save();

    echo $customer->getId();
}

Source:http://excellencemagentoblog.com/useful-code-snippets

Creating a Invoice

Use this code to create invoice for an order in Magento.

$order = Mage::getModel('sales/order')->loadByIncrementId('100000001');
try {
if(!$order->canInvoice())
{
Mage::throwException(Mage::helper('core')->__('Cannot create an invoice.'));
}

$invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice();

if (!$invoice->getTotalQty()) {
Mage::throwException(Mage::helper('core')->__('Cannot create an invoice without products.'));
}

$invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_ONLINE);
//Or you can use
//$invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_OFFLINE);
$invoice->register();
$transactionSave = Mage::getModel('core/resource_transaction')
->addObject($invoice)
->addObject($invoice->getOrder());

$transactionSave->save();
}
catch (Mage_Core_Exception $e) {

}

Source: http://excellencemagentoblog.com/useful-code-snippets

Generate a CSV file

By using this code, you can generate a CSV with the custom data in Magento.

$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);

Source: https://www.phpzag.com/generate-csv-file-in-magento/

 

Leave a Reply

Your email address will not be published. Required fields are marked *