Monday 28 October 2013

Add gift options in invoice pdf in Magento

for Add gift message to Magento’s PDF packingslip you have to modified invoice.php file in (\app\code\local\Mage\Sales\Model\Order\Pdf\Invoice.php)
it is a core file ao you have to move this file in local directory
 then find getPdf($invoices = array()) function in it

before   $this->_afterGetPdf();  this line add below code in it.

/*    Draw gift options*/
                $message = Mage::getModel('giftmessage/message');
                   $oid= $item->getOrderItemId();
                  $sales =  Mage::getModel('sales/order_item')->load($oid);
           
        $gift_message_id = $sales->getGiftMessageId();
        if(!is_null($gift_message_id)) {
              $message->load((int)$gift_message_id);
              $gift_sender = $message->getData('sender');
              $gift_recipient = $message->getData('recipient');
              $gift_message = $message->getData('message');

              $page->drawText(Mage::helper('sales')->__('Message from:'), 55, $this->y, 'UTF-8');
              $page->drawText(Mage::helper('sales')->__($gift_sender), 120, $this->y, 'UTF-8');
             $this->y -=10;
              $page->drawText(Mage::helper('sales')->__('Message to:'), 55, $this->y, 'UTF-8');
              $page->drawText(Mage::helper('sales')->__($gift_recipient), 120, $this->y, 'UTF-8');
             $this->y -=15;
              $page->drawText(Mage::helper('sales')->__('Message:'), 55, $this->y, 'UTF-8');
              $page->drawText(Mage::helper('sales')->__($gift_message), 120, $this->y, 'UTF-8');
             
             // $gift_message = wordwrap($gift_message, 140, "\n", false);
              /*$token = strtok($gift_message, "\n");
              $y = 740;
              while ($token != false) {
              if ($y < 60) {
              $pdf->pages[] = ($page = $pdf->newPage(Zend_Pdf_Page::SIZE_A4));
              $page->setStyle($style);
              }
              else {
              $page->drawText($token, 40, $this->y);
              $this->y-=10;
              }
              $token = strtok("\n");
              }*/

            }
                  /*    Draw gift options end*/

Wednesday 2 October 2013

delete existing order from invoice,shipment,credit memo.

http://www.magentocommerce.com/magento-connect/orders-eraser.html using of this extension you may delete order from sales > order> grid ,but if you want to delete same existing order id from invoice, shipment, creditmemo grid you have to customize little more in this extension.

For this you may change in function _erase2($orderId) in(\app\code\community\Wyomind\Orderseraser\Model\Orderseraser.php)
add below code:

$tablesfig = $resource->getTableName('sales_flat_invoice_grid');
$tablesfsg = $resource->getTableName('sales_flat_shipment_grid');
$tablesfcg = $resource->getTableName('sales_flat_creditmemo_grid');


$sql = "DELETE FROM " . $tablesfig . " WHERE order_id     = " . $orderId . ";";
$delete->query($sql);
$sql = "DELETE FROM " . $tablesfsg . " WHERE order_id     = " . $orderId . ";";
$delete->query($sql);
$sql = "DELETE FROM " . $tablesfcg . " WHERE order_id     = " . $orderId . ";";
$delete->query($sql);
      

magento summary rating of customers review in review list

put this code in(deault/default\template\review\product\view/list.phtml)
         <tbody>
                    <?php
                     $_percent = 0;
                    foreach ($_review->getRatingVotes() as $_vote){
                    $_percent = $_percent + $_vote->getPercent();
                    }
                      $_percent = $_percent / count($_review->getRatingVotes());?>
                    <tr>
                        <th class="label"><?php //echo $this->escapeHtml($_vote->getRatingCode()) ?>Aggregate rating:</th>
                        <td class="value">
                            <div class="rating-box">
                                <div class="rating" style="width:<?php echo  $_percent  ?>%;"></div>
                            </div>
                        </td>
                    </tr>
                    <?php //endforeach; ?>
                </tbody>


instead of

            <tbody>
                        <?php foreach ($_votes as $_vote): ?>
                        <tr>
                            <th><?php echo $this->escapeHtml($_vote->getRatingCode()) ?></th>
                            <td>
                                <div class="rating-box">
                                    <div class="rating" style="width:<?php echo $_vote->getPercent() ?>%;"></div>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>


Friday 20 September 2013

Get Order Details On Order Success-page

put the below code in frontend/default/default/template/checkout/success.phtml

