Wednesday 16 December 2015

How to use helpers in magento ?

In magento helpers is very useful functionality.Basically we can call helper functions anywhere in the site .

Each module has its own helper function

like in magento you use a below cart helper function to get cart url 

Mage::helper('checkout/cart')->getCartUrl()

the above helper function is created at below location

app/code/core/Mage/Checkout/Helper/Cart.php 

Lets create one new helper function in the end of Cart.php 

let say we need a function in which we need to get all ordered product items data 

 
For this i have create a new function as below

public function getordered_products_data($order_id){
        $cart =  Mage::getModel('sales/order')->load($order_id);
        print_r($cart->getData());die;
        foreach ($cart->getAllItems() as $item) {
        $loadproduct =     Mage::getModel('catalog/product')->load($item->getProduct()->getId());
        print_r($loadproduct->getData());
        }

}


and now we can use this function anywhere in the site as below

Mage::helper('checkout/cart')->getordered_products_data($your_order_id); // pass your order id here

and with this you can see all products data in order anywhere in the site by using above function.

thanks and hope it will help the magento comunity 


Thursday 3 December 2015

how to redirect http to https or vice versa through htaccess

To redirect the site from http to htttps just use the below code in the top of htaccess file


for htttps to http


RewriteEngine On
RewriteCond %{HTTPS} on
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]


for http to https 

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]

 

 



Friday 30 October 2015

Magento - blocks not showing problems after installing SUPEE-6788

Hi recently i have install a latest patch from magento  SUPEE-6788 in my magento store.
But it has causes  block not render problem, no  blocks was visible on frontend .

than i troubleshoot it and found that in this patch magento has added a 2 new tables named as

permission_variable   and   permission_block 

  • first of all check if these tables exist in your database or not
  •  if they exist than check in permission_block table that your  block value exist in that table or not like below


 you will need to be insert your block name in the permission_block  as above
once you will  done with your block name and your blocks should be visible on frontend



Sunday 25 October 2015

how to check admin is logged in or not in Magento

 Hi with the below peace of code you can check admin user is logged in or not anywhere is magento

$sesId = isset($_COOKIE['adminhtml']) ? $_COOKIE['adminhtml'] : false ;
$session = false;
if($sesId){
    $session = Mage::getSingleton('core/resource_session')->read($sesId);
}
$loggedIn = false;
if($session)
{
    if(stristr($session,'Mage_Admin_Model_User'))
    {
        $loggedIn = true;
    }
}
var_dump($loggedIn);// this will be true if admin logged in and false if not

Thursday 8 October 2015

How to get category tree structure in Magento programatically ?

In many places we will need to get the category tree in magento programmatically. With the below peace of code you can get the tree anywhere in magento



   $rootCatId = Mage::app()->getStore()->getRootCategoryId(); // it will fetch your current store root id
   $catlistHtml = getTreeCategories($rootCatId, false);
   echo $catlistHtml;

function getTreeCategories($parentId, $isChild){
    $allCats = Mage::getModel('catalog/category')->getCollection()
                ->addAttributeToSelect('*')
                ->addAttributeToFilter('is_active','1')  // is acategory active
                ->addAttributeToFilter('include_in_menu','1') //  to check include_in_menu yes or no
                ->addAttributeToFilter('parent_id',array('eq' => $parentId))  // filter parent id
                ->addAttributeToSort('position', 'asc');
              
    $class = ($isChild) ? "sub-cat-list" : "cat-list";
    $html .= '<ul class="'.$class.'">';
    foreach($allCats as $category)
    {
        $html .= '<li><span>'.$category->getName()."</span>";
        $subcats = $category->getChildren();
        if($subcats != ''){
            $html .= getTreeCategories($category->getId(), true);
        }
        $html .= '</li>';
    }
    $html .= '</ul>';
    return $html;
}


Please let me know if there is other such easy way to do this.I will love to hear and update my post.

thanks

Wednesday 7 October 2015

How to get products of particular category in Magento ?

Hi it is very easy to get products of particular category in magento.
Check the below peace of code , with this you can get the products of your desored category


$products =
              Mage::getModel('catalog/category')->load('put your category id here')
            ->getProductCollection()
            ->addAttributeToSelect('*') ;
          

                foreach($products as $productsss){
                                  print_r($productsss->getData());
                    }


you can also add the filters in the above collection to get your desired products
like if you want to get only enabled products in the particular category like

$products = Mage::getModel('catalog/category')->load($catid)
            ->getProductCollection()
            ->addAttributeToSelect('*')
            ->addAttributeToFilter('status', 1) ;


with this only products enabled will be show in list. You can add as many as filters you want.

Hope it will help somebody.

Thanks


Sunday 31 May 2015

How to get customer session in external file Magento ?

Hi sometime we need to access the customer session in nexternal file and with the below code you can access


<?php
// Include Magento application
require_once ( "path_to_your_magento/app/Mage.php" );
umask(0);

// Initialize Magento
Mage::app();

// You have two options here,
// "frontend" for frontend session or "adminhtml" for admin session
Mage::getSingleton("core/session", array("name" => "frontend"));

$session = Mage::getSingleton("customer/session");

if($session->isLoggedIn())
{
    echo "Logged in";
}else{
    echo "Not logged in";
}

Monday 25 May 2015

Copy products from one category to another in Magento

Hi sometime we need to copy the products from one caegory to another in magento , but by default there is no such option like this in magento. So we can do this programatically with the below code




