Tag Archives: Magento tutorials online

Magento add product to cart in programmatically


Magento add product to cart in programmatically : In magento we sometimes need to add the products in cart programmatically. Model Mage::getModel(‘checkout/cart’) is used to manage the cart in magento. Products can be added programmatically using this model. Here in this tutorial we are going to explain how to add products in magento cart programmatically.


Magento add product to cart in programmatically

Here is syntax to add an item programattically. First load the product object using product id which you want to add in cart. Then initialize the cart using the Mage::getModel(‘checkout/cart’); model and add the product object with quantity in cart’s object.

Magento add product to cart in programmatically:

load($productId);
$cart = Mage::getModel('checkout/cart');
$cart->init();
$cart->addProduct($product, array('qty' => $qty));
$cart->save();
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
?>

The above example will add the product with 3 quantities in the current cart.

Magento remove item from cart programmatically


Magento remove item from cart programmatically : We sometimes need to remove products(items) from the cart on the basis of sku or id. Here in this tutorial we are going to explain how to remove cart item(product) programmatically.


Magento remove item from cart programmatically

Remove Item(Product) By Sku from Cart

Use the below method to delete the product by sku as –

Magento remove Product from cart programmatically:

getCart()->getItems();
foreach ($items as $item) {
    if ($item->getProduct()->getSku() == $sku) {
	    $itemId = $item->getItemId();
        $cartHelper->getCart()->removeItem($itemId)->save();     
        break;
    }
}
}

?>

Call the above method and pass the sku as parameter. If sku matches with the items available in cart it will remove the product.

Remove Item(Product) By Product Id from Cart

Use the below method to delete the product by id as –

Magento remove Product from cart programmatically:

getCart()->getItems();
foreach ($items as $item) {
    if ($item->getProduct()->getId() == $productId) {
	    $itemId = $item->getItemId();
        $cartHelper->getCart()->removeItem($itemId)->save();     
        break;
    }
}
}

?>

Call the above method and pass the product id as parameter. If id matches with the items available in cart it will remove the product.

Magento get shipments for order


Magento get shipments for order : Mage_Sales module is used to manage the sales order shipments in magento. Shipments basically allows you to manage the shipments and tracking numbers in magento. Resource sales_order_shipment(order_shipment) is used for shipments in magento.In this tutorial we are going to explain how you can get all the shipments created against an order. There can be multiple shipments for an order.


Magento get shipments for order

You can get all the shipments of an order as below –

Magento get shipments for order:

load($orderId);
$shipmentIds = array();
foreach($order->getShipmentsCollection() as $shipment)
{
    $shipmentIds[] = $shipment->getId();
}

?>

The above example will give you array of shipment ids for order 1245. You also get other information about the shipments such as – total weight , total quantity etc.

Magento get invoice from order


Magento get invoice from order : Basically Mage::getModel(‘sales/order’) is used to get the invoice collection using this invoice collection is loaded from the order. As we know invoices are created against the order. An order can have one or more than one invoice. Here in this tutorial we are going to explain how to get the all invoice of an order.
.


Magento get invoice from order

You can get all invoice of the an order as below which show how to get invoice increment ids and grand total from order. –

Magento get invoice from order id:

load($orderId);
$invoiceIncrementIds = array();
if ($order->hasInvoices()) {
    foreach ($order->getInvoiceCollection() as $invoce) {
        $invoiceIncrementIds[] = $invoce->getIncrementId();
    }
}

?>

The above example will give you all the invoices created against the order id 1245. You can get other details of invoice same as grandtoal, increment id.

Get More About Invoice From Order

Let us get more details of invoices from order as below –

Get Subtotal | Grand total | Shipping Amount From Invoice Of Order

Get Subtotal | Grand total | Shipping Amount From Invoice Of Order:

load($orderId);
if ($order->hasInvoices()) {
    $grandTotal = array();
    $subTotal = array();
    $shippingAmount = array();
    $invoiceIncrementIds = array();
    foreach ($order->getInvoiceCollection() as $invoce) {
        $invoiceIncrementId = $invoce->getIncrementId();
                $invoiceIncrementIds[] = $invoiceIncrementId;
		$grandTotal[$invoiceIncrementId] = $invoice->getGrandTotal();
                $subTotal[$invoiceIncrementId] = $invoice->getSubTotal();
                $shippingAmount [$invoiceIncrementId] = $invoice->getShippingAmount();
    }
}