<?php /* order detail on success page code starts here:- */ ?>
<?php $order = Mage::getModel('sales/order')->loadByIncrementId($this->getOrderId());
 $order_items = $order->getAllItems();
?>
<div class="success-box">
  <div class="successorderleft">
    <div class="content">
      <h4><?php echo $this->__('Your Confirmation Number is:') ?></h4>
      <p><?php echo $this->getOrderId();?></p>
      <p>Order Date: <?php echo  $this->formatDate($order->getCreatedAt(),'long') ;?></p>
    </div>
    <?php if($order->_data["shipping_description"]!=''){ ?>
    <div class="content">
      <h4><?php echo $this->__('Your Delivery type is:') ?></h4>
      <p><?php echo $shipping_method = $order->_data["shipping_description"];  ?></p>
    </div>
    <?php } ?>
    <div class="content">
      <h4><?php echo $this->__('And we&rsquo;ll deliver to:') ?></h4>
      <p><?php echo $order->getShippingAddress()->getFormated(true); ?></p>
    </div>
  </div>
  <div class="Successright">
    <div class="order-details-head"><?php echo $this->__('You Ordered:') ?></div>
    <table border="0" cellspacing="0" cellpadding="0" class="data-table">
      <thead>
        <tr class="first last">
          <th class="first" colspan="1"><?php echo $this->__('Product Name') ?></th>
          <th class="a-center" style="width:48px;"><?php echo $this->__('QTY') ?></th>
          <th class="a-right" style="width:102px;"><?php echo $this->__('Unit Price') ?></th>
        </tr>
      </thead>
      <tbody>
        <?php foreach($order_items as $_item):
        if ($_item->getParentItem()) continue;
       
        $product = Mage::getModel("catalog/product")->getIdBySku($_item->getSku());
        $product = Mage::getModel("catalog/product")->load($product);
    ?>
        <tr class="odd a-letf">
          <td><h2 class="product-name"><a href="<?php echo $product->getProductUrl() ?>">
              <?php  echo $this->htmlEscape($product->getName());?>
              </a> </h2>
            <?php
          if($_options = $_item->getProductOptions()):?>
            <dl class="item-options">
              <?php foreach ($_options['attributes_info'] as $_option) :  ?>
              <dt><?php echo $this->htmlEscape($_option['label']) ?></dt>
              <dd><?php echo $_option['value'] ?></dd>
              <?php endforeach; ?>
            </dl>
            <?php endif; ?></td>
          <td class="a-center" ><p class="Succqty"><?php echo abs($_item->getQtyOrdered()); ?></p></td>
          <td class="a-right" ><?php echo Mage::helper('checkout')->formatPrice($this->helper('checkout')->getSubtotalInclTax($_item)) ?></td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
    <table cellpadding="0" cellspacing="0" background="0" class="Successtabletotal">
      <tr>
        <td colspan="2" class="a-right success-subtotal"><?php echo $this->__('Subtotal:'); ?></td>
        <td class="a-right success-subtotal" style="width:102px;"><?php echo Mage::helper('checkout')->formatPrice($order->getSubtotal());?></td>
      </tr>
      <?php if($order->getCouponCode()!=""){?>
      <tr>
        <td colspan="2" class="a-right success-subtotal"><?php echo $this->__('Discount('.$order->getCouponCode().')'); ?></td>
        <td class="a-right success-subtotal" style="width:102px;"><?php echo Mage::helper("core")->currency($order->discount_amount) ;?></td>
      </tr>
      <?php }?>
      <tr>
        <td colspan="2" class="a-right success-shipping"><?php echo $this->__('Shipping:'); ?></td>
        <td class="a-right success-shipping" style="width:102px;"><?php echo Mage::helper('checkout')->formatPrice($order->getShippingAmount());?></td>
      </tr>
      <tr>
        <td colspan="2" class="a-right success-tax"><?php echo $this->__('Tax:'); ?></td>
        <td class="a-right success-tax" style="width:102px;"><?php echo Mage::helper('checkout')->formatPrice($order->getTaxAmount());?></td>
      </tr>
      <tr>
        <td colspan="2" class="a-right success-total"><?php echo $this->__('Total:'); ?></td>
        <td class="a-right success-total" style="width:102px;"><?php echo Mage::helper('checkout')->formatPrice($order->getGrandTotal());?></td>
      </tr>
    </table>
  </div>
</div>
<?php /* order detail on success page code end here:- */ ?>

Friday 19 July 2013

how to get current url in php

