9/27/2011

How to delete all sales order in magento

In Magento Connect you will find some extension which will delete all cancel order and Pending Order, But it never delete all processed order. To delete all orders following code snippet can be used.

<?php
require 'app/Mage.php';
Mage::app('admin')->setUseSessionInUrl(false);                                                                              
$sales_orders = Mage::getModel('sales/order')->getCollection()->getData();
foreach($sales_orders as $sales_order){
    $id = 0;
    $id = $sales_order['increment_id'];
    try{
        Mage::getModel('sales/order')->loadByIncrementId($id)->delete();
        echo "order #".$id." is removed".PHP_EOL;
    }catch(Exception $e){
        echo "order #".$id." could not be remvoved: ".$e->getMessage().PHP_EOL;
    }
}
echo "complete."
?>

9/26/2011

How to use or mysql condition in $collection data of magento

Magento provide  addAttributeToFilter to use and operator in $collection, But using of OR operator is little bit different . I was guess that there must be and OrAttributeToFilter , But I was wrong I think magento forgot to write this function, Lastly I found the solution to use mysql OR in magento . In addAttributeToFilter we have to write the condition in the form of array.
protected function _prepareCollection()
{
   $collection = Mage::getModel('catalog/product')->getCollection();
   $collection->addAttributeToFilter(
      array(
          array('attribute'=>'category_ids','finset'=>2),
          array('attribute'=>'category_ids','finset'=>3)
      )
   );
}


use your own attribute name and value to get the data

9/16/2011

How to upload and read csv file in magento

To upload CSV file and to read that file line by line , Please write the below code in magento

if(isset($_FILES['import_file']['name']) && $_FILES['import_file']['name'] != '')
{
    $uploaderFile = new Varien_File_Uploader('import_file');
    $uploaderFile->setAllowedExtensions(array());
    $uploaderFile->setAllowRenameFiles(false);
    $uploaderFile->setFilesDispersion(false);
    $uploaderFilepath = Mage::getBaseDir('media') . DS . 'importcsv' . DS ;
    $uploaderFile->save($uploaderFilepath, $_FILES['import_file']['name'] );
    $file = $_FILES['import_file']['name'];
    $filepath = $uploaderFilepath.$file;
    $i = 0;
    if(($handle = fopen("$filepath", "r")) !== FALSE) {
        while(($data = fgetcsv($handle, 1000, ",")) !== FALSE){            
            if($i>0 && count($data)>1){
                updateData($data);
            }          
            $i++;
        }
    }
    else{
        Mage::getSingleton('adminhtml/session')->addError("There is some Error");
        $this->_redirect('*/*/index');
    }
}
    function updateData($data)
    {
        //Write your code here and Update it to magento tables
    }