Saturday, April 30

How to call the static block inside the CMS Page in Magento

We can easily call the static block in to the CMS Page.
first of all we have to create a static block

Let us suppose we have created the static block with the identifier "myfooter_block"

Now we can call the static block from the CMS Page easily with the help of following code

{{block type="cms/block" block_id="myfooter_block"}}
Hope it helps! thanks..

How to call a static block from template file in Magento

We can call a static block from template file (.phtml) easily.
First we have to create a static block..

Let us consider we have created a static block with the identifier "myfooter_block"

Now we can call the static block from any .phtml file with the help of following code..

<?php echo $this->getLayout()->createBlock('cms/block')->setBlockId('myfooter_block')->toHTML();?>

hope it helps. Thanks

Thursday, April 21

How to get List of Sub Category by main Category ID in Magento

In Magento default the "top.phtml" file shows all category and sub category. can access all category and subcategory in magento by editing "top.phtml"

Here is the location for "top.phtml"
app/design/frontend/your-package/your-theme/template/catalog/navigation/top.phtml

For that we will write the code in top.phtml file

<?php foreach ($this->getStoreCategories() as $_category): ?>
<li>
<a href="<?php echo $this->getCategoryUrl($_category)   ?>"><?php echo $this->htmlEscape($_category->getName())   ?></a>
<?php 
$_catid=$_category->getId();
$category = Mage::getModel('catalog/category')->load($_catid);
$subcategory =  $category->getAllChildren(true);
array_shift($subcategory);
if($subcategory!=null)
{?>
<ul>
<?php
 
foreach ($subcategory as $sub)
{
$sub1 = Mage::getModel('catalog/category')->load( $sub);
?>
<li><a href="<?php echo $sub1->getUrl();?>"><span>
<?php echo $sub1->getName(); ?>
</span></a></li>
<?php } ?>
 
</ul>
<?php  }?>
 
</li>
<?php endforeach ?>

Tuesday, April 19

How to filter all products by attribute value in Magento

Here, I will show how we can filter or fetch products related to any particular attribute and value.

A simple scenario will be filtering products by manufacturer/brand. Suppose, I want to get all products under ‘Samsung’ manufacturer/brand.

For this, you need the attribute code and attribute value ID for which you are fetching products.

To fetch attribute name and value, you can see my previous post here:- How to get attribute name and value in Magento

Now, lets move on to the code. Here is how you can do this:-
/**
 * Get all products related to any particular brand
 * Let us suppose that we are fetching the products related to 'Samsung' brand
 * Let us suppose the Manufacturer ID of Samsung = 3
 */
 
$manufacturerId = 3;
$attributeCode = 'manufacturer';
 
$products = Mage::getModel('catalog/product')
                    ->getCollection()
                    ->addAttributeToFilter($attributeCode, $manufacturerId);
 
// print all products
echo "
"; print_r($products->getItems()); echo "
";

How to get attribute name and value in Magento

Here is the code to get attribute code and value for any product
Let as assume the attribute code is "my_attribute"
/**
 * get attribute collection
 */
$attribute = $_product->getResource()->getAttribute('my_attribute');
/**
 * get attribute type
 */
$attribute->getAttributeType();
/**
 * get attribute Label
 */
$attribute->getFrontendLabel();
/**
 * get attribute default value
 */
$attribute->getDefaultValue();
/**
 * check if the attribute is visible
 */
$attribute->getIsVisible();
/**
 * check if the attribute is required
 */
$attribute->getIsRequired();
/**
 * get attribute value
 */
$attributeValue = Mage::getModel('catalog/product')->load($_product->getId())->getMyAttribute();

Here is the code to fetch value from a select box attribute

$attributeValue = Mage::getModel('catalog/product')
                            ->load($_product->getId())
                            ->getAttributeText('my_attribute');

Load any particular attribute by attribute code
$attributeInfo = Mage::getResourceModel('eav/entity_attribute_collection')
                        ->setCodeFilter(YOUR_ATTRIBUTE_CODE)
                        ->getFirstItem();
 
// echo "
"; print_r($attributeInfo->getData()); echo "
";

Get all option value list for the particular attribute

You can see above that I got attribute information by attribute code. My attribute information is stored as $attributeInfo.

Here is the code to get all option values for my attribute $attributeInfo.

$attributeOptions = $attributeInfo->getSource()->getAllOptions(false);
// echo "
"; print_r($attributeOptions); echo "
";

Get attribute’s option information by option id

I have my attribute as $attributeInfo.
I have my attribute’s option value array as $attributeOptions.