<?php echo $_SERVER['HTTP_REFERER'];?>

Discount per product in magento

steps for apply discount per product by percent & also create by flat amount

1.step create attribute 'discount' data-type texfield
 create another attribute 'appludiscount' data-type yes/no  default value yes

2.assign attribute in attribute set's price tab

3.add following code in catalog/product/view.phtml file just after
product name
   
    <?php $discount = $_product['discount']; ?>
        <?php if($discount !=""){?>
            <div class="product-discount">
            <?php echo $discount."% Discount"; ?>
            </div>
        <?php }?>

4.add following code in checkout/cart/item/default.phtml file after line no 41
<?php
$custom = Mage::getModel('catalog/product')->load($_item->getProductId());
$discount= $custom['discount']; ?>
<?php if($discount !=""){?>
<div class="discount"> <?php if($custom->getAttributeText('applydiscount') == "No")
{echo Flat." ".$discount." ". Discount; }
else
{
    echo $discount."% Discount";}?></div>
<?php }?>

5. now create observer file for it so create module
app/code/local/plumtree/Discount/model/observer.php file
<?php

class Plumtree_Discount_Model_Observer
{
   
    public function modifyPrice(Varien_Event_Observer $observer)
    {
       
       $item = $observer->getQuoteItem();
    if ($item->getParentItem()) {
        $item = $item->getParentItem();
        //echo "<pre>";
        //print_r($item->getData());exit;
    }

   
    $pid= $item->getProductId();
   $product = Mage::getModel('catalog/product')->load($pid);
   $productData  = $product->getData();
    $discount = $productData['discount'];
                   /* flat ammount Discount code starts here*/
    if( $product->getAttributeText('applydiscount') == "No"){
        $specialprice = $product->getFinalPrice();
        $new_price = $specialprice - $discount;
               if ($new_price > 0) {
        $item->setCustomPrice($new_price);
        $item->setOriginalCustomPrice($new_price);
        $item->getProduct()->setIsSuperMode(true);
            }
        }
       
         /* flat ammount Discount code ends here*/
       
          /* flat percent Discount code starts here*/
        else{
            $specialprice = $product->getFinalPrice();
            $new_price = ($specialprice*(100-$discount))/100;
                   if ($new_price > 0) {
         $item->setCustomPrice($new_price);
         $item->setOriginalCustomPrice($new_price);
         $item->getProduct()->setIsSuperMode(true);
              }
            }
           
             /* flat percent Discount code ends here*/
}
}

6.create app/code/local/plumtree/Discount/etc/config.xml

<?xml version="1.0"?>
<config>
    <modules>
        <Plumtree_Discount>
            <version>0.1.0</version>
        </Plumtree_Discount>
    </modules>
       <frontend>
         <events>
            <checkout_cart_product_add_after>
                <observers>
                   <Plumtree_Discount_Model_Observer>
                      <type>singleton</type>
                      <class>Plumtree_Discount_Model_Observer</class>
                      <method>modifyPrice</method>
                   </Plumtree_Discount_Model_Observer>
               </observers>
            </checkout_cart_product_add_after>
        </events>
      </frontend>
</config>
enjoy the code.

how to remove null data from additionali information table in product detail page in magento

By default if any value is not assigned to product data it retrive no in additionali information
check in chair dimension has no value

so go to \app\design\frontend\pro\weldingmart\template\catalog\product\view\attributes.phtml
add one if condition before <tr >starts like
  <?php if($_product[$_data['code']] != ""){?>
             <tr>
                <th class="label"><?php echo $this->htmlEscape($this->__($_data['label'])) ?></th>
                <td class="data"><?php echo $_helper->productAttribute($_product, $_data['value'], $_data['code']) ?></td>
            </tr>
            <?php }?>

Wednesday 19 June 2013

How to remove last name validation when create account in magento


1.Remove last name from:  app\design\frontend\default\default\template\persistent\checkout\onepage

\billing.phtml

2.now Comment validation from /mage/customer/model/customer.php
find function function validate() and comment below code
if (!Zend_Validate::is($this->getTelephone(), \\\’NotEmpty\\\’)) {
          $errors[] = Mage::helper(\\\’customer\\\’)->__(\\\’Please enter the telephone number.\\\’);
       }

same as above in file /mage/customer/model/Address/abstract.php file

3.now for Display only frst name in grid we have to modify mage/adminhtml/Block/customer/grid.php file find
$this->addColumn('name', array(
            'header'    => Mage::helper('customer')->__('Name'),
            'index'     => 'name'
        ));
 & replace it with below code
$this->addColumn('name', array(
            'header'    => Mage::helper('customer')->__('Name'),
            'index'     => 'firstname'
        ));

Tuesday 18 June 2013

view all product link in pager in category listing page in magento

add “View All” link in Magento’s pagination.in product list page you have two follw two steps only:

1. in page/html/pager.phtml file add
<a href="<?php echo $this->getLimitUrl('all')?>" title="<?php echo $this->__('View All Products') ?>">
<?php echo $this->__('View All') ?>
</a>

2 step app/code/local/mage/catalog/block/product/list/toolbar.php file

modify function _construct()

add below code after $this->setTemplate('catalog/product/list/toolbar.phtml'); line

$defaultLimit = $this->getDefaultPerPageValue();
Mage::getSingleton('catalog/session')->setData("limit_page",$defaultLimit);


enjoy Code.

Friday 14 June 2013

Add subcategory thumbnail image in topmenu in magento

link :http://source.9nit.com/magento/how-to-retrieve-the-parent-category-images-in-topmenu-in-magento-42154.html

step 1:
modified mage/catalog/model/observer.php file  modify  _addCategoriesToMenu function in modify
$categoryData = array( 
like
 $categoryData = array(
                'name' => $category->getName(),
            'id' => $nodeId,
            'url' => Mage::helper('catalog/category')->getCategoryUrl($category),
            'is_active' => $this->_isActiveMenuCategory($category),
            'links' => $category->getData('links'),
            'image' => $category->getImageUrl('image'),
            'thumbnail' =>Mage::getModel('catalog/category')->load($cat)->getThumbnail(),
            'getLevel' => $category->getLevel()
            );


also add $cat = $category->getId();  after $nodeId



step2:
modify Mage/page/block/html/topmenu.php  modified _getHtml function
add below code after $html .= '<a href="' . $child->getUrl() . '" ' . $outermostClassCode . '><span>'
                . $this->escapeHtml($child->getName()) . '</span></a>';

// new code starts here 

$parentLevels = $child->getLevel();
            if($parentLevels != 0)
              {
                //echo $child->getData('thumbnail');

                   $urls = Mage::getBaseUrl('media').'catalog/category/'.$child->getData('thumbnail');
                if(!file_exists("./media/catalog/category/resized"))    
                mkdir("./media/catalog/category/resized",0777);
                $imageName = substr(strrchr($urls,"/"),1);
                $imageResized = Mage::getBaseDir

('media').DS."catalog".DS."category".DS."resized".DS.$imageName;
                $dirImg = Mage::getBaseDir().str_replace("/",DS,strstr($urls,'/media'));
                if (!file_exists($imageResized)&&file_exists($dirImg)) :
                     $imageObj = new Varien_Image($dirImg);
                      $imageObj->constrainOnly(TRUE);
                      $imageObj->keepAspectRatio(FALSE);
                     $imageObj->keepFrame(TRUE);
                     $imageObj->resize(28,28);
                     $imageObj->save($imageResized);
               endif;

              $newImageUrl = Mage::getBaseUrl('media')."catalog/category/resized/".$imageName;

                     if($child->getData('thumbnail') !="")
                    {
                            $html .= '<img src="'.$newImageUrl.'"   />';
                     }
                }



Wednesday 5 June 2013

Import tier price through csv in magento

1. Create tierprice.csv in which there are Colums like  sku,price_General_2 (here genereal is customergroup
& 2 is qty),price_General_5,price_Wholesale_2  having value 
1112,200.99,425.99,150   

2.Create a custom module for import tierprice csv
create file in app/etc /modules     /Plumtree_Tierprice.xml  in it:
<?xml version="1.0"?>
<config>
    <modules>
        <Plumtree_Tierprice>
            <active>true</active>
            <codePool>local</codePool>
        </Plumtree_Tierprice>
    </modules>
</config>

3.Create modules Config.xml .App/code/local/Plumtree/Tierprice/etc/config.xml in it:
<?xml version="1.0"?>
<config>
  <modules>
        <Plumtree_Tierprice>
            <version>0.1.0</version>
        </Plumtree_Tierprice>
    </modules>
     <global>
        <models>
            <catalog>
                <rewrite>
                   

<convert_adapter_product>Plumtree_Tierprice_Catalog_Model_Convert_Adapter_Product</convert_adapter_product>
                </rewrite>
            </catalog>
        </models>
    </global>
</config>

4. now create model file in app/code/local/Plumtree/Tierprice/Catalog/Model/Convert/Adapter/Product.php    in

it:
<?php
class Plumtree_Tierprice_Catalog_Model_Convert_Adapter_Product extends

Mage_Catalog_Model_Convert_Adapter_Product
{
   
        private $_group_list = null;
        private $_tier_price_fields = null;
       
        public function load() {
           // load the group list
           $this->_group_list = Mage::getResourceModel('customer/group_collection')-

>setRealGroupsFilter()->loadData()->toOptionArray();
          
            // call the parent load
            return parent::load();
        }
       
    public function saveRow(array $importData)
    {
        // doing normal import...
        parent::saveRow($importData);
       
        if (!is_array($this->_group_list)) {
            $this->_group_list = Mage::getResourceModel('customer/group_collection')-

>setRealGroupsFilter()->loadData()->toOptionArray();
        }
       
        // is there a tier price field? (check this only the first time)
       
        if (!is_array($this->_tier_price_fields)) {
           
            $this->_tier_price_fields = array();
           
            foreach ($importData as $k=>$v) {
                $matches = array();
                if (preg_match('/^price\_([^_]+)\_?([0-9]+)?$/', $k, $matches)) {
                    // found a valid field. Check the group name and quantity
                   
                    $foundvalid = false;
                    foreach ($this->_group_list as $group) {
                        if (strtolower($group['label']) == strtolower($matches[1])) {
                            $foundvalid = true;
                            if (isset($matches[2])) $q = (int)$matches[2]; else $q = 1;
                            $this->_tier_price_fields[$k] = array('id_group'=>$group

['value'], 'quantity'=>$q);
                            break;
                        }
                    }
                   
                    if (!$foundvalid) {
                        // group not found!
                        // can't call exceptions here?
                        //$message = Mage::helper('catalog')->__('Customer group "%s" for

tier price not found', $matches[1]);
                          //    Mage::throwException($message,

Varien_Convert_Exception::NOTICE);
                    }
                   
                } /* end if */
            }
           
        }
       
        if (!count($this->_tier_price_fields)) return true; // no tier prices found
       
       
      // fetch the store object
      if (empty($importData['store'])) {
                if (!is_null($this->getBatchParams('store'))) {
                  $store = $this->getStoreById($this->getBatchParams('store'));
                } else {
                    // can't call exceptions here?
                  //$message = Mage::helper('catalog')->__('Skip import row, required field

"%s" not defined', 'store');
                  //Mage::throwException($message);
                }
            }    else {
                $store = $this->getStoreByCode($importData['store']);
            }
           
            // create the product object
      $product = $this->getProductModel()->reset();
      $product->setStoreId($store->getId());
      $productId = $product->getIdBySku($importData['sku']);
      $storeId = $store->getId();
     
            if ($productId) {
              $product->load($productId);
               
                $tierPrices = $product->tier_price;
               
                foreach ($this->_tier_price_fields as $tier_key=>$imported_tier_price) {
                    // should i update an existing tier price?
                    foreach ($tierPrices as $ktp=>$tp) {
                        if ($tp['website_id'] != $storeId) continue;
                        if ($tp['cust_group'] != $imported_tier_price['id_group'])

continue;
                        if ($tp['all_groups'] != 0) continue;
                        if ($tp['price_qty'] != $imported_tier_price['quantity'])

continue;
                       
                        // it matches this existing tier price. I remove it
                        unset($tierPrices[$ktp]);
                    }
                   
                    // now i add the imported tier_price
                    if ($importData[$tier_key]) {
                        $tierPrices[] = array(
                            'website_id'  => $storeId,
                            'cust_group'  => $imported_tier_price['id_group'],
                  'all_groups'  => 0,
                            'price_qty'   => number_format

($imported_tier_price['quantity'], 4, '.', ''),
                            'price'       => number_format($importData

[$tier_key], 4, '.','')
                        );
                    }
                   
                   
                }
               
                $product->tier_price = $tierPrices;
               
                // Save you product with all tier prices
                $product->save();
            }
       
        return true;
    }
}
  that's it. now Import csv through data flow Advanced profile.
                                                                                                                                                  

Tuesday 21 May 2013

Add wysiwyg editor in custom magento module.

Just Follw this simple 4 steps in your custom module.
step-1
Go to following path and open Edit.php
app\code\local\Namespace\Modulename\Block\Adminhtml\Modulename
and Add this Function
protected function _prepareLayout()
{
// Load Wysiwyg on demand and Prepare layout
if (Mage::getSingleton(‘cms/wysiwyg_config’)->isEnabled() && ($block = $this->getLayout()->getBlock(‘head’))) {
$block->setCanLoadTinyMce(true);
}
parent::_prepareLayout();
}

step-2
Go to following path and open Form.php
app\code\local\Namespace\Modulename\Block\Adminhtml\Modulename\Edit\Tab
and find function protected function _prepareForm()
and add
$form->setHtmlIdPrefix(‘modulename’);
$wysiwygConfig = Mage::getSingleton(‘cms/wysiwyg_config’)->getConfig(
array(‘tab_id’ => ‘form_section’)
);
And add field property
$wysiwygConfig["files_browser_window_url"] = Mage::getSingleton(‘adminhtml/url’)->getUrl(‘adminhtml/cms_wysiwyg_images/index’);
$wysiwygConfig["directives_url"] = Mage::getSingleton(‘adminhtml/url’)->getUrl(‘adminhtml/cms_wysiwyg/directive’);
$wysiwygConfig["directives_url_quoted"] = Mage::getSingleton(‘adminhtml/url’)->getUrl(‘adminhtml/cms_wysiwyg/directive’);
$wysiwygConfig["widget_window_url"] = Mage::getSingleton(‘adminhtml/url’)->getUrl(‘adminhtml/widget/index’);
$wysiwygConfig["files_browser_window_width"] = (int) Mage::getConfig()->getNode(‘adminhtml/cms/browser/window_width’);
$wysiwygConfig["files_browser_window_height"] = (int) Mage::getConfig()->getNode(‘adminhtml/cms/browser/window_height’);
$plugins = $wysiwygConfig->getData(“plugins”);
$plugins[0]["options"]["url"] = Mage::getSingleton(‘adminhtml/url’)->getUrl(‘adminhtml/system_variable/wysiwygPlugin’);
$plugins[0]["options"]["onclick"]["subject"] = “MagentovariablePlugin.loadChooser(‘”.Mage::getSingleton(‘adminhtml/url’)->getUrl(‘adminhtml/system_variable/wysiwygPlugin’).”‘, ‘{{html_id}}’);”;
$plugins = $wysiwygConfig->setData(“plugins”,$plugins);
$fieldset->addField(‘fieldname’, ‘editor’, array(
‘name’ => ‘fieldname’,
‘label’ => Mage::helper(‘modulename’)->__(‘Content’),
‘title’ => Mage::helper(‘modulename’)->__(‘Content’),
‘style’ => ‘width:700px; height:300px;’,
‘wysiwyg’ => true,
‘required’ => false,
‘state’ => ‘html’,
‘config’ => $wysiwygConfig,
));

step-3
Go to following path and open modulename.xml if its not available than create id
app\design\adminhtml\default\default\layout
and add
<?xml version=”1.0″?>
<layout>
<modulename_adminhtml_controllername_index>
<reference name=”content”>
<block type=”modulename/adminhtml_blockname” name=”blockname” />
</reference>
</modulename_adminhtml_controllername_index>
<modulename_adminhtml_controllername_edit>
<update handle=”editor”/>
</modulename_adminhtml_controllername_edit>
</layout>

step-4
if you want to Display editor's content in front side use below code .

$_cmsHelper = Mage::helper(‘cms’);
$_process = $_cmsHelper->getBlockTemplateProcessor();
echo $_process->filter($item['content']);

Magento : Login/Logout Code in Header

<?php if (! Mage::getSingleton('customer/session')->isLoggedIn()): ?>

<a href="<?php echo Mage::helper('customer')->getLoginUrl(); ?>"><?php echo $this->__('Login') ?></a>

<?php else: ?>

<a href="<?php echo Mage::helper('customer')->getLogoutUrl(); ?>"><?php echo $this->__('Logout') ?></a>

<?php endif; ?>

Tuesday 14 May 2013

Magento Forms: Prototype Javascript Validation In Custom Module

If you want to use magento's default validatin inyour custom module it may helps you.

Adding Javascript validation to your own forms is extremely simple. First, you need to create a Form (form.js) object to represent your form.
<script type="text/javascript">
//< ![CDATA[
  var myForm= new VarienForm('formId', true);
//]]>
</script>
 
example how to add validation in custom module through class name is as below:
<label for="name">Name *</label>
<input type="text" id="name" name="name" value="" class="required-entry"/>
<label for="email">Email Address *</label>
<input type="text" id="email" name="email"  class="required-entry validate-email"/>
 