?>

Magento 2 get current url


Magento 2 get current url : While working with magento we often need to know the current url so that we can work with it. Here in this tutorial we are going to explain how to get the current url in magento. We will also explain how to get the current controller name , Action name or Module name.


Magento 2 get current url

You can get the current url in magento as below –

Magento 2 get current url:

echo $currentUrl = $this->getRequest()->getCurrentUrl();

The above example will give you the current url. example : http://example.com/test-product

Magento Get Current Controller name

You can get the current controller name in magento as below –

Magento Get Current Controller name:

$controllerName = $this->getRequest()->getControllerName();

The above example gives the controller name.

Magento Get Current Action name

You can get the current action name in magento as below –

Magento Get Current Action name :

$actionName = $this->getRequest()->getActionName();

The above example gives the action name.

Magento Get Route name

You can get the current route name in magento as below –

Magento Get Current Route name :

$actionName = $this->getRequest()->getRouteName();

The above example gives the route name.

Magento Get Module name

You can get the current Module name in magento as below –

Magento Get Current Module name :

$actionName = $this->getRequest()->getModuleName();

The above example gives the module name.

Magento export products in csv


Magento export products in csv : We sometimes need to export the magento products in files such as csv, xml. Here in this tutorial we are going to to explain how to export all the enabled products in csv file. We are going to create a script which will load product collection on the basis of the status filter. You can add your needed filter in product collection.


Magento export products in csv

Steps to export products in csv file in magento-

1. Create a file at root of magento named as exportProducts.php
Now add the below code in the file which contains the code to export the enabled products. The fields exported will be id, sku, name and price.

Magento export products in csv:

getCollection();
$products->addAttributeToFilter('status', 1);
$fopen = fopen('products.csv', 'w');
$csvHeader = array("id","sku", "name", "price");// Add the fields you need to export
fputcsv( $fopen , $csvHeader,",");
foreach ($products as $product){
    $id = $product->getId();
	$sku = $product->getSku();
	$name = $product->getName();
	$price = $product->getPrice();
    fputcsv($fp, array($id,$sku,$name, $price), ",");Add the fields you added in csv header
}
fclose($fopen );

2. Run this file in browser such as : http://example.com/exportProducts.php
When you run this file a csv file products.csv will be create which will look something like this –

Magento export products in csv

You can add the fields which you need to export in csv file. The above example exports only product id, sku, name and price.

Tip : You can add your own filter to get the products from database as per your requirement.
Note : If You have a lot products try incremental approach instead of loading all products at one time which will give better performance.

Magento Core Query – Read Write


Magento Core Query – Read Write : Magento provides data models to access the data from tables and modify them. Using models to perform data operations is easier and good practice. Sometimes we need to perform Direct SQL queries to perform read or write operation. In some cases writing direct SQL queries becomes simpler & faster in terms of performance. For example if we want to update the rows of a table using magento model, for this we need to loop all the rows and then set value to update them which will take more time than updating the rows using Direct SQL Queries which will take 2-3 seconds. Here in this tutorial we are going to explain how to use the Direct SQL Queries in Magento.


Magento Core Query – Read Write

Table Name & Table Prefix

While installing magento we have option to provide the table prefix which is appended before the each table name of magento. You can get table name prefix as below –

Magento Core Query – Read Write: Table Name & Table Prefix

getTableName('your_table_name');
	
	or 
	/**
	*Get Table Name From Entity
	*/
	$tableName = $resource->getTableName('catalog/product');
	
	echo $tableName;
	// will give you name with prefix ie. magento_your_table_name
?>

Read Data From Database:

If you want to preform read operation use the following syntax :

Magento Core Query – Read Write: Read operation

getTableName('catalog_product_entity');
	
	$read = Mage::getSingleton( 'core/resource' )->getConnection( 'core_read' );
        // used to  perform read operation
        $tableName = $resource->getTableName('catalog/product');
	
	$query = "SELECT * FROM " . $tableName . " WHERE created_at > $createdAt ";
        $result = $read->query($query);
        print_r($result);
?>