Suppose, I want to get detail information of any option listed in $attributeOptions array. Here is the code to do so
$attributeId = $attributeInfo->getAttributeId();
$optionId = YOUR_ATTRIBUTE_OPTION_ID;
 
$attributeOptionSingle = Mage::getResourceModel('eav/entity_attribute_option_collection')
                                    ->setPositionOrder('asc')
                                    ->setAttributeFilter($attributeId)
                                    ->setIdFilter($optionId)
                                    ->setStoreFilter()
                                    ->load()
                                    ->getFirstItem();
 
// echo "
"; print_r($attributeOptionSingle); echo "
";

Get attribute of particular entity type

Here, I am going to get information about ‘order_id’ attribute of ‘invoice’ entity type.

$entityType = Mage::getModel('eav/config')->getEntityType('invoice');
$entityTypeId = $entityType->getEntityTypeId();
 
$attribute = Mage::getResourceModel('eav/entity_attribute_collection')
                ->setCodeFilter('order_id')
                ->setEntityTypeFilter($entityTypeId)
                ->getFirstItem();
Get attribute options of Configurable product
$confAttributes = $_product->getTypeInstance(true)->getConfigurableAttributesAsArray($_product);

Friday, April 8

Allow Guests To Check Order Status in Magento

Step 1: First thing you have to do is add an API user with a role that has access to all Sales Order information. Generate an API key (any combination of letters and numbers at least 22 (128 bit) characters long) and copy it to Notepad or write it down. You will need it later.

Step 2: Create a New CMS Page that will contain our API code. We usually set the URL identifier to "order-status". Here is what goes in the Content of this new CMS page:
{{block type="core/template" template="cms/order-status-api.phtml"}}


Step 3: create the "order-status-api.phtml" file that will contain our API and HTML display code.
This file needs to be created at /app/design/frontend/default/yourtheme/template/cms/order-status-api.phtml


Here is the code that goes in this file.

<style type="text/css">
.orderStatusTable {
 border:1px solid #CCCCCC;
 font-size:11px;
}
.orderStatusTable td {
padding:8px;
}
.currentStatus {
 font-size: 11px;
 background-color: #eee;
 padding: 10px;
 margin: 0 0 15px 0;
 line-height: 15px;
 border: 1px solid #ccc;
 color: #333;
}
.currentStatus span {
 font-size: 14px;
 line-height: 23px;
 color: #000;
}
</style>
<div class="page-head">
 <h3>Check My Order Status</h3>
</div>

<p>Please enter your order number and email address to see the status of your order.</p>

<form name="" action="/order-status/" method="get">
<table border="0" cellspacing="0" cellpadding="0" class="orderStatusTable">
 <tr>
  <td><strong>Order Number:</strong></td>
  <td><input type="text" name="order_id" id="order_id" value="<?php echo (isset($_GET['order_id'])) ? $_GET['order_id'] : ''; ?>" /></td>
 </tr>
 <tr>
  <td><strong>Email Address:</strong></td>
  <td><input name="email_address" type="text" id="email_address" value="<?php echo (isset($_GET['email_address'])) ? $_GET['email_address'] : ''; ?>" size="30" /></td>
 </tr>
 <tr>
  <td>&nbsp;</td>
  <td><input type="submit" name="submit" value="Submit" /></td>
 </tr>
</table>

</form>

<div class="divider"></div>