Here are the few magento javascript validation classes as below:

validate-select   - Please select an option

required-entry   - This is a required field

validate-number  - Please enter a valid number in this field

validate-digits   - Please use numbers only in this field. please avoid spaces or other characters such as dots or commas

validate-alpha  - Please use letters only (a-z or A-Z) in this field.

validate-code  - Please use only letters (a-z), numbers (0-9) or underscore(_) in this field, first character should be a letter.

validate-alphanum  - Please use only letters (a-z or A-Z) or numbers (0-9) only in this field. No spaces or other characters are allowed

validate-street  - Please use only letters (a-z or A-Z) or numbers (0-9) or spaces and # only in this field

validate-phoneStrict  - Please enter a valid phone number. For example (123) 456-7890 or 123-456-7890

validate-phoneLax  - Please enter a valid phone number. For example (123) 456-7890 or 123-456-7890

validate-fax  - Please enter a valid fax number. For example (123) 456-7890 or 123-456-7890

validate-date - Please enter a valid date

validate-email  - Please enter a valid email address. For example johndoe@domain.com.

validate-emailSender  - Please use only letters (a-z or A-Z), numbers (0-9) , underscore(_) or spaces in this field.

validate-password  - Please enter 6 or more characters. Leading or trailing spaces will be ignored

validate-admin-password  - Please enter 7 or more characters. Password should contain both numeric and alphabetic characters

validate-cpassword  - Please make sure your passwords match

validate-url  - Please enter a valid URL. http:// is required

validate-clean-url  - Please enter a valid URL. For example http://www.example.com or www.example.com

validate-identifier  - Please enter a valid Identifier. For example example-page, example-page.html or anotherlevel/example-page

validate-xml-identifier  - Please enter a valid XML-identifier. For example something_1, block5, id-4

validate-ssn  - Please enter a valid social security number. For example 123-45-6789

validate-zip - Please enter a valid zip code. For example 90602 or 90602-1234


Monday 13 May 2013

Get the current category/product/cms page in Magento


<?php
$currentCategory = Mage::registry('current_category');
$currentProduct = Mage::registry('current_product');
$currentCmsPage = Mage::registry('cms_page');
?>

Get Product Collection by Product Type in Magento


$collectionSimple = Mage::getResourceModel('catalog/product_collection')
    ->addAttributeToFilter('type_id', array('eq' => 'simple'));

$collectionConfigurable = Mage::getResourceModel('catalog/product_collection')
    ->addAttributeToFilter('type_id', array('eq' => 'configurable'));

$collectionBundle = Mage::getResourceModel('catalog/product_collection')
    ->addAttributeToFilter('type_id', array('eq' => 'bundle'));

$collectionGrouped = Mage::getResourceModel('catalog/product_collection')
    ->addAttributeToFilter('type_id', array('eq' => 'grouped'));

$collectionVirtual = Mage::getResourceModel('catalog/product_collection')
    ->addAttributeToFilter('type_id', array('eq' => 'virtual'));

Join custom table to product collection in magento


$collection = Mage::getModel('module/model_name')->getCollection();
$collection->getSelect()->join( array('table_alias'=>$this->getTable('module/table_name')), 'main_table.foreign_id = table_alias.primary_key', array('table_alias.*'), 'schema_name_if_different');


For Example,


$collection = Mage::getResourceModel('catalog/product_collection')
                ->addAttributeToSelect('name')
                ->addAttributeToSelect('sku')
                ->addAttributeToSelect('price')
                ->addAttributeToSelect('status')
                ->addAttributeToSelect('visibility')
                ->addAttributeToFilter('type_id', array('eq' => 'simple'))
                ->addFieldToFilter('status', Mage_Catalog_Model_Product_Status::STATUS_ENABLED)
                ->addAttributeToFilter('visibility', array('neq' => 1));

Add tracking no in shipment in magento through script

1.create a csv file . In it put following fields OrderNumber,Email,TrackingNumber,Carrier . & csv's name is orders_tracking_import.csv
2 Create ordertracking.php file in your magento's root directory

<?php
    require_once("app/Mage.php");
    Mage::app();
 
    if (isset($_POST['MAX_FILE_SIZE'])) {

        $email = true;
 
        $target_path = basename( $_FILES['uploadedfile']['name']);
        $_FILES['uploadedfile']['tmp_name'];
        $target_path = basename( $_FILES['uploadedfile']['name']);
         
        if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
?>

The file <?php echo basename( $_FILES['uploadedfile']['name']); ?> has been uploaded succesfully!


<?php  
            ini_set("auto_detect_line_endings", 1);
            $current_row = 1;
            $handle = fopen($target_path, "r");
            $csvData = array();
         
            while ( ($data = fgetcsv($handle, 10000, ",") ) !== FALSE )
            {
                $number_of_fields = count($data);
//print_r($number_of_fields);exit;
                if ($current_row == 1) {    //Header line
                    for ($c=0; $c < $number_of_fields; $c++)
                    {
                        $header_array[$c] = $data[$c];
                    }
                } else {    //Data line
                    for ($c=0; $c < $number_of_fields; $c++)
                    {
                        $data_array[$header_array[$c]] = $data[$c];
                    }
                    $csvData[] = $data_array;
                }
                $current_row++;
            }
           
            fclose($handle);
         
            foreach($csvData as $rec) {
                                             
                $includeComment = false;
                $comment = NULL;
               
                $order = Mage::getModel('sales/order')->loadByIncrementId($rec['OrderNumber']);
               
                //This converts the order to "Completed".


   if ($order->canShip())
 {

                    $convertor = Mage::getModel('sales/convert_order');
                    $shipment = $convertor->toShipment($order);
                    $shipment->setIncrementId($orderId);
                   
                    foreach ($order->getAllItems() as $orderItem) {
                   
                        if (!$orderItem->getQtyToShip()) {
                            continue;
                        }
                        if ($orderItem->getIsVirtual()) {
                            continue;
                        }
                   
                        $item = $convertor->itemToShipmentItem($orderItem);
                   
                        $qty = $orderItem->getQtyToShip();
                   
                        $item->setQty($qty);
                        $shipment->addItem($item);
                    }
                   
                 } else {
               
                    foreach ($order->getShipmentsCollection() as $shipment) {
                        $shipmentId = $shipment->getIncrementId();
                    }
                        $shipment = Mage::getModel('sales/order_shipment')->loadByIncrementId($shipmentId);
                }
             
                $carrierTitle = NULL;
               
                // FOR GUIDANCE ON THIS SECTION LOOK AT MY FIRST POST... IT HAS BETTER COMMENTS
               
                if ($rec['Carrier'] == 'ups') {
                    $carrierTitle = 'United Parcel Service';
                }
                if ($rec['Carrier'] == 'dhl') {
                    $carrierTitle = 'DHL (Deprecaied)';
                }
                if ($rec['Carrier'] == 'fedex') {
                    $carrierTitle = 'Federal Express';
                }
if ($rec['Carrier'] == 'dhlint') {
                    $carrierTitle = 'DHL';
                }
                if ($rec['Carrier'] == 'usps') {
                    $carrierTitle = 'United States Postal Service';
                }
                if ($rec['Carrier'] == 'custom') {
                    $carrierTitle = 'Custom Value';
                }
               
                $data = array();
                $data['carrier_code'] = $rec['Carrier'];
                $data['title'] = $carrierTitle;
                $data['number'] = $rec['TrackingNumber'];
               
                $track =Mage::getModel('sales/order_shipment_track')->addData($data);

                $shipment->addTrack($track);
             
               
    if ($order->canShip()){
                    $shipment->register();
                    $shipment->addComment($comment, $email && $includeComment);
                    $shipment->setEmailSent(true);
                    $shipment->getOrder()->setIsInProcess(true);
                   
                    $transactionSave = Mage::getModel('core/resource_transaction')
                        ->addObject($shipment)
                        ->addObject($shipment->getOrder())
                        ->save();
                   
                    $shipment->sendEmail($rec['Email'], ($includeComment ? $comment : ''));
                   
                    $shipment->save();
                }
   else {
                    $track->save();
                    $shipment->sendEmail($rec['Email'], ($includeComment ? $comment : ''));
                    $order->setStatus('complete');
                    $order->addStatusToHistory('complete', '', false);
                    $order->save();
                }    
                                 

            }
         
        } //end if statment for file upload check
       
    } else { // end if statement for post check for upload

?>

<form enctype="multipart/form-data" action="" method="POST">
  <p>
    <input type="hidden" name="MAX_FILE_SIZE" value="1000000000" />
    CSV File:
    <input name="uploadedfile" type="file" />
  </p>
  <p>
    <input type="submit" name="upload" id="upload" value="Submit" />
  </p>
</form>


<?php
   
    }

?>