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