<?php
$category = Mage::getModel('catalog/category');
$category->load('2'); // Preset category id
$collection = $category->getProductCollection();
$collection->addAttributeToSelect('*');
foreach ($collection as $product) {
$product->getId();// Now get category ids and add a specific category to them and save?
$categories = $product->getCategoryIds();
$categories[] = 3; // Category to add
$product->setCategoryIds($categories);
$product->save();

}

Thursday 21 May 2015

Programatically create order in Magebto ?

HI sometime we need to create a orders grammatically in magento and with the below code you can easily


Create a new file in magento root and add the below code in that
<?php
require_once('../app/Mage.php'); //Path to Magento
umask(0);
Mage::app();


$productids=array(1,2); // products you want to add in order
$websiteId = Mage::app()->getWebsite()->getId();
$store = Mage::app()->getStore();
$order=1;
 // Start New Sales Order Quote
 $quote = Mage::getModel('sales/quote')->setStoreId($store->getId());

 // Set Sales Order Quote Currency
 $quote->setCurrency($order->AdjustmentAmount->currencyID);
 $customer = Mage::getModel('customer/customer')
             ->setWebsiteId($websiteId)
             ->loadByEmail('demo@gmail.com');
 if($customer->getId()==""){
     $customer = Mage::getModel('customer/customer');
     $customer->setWebsiteId($websiteId)
             ->setStore($store)
             ->setFirstname('rohit')
             ->setLastname('goel')
             ->setEmail('any@gmail.com')
             ->setPassword("123456");
     $customer->save();
 }

 // Assign Customer To Sales Order Quote
 $quote->assignCustomer($customer);

     // Configure Notification
 $quote->setSendCconfirmation(1);
 foreach($productids as $id){
     $product=Mage::getModel('catalog/product')->load($id);
     $quote->addProduct($product,new Varien_Object(array('qty'   => 1)));
 }

 // Set Sales Order Billing Address
 $billingAddress = $quote->getBillingAddress()->addData(array(
     'customer_address_id' => '',
     'prefix' => '',
     'firstname' => 'john',
     'middlename' => '',
     'lastname' =>'Deo',
     'suffix' => '',
     'company' =>'',
     'street' => array(
             '0' => 'Patiala',
             '1' => 'Sector 64'
         ),
     'city' => 'Noida',
     'country_id' => 'IN',
     'region' => 'PB',
     'postcode' => '147001',
     'telephone' => '9464532670',
     'fax' => 'gghlhu',
     'vat_id' => '',
     'save_in_address_book' => 1
 ));
 $shipprice=10;
 // Set Sales Order Shipping Address
$shippingAddress = $quote->getShippingAddress()->addData(array(
     'customer_address_id' => '',
     'prefix' => '',
     'firstname' => 'Rohit',
     'middlename' => '',
     'lastname' =>'Goel',
     'suffix' => '',
     'company' =>'',
     'street' => array(
             '0' => 'Patiala',
             '1' => 'Sector 64'
         ),
     'city' => 'Patiala',
     'country_id' => 'IN',
     'region' => 'PB',
     'postcode' => '147001',
     'telephone' => '9464532670',
     'fax' => 'gghlhu',
     'vat_id' => '',
     'save_in_address_book' => 1
 ));
 if($shipprice==0){
     $shipmethod='freeshipping_freeshipping';
 }

 // Collect Rates and Set Shipping & Payment Method
 $shippingAddress->setCollectShippingRates(true)
                 ->collectShippingRates()
                 ->setShippingMethod('flatrate_flatrate')
                 ->setPaymentMethod('checkmo');

 // Set Sales Order Payment
 $quote->getPayment()->importData(array('method' => 'checkmo'));

 // Collect Totals & Save Quote
 $quote->collectTotals()->save();

 // Create Order From Quote
 $service = Mage::getModel('sales/service_quote', $quote);
 $service->submitAll();
 //$increment_id = $service->getOrder()->getRealOrderId();

 // Resource Clean-Up
 //$quote = $customer = $service = null;

 // Finished
 //return $increment_id;



?>

Wednesday 13 May 2015

Get all statuses of particular state in Magento

Hi by below code you can get the all statuses of a particular state 

$complete_statuses = Mage::getResourceModel( 'sales/order_status_collection' )->joinStates()->addFieldToFilter('state','complete');
foreach ($complete_statuses as $complete_statuses_array ){
    $stausarray[] =  $complete_statuses_array->getStatus();
}


in this i have get the statuses of a complete state. You can replace  state
in ->addFieldToFilter('state','complete');  according to your needs


run some function on ajax complete in prototype

HI sometime we need to detect the ajax complete event .In prototype you can do this by below code



Ajax.Responders.register({
  onComplete: function() {
       yourfunction(); // you can put your code here which you want to run on ajax complete event 
    }
});

Friday 8 May 2015

Get collection count in magento

HI you can get the colection count by below code


Mage::getModel('catalog/product')->getCollection()->getSize();  :)

Thursday 7 May 2015

How to redirect to referrer from Observer in Magento ?

we can redirect to the referrer from magento observer like below


Mage::getSingleton('core/session')->addError('your error message'); // to show your message after redirection
$url = Mage::helper('core/http')->getHttpReferer() ? Mage::helper('core/http')->getHttpReferer()  : Mage::getUrl();
Mage::app()->getFrontController()->getResponse()->setRedirect($url);
Mage::app()->getResponse()->sendResponse();
exit ;