Mage::getSingleton( ‘core/resource’ )->getConnection( ‘core_read’ ); is used to perform the read operation on the database. The above example will execute the query and give the result.

Write Data to Database:

If you want to preform write operation use the following syntax :

Magento Core Query – Read Write: Write Operation

getConnection( 'core_write' );
        
        $tableName = $resource->getTableName('your_table_name');
	
	$write->query("insert into " . $tableName . "(field1, field2, field3) values('value1', 'value2', 'value3')");
?>

Mage::getSingleton( ‘core/resource’ )->getConnection( ‘core_write’ ); is used to perform the write operation on the database. The above example will execute the insert query.

More About Magento Custom Query

Let us have a look over other Read – Write Example.

Magento Read::fetchAll

Magento Core Query – Read Write: Read operation

getTableName('catalog_product_entity');
	
	$read = Mage::getSingleton( 'core/resource' )->getConnection( 'core_read' );
        // used to  perform read operation
        $tableName = $resource->getTableName('catalog/product');
	
	$query = "SELECT * FROM " . $tableName . ";
        $result = $read->fetchAll($query);
        print_r($result);
?>

The above example will give you all result from the table.

Magento Read::fetchOne

Magento Core Query – Read Write: Read operation

getTableName('catalog_product_entity');
	
	$read = Mage::getSingleton( 'core/resource' )->getConnection( 'core_read' );
        // used to  perform read operation
        $tableName = $resource->getTableName('catalog/product');
	
	$query = "SELECT * FROM " . $tableName . ";
        $result = $read->fetchOne($query);
        print_r($result);
?>

The above example will give the only one value from the first row.

Magento create Root category programmatically


Magento create Root category programmatically : In magento sometimes we need to create the categories programmatically. The model Mage::getModel(‘catalog/category’); is used for categories in magento. In this tutorial we are going to explain how to create categories programmatically with example.


Magento create Root category programmatically

You can create categories programmatically as below-

Create sub category In Magento –

If you know parent id and want to create the sub category you use the below method –

Magento create category programmatically:

try{
    $category = Mage::getModel('catalog/category');
    $category->setName('Test Category');
    $category->setUrlKey('test-category');
    $category->setIsActive(1);
    $category->setDisplayMode('PRODUCTS');
    $category->setIsAnchor(1); 
	$storeId = Mage::app()->getStore()->getId();
    $category->setStoreId($storeId);
	$parentId = 12;
    $parentCategory = Mage::getModel('catalog/category')->load($parentId);
    $category->setPath($parentCategory->getPath());
    $category->save();
} catch(Exception $e) {
    echo $e->getMessage();
}

The above example will create a sub category in parent category with $parentId = 12;

Create root category in Magento –

If you want to create root categoory in magento you need to set following two things –

  • Store id as 0
  • Parent Id as 1.

Magento create root category programmatically:

try{
$storeId    = 0;
$category = Mage::getModel('catalog/category');
$category->setStoreId($storeId);
$category->setName('Test category');
$category->setUrlKey('Test category');
$category->setIsActive(1);
$category->setDisplayMode('PRODUCTS');
$parentId = Mage_Catalog_Model_Category::TREE_ROOT_ID;
$parentCategory = Mage::getModel('catalog/category')->load($parentId);
$category->setPath($parentCategory->getPath());
$category->save();
} catch(Exception $e) {
    echo $e->getMessage();
}

The above example will create the root category.

Magento error service temporarily unavailable


Magento error service temporarily unavailable – Sometimes the mesaages “Error 503: Service Temporarily Unavailable” and “The server is temporarily unable to service your request due to maintenance downtime or capacity problems. Please try again later” is displayed in magento. Basically magento creates a file maintenance.flag on root when it is performing some specific action to show users maintenance message. You can fix this issue by deleting this file.


Magento error service temporarily unavailable

1. When there is problem with server and it is giving the 503 error response.

2. Or When store is in maintenance mode. Sometimes when magento is performing some tasks it creates the maintenance.flag. If maintenance.flag is found at root then magento shows default 503 error page.

Solution

Magento error service temporarily unavailable

To fix this issue simply delete the file maintenance.flag which is created at root.

Fix service unavailable magento

After deleting this it should work as usual.