<?php
 
 $live = true; //determines verbosity of errors
 
 $error = '';
 $statusMessage = '';
 $trackingNumberMessage = '';
 $shippingMessage = '';
 
 $orderID = '';
 $emailAddress = '';
 
 if(isset($_GET['order_id'])) {
  
  $orderID = trim(preg_replace('/[^0-9]*/', '', $_GET['order_id']));
  $emailAddress = trim($_GET['email_address']);
  
  try {
   
   ini_set("soap.wsdl_cache", "0");
   ini_set("soap.wsdl_cache_enabled", "0");
  
   //******************************************************************/
   
   // change to match your domain name
   $proxy = new SoapClient('http://www.yourdomain.com/api/soap/?wsdl');
   
   //change to your API username/password
   $sessionId = $proxy->login('apiusername', 'apikey');
   
   //******************************************************************/
   
   //find all orders related to this id
   $orderById = $proxy->call($sessionId, 'sales_order.info', $orderID);
   
   $items = $orderById['items'];
   
   if($orderById['customer_email'] == $emailAddress) {
    //we are setting this variable for use later
    $orderLookup = "success";
    if (strtolower($orderById['status']) == "holded") {
     $orderById['status'] = "On Hold";
    }
    $statusMessage = '<span>Your order status is: <strong>'.ucwords(str_replace('_', ' ', $orderById['status'])).'</strong></span>';
    
    if(ucwords(str_replace('_', ' ', $orderById['status'])) == "Processing"){
     $statusMessage .= '<br/><br/><strong>What does this mean?</strong><br/>Processing Time is the time it takes from when you submit your order to when the product leaves the Distribution Center.';
    }
    
   } else {
    $orderLookup = "failure";
    echo "We were unable to find your order information. Please verify your Order Number and Email Address are correct.";
   }
      
   //if the order status is complete we look up shipping information
   if(strtolower($orderById['status']) == "complete" && $orderLookup == "success") {
    

    //we look for all shipments related to this order id using internal magento order id
    $findShipments = $proxy->call($sessionId, 'sales_order_shipment.list', array(array('order_id'=>array('like'=>$orderById['order_id']))));
    
    if (count($findShipments) < 1) { //if $findShipments is not an array
     
     echo "There was an unknown error and your shipment information could not be found. Please contact Customer Service to get the current status of your order.";
     
    } else {
    
     //we pull the increment id for the shipment
     $thisShipmentID = $findShipments[0]['increment_id'];
     
     //now we pull all shipment info that specific shipment id
     $getShipmentInfo = $proxy->call($sessionId, 'sales_order_shipment.info', $thisShipmentID);
     $allowedCarriers = $proxy->call($sessionId, 'sales_order_shipment.getCarriers', $thisShipmentID);
     
     //set each variable
     $shipDate = $getShipmentInfo['created_at'];
     $service = $allowedCarriers[$getShipmentInfo['tracks'][0]['carrier_code']];
     if($service == "Custom Value") $service = "Truck Freight";
     $trackingNumber = $getShipmentInfo['tracks'][0]['number'];
             
     $defaultTimeZone = date_default_timezone_get();
     
     date_default_timezone_set('EST');
     
     //print_r($getShipmentInfo);
     
     if($service == "ups") {
      $trackingNumberMessage = "Tracking Number: <strong><a href='http://wwwapps.ups.com/WebTracking/track?loc=en_US&trackNums=".$trackingNumber."' target='_blank'>".$trackingNumber."</a></strong>";
     } else {
      $trackingNumberMessage = "Tracking Number: <strong>".$trackingNumber."</strong>";
     }
     
     //and echo the data to screen
     $shippingMessage = "Your order was shipped on " . date("l, F jS, Y \\a\\t g:i:s a T", strtotime($shipDate . ' ' . $defaultTimeZone)) . " via " . $service . ".<br/><br/>";
     
         
    } //no errors
   
   }
   
   
   if($orderLookup != "failure"){
   
    echo '<p class="currentStatus">'.$statusMessage.'<br/>'.$trackingNumberMessage.'</p>';
    
    echo $shippingMessage;
    
    echo "<h4>Products in your order:</h4><ul>";
      foreach($items as $item){
       echo "<li>".number_format($item['qty_invoiced'], 0) . " x <strong>" . strtoupper($item['sku']) . "</strong> " . $item['name'] . "</li>";
      }
    echo "</ul>";
   }
   
  } catch (SoapFault $fault) {
   //this is a basic implementation of error checking. I am using try to stop the error from showing a nasty magento error page
   if($fault->faultcode == "100") {
    echo "That Order Number was not found in our system.";
   } elseif ($fault->faultcode == "http") {
    echo "Request timed out. Please try again later.";
   } else {
    //leave this on for testing so we can see SOAP status codes; turn off for live
    if ($live == false) {
     echo "Error $fault->faultcode: $fault->faultstring";
    } else {
     echo "There was an unknown error. Please try again later, or contact us.";
    }
   }   
  }
  
  
  
 } // end if


?>
<p><br /><br /><em>For detailed information regarding the status of your order, please contact our helpful Customer Service Experts.</em></p>

IMPORTANT: You must change two lines in the code to match your settings. These are clearly commented starting at Line 72.

Save the changes you made and upload the file. You should now be able to access the file at http://www.yourdomain.com/order-status.

How to get Total Cart Item and total Price in magento

<?php
  $count = $this->helper('checkout/cart')->getSummaryCount();  //get total items in cart
  $total = $this->helper('checkout/cart')->getQuote()->getGrandTotal(); //get total price
  if($count==0)
  {
    echo $this->__('Items: %s',$count);
  }
  if($count==1)
  {
    echo $this->__(' Item: %s',$count);
  }
  if($count>1)
  {
    echo $this->__(' Items: %s',$count);
  }
  echo $this->__(' Total: %s', $this->helper('core')->formatPrice($total, false));
?>