Friday, April 1, 2016

Magento get country code for logged in user Using mageworx geoip location

steps:

1. Install the Mageworx geoip location extension

http://www.mageworx.com/geoip-location-magento-extension.html

2.  Use the below code where you want to have the country code of the logged in user:


$rec = Mage::getModel('mageworx_geoip/geoip')->getLocation();

return $locData =$rec->getCode(); //this will return the country code for e.g. IN for India.

Note:: you can use  $rec->getData(); to get all the below information:
IP, CODE ,COUNTRY ,FLAG

Tuesday, March 22, 2016

Add option to customer attribute programmatically In Magento

To programmatically Add option to customer attribute , Add the function given in the reference url to your controller or block:

http://blog.onlinebizsoft.com/magento-programmatically-insert-new-attribute-option/

And replace the below code

 $attribute_code         = $attribute_model->getIdByCode('catalog_product', $arg_attribute);
  

To

 $attribute_code         = $attribute_model->getIdByCode('customer', $arg_attribute);
  

Monday, March 21, 2016

Magento Change Pager Phtml Custom Module



In you block of custom module, for e.g.In my case,  Netgo_Userstatus_Block_Userstatus_List

Just Use the blow code in _prepareLayout() function

  protected function _prepareLayout()
{
        parent::_prepareLayout();
        $pager = $this->getLayout()->createBlock(
            'page/html_pager',
            'netgo_userstatus.userstatus.html.pager'
        )->setTemplate('page/html/newsfeed_pager.phtml')
        ->setCollection($this->getUserstatuss());
        $this->setChild('pager', $pager);
        $this->getUserstatuss()->load();
        return $this;
    }

The Red colored is the extra code that I have added, you can define your phtml file for the pager.

Friday, February 19, 2016

Magento admin change default page size of grid

You have to modify two files for that: Grid.php and Grid.phtml,
Below are the details of files:

In Admin Block File:
/public_html/app/code/core/Mage/Adminhtml/Block/Widget
Grid.php

Search for $_defaultLimit in the file and change the value according to your choice.
protected $_defaultLimit    = 75;

PHTML File:
app/design/adminhtml/default/default/template/widget
grid.phtml

Add your option in the select box.

<select name="<?php echo $this->getVarNameLimit() ?>" onchange="<?php echo $this->getJsObjectName() ?>.loadByElement(this)">
<option value="20"<?php if($this->getCollection()->getPageSize()==20): ?> selected="selected"<?php endif; ?>>20</option>
<option value="30"<?php if($this->getCollection()->getPageSize()==30): ?> selected="selected"<?php endif; ?>>30</option>
<option value="50"<?php if($this->getCollection()->getPageSize()==50): ?> selected="selected"<?php endif; ?>>50</option>
<option value="75"<?php if($this->getCollection()->getPageSize()==75): ?> selected="selected"<?php endif; ?>>75</option>
<option value="100"<?php if($this->getCollection()->getPageSize()==100): ?> selected="selected"<?php endif; ?>>100</option>
<option value="200"<?php if($this->getCollection()->getPageSize()==200): ?> selected="selected"<?php endif; ?>>200</option>
</select>

I have added 75 as additional page size, It will be default pagesize too.

Monday, October 26, 2015

PHP Remove special (non printable) characters from text

 

$mystring = " Fund BDM̢۪s were then able to engage with 19 employers, most of whom were subsequently converted to the MTAA Super Clearinghouse.
";
preg_replace("/[^\x0A\x20-\x7E]/",'', $mystring);

echo $mystring;

//The above code will result in

Fund BDMs were then able to engage with 19 employers, most of whom were subsequently converted to the MTAA Super Clearinghouse..
        

Wednesday, October 21, 2015

DISPLAY OUT OF STOCK PRODUCTS ACCORDING TO ADMIN INVENTORY SETTING

 

$isOutOfStockAllowed = Mage::getStoreConfig('cataloginventory/options/show_out_of_stock');
 
  foreach($_productCollection as $_product)
       {
        if(!$isOutOfStockAllowed){
         if(!$_product->isSaleable()){
          continue;
         }
         
        }
        //PRODUCT DISPLAY CODE HERE
        
        }
        

Saturday, October 17, 2015

Facebook page feed time issue

I was implementing facebook page feed for one of my client, the feeds were appearing correct but time was different, actually it was a timezone issue, you have to convert facebook time to local timezone, and to do this i found the perfect way.

step1.
Download and include the js file into your script.

https://gist.github.com/aredo/4153245

step2:

use below code to determine the client timezone:

<script type="text/javascript">
    jQuery(document).ready(function() {
       var timezone = jstz.determine();
var timezonename = timezone.name();  
    });
</script>

Saturday, December 20, 2014

Magento Flat category , show category tree

Below code displays dropdown of categories and subcategories upto n level.


<!----NEW CODE---->

<select id="category-changer"  name="cat" style="width:150px;">
<option value="6"> All Categories </option>
<?php echo $catlistHtml; ?>  
</select>
<?php
function str_prefix($str, $n=1, $char=" "){
    for ($x=0;$x<$n;$x++){ $str = $char . $str; }
    return $str;
}
function getTreeCategories($parentId, $isChild){
    $_cathelper = Mage::helper('catalog/category');
$allCats = Mage::getModel('catalog/category')->getCollection()
                ->addAttributeToSelect('*')
                ->addAttributeToFilter('is_active','1')
                ->addAttributeToFilter('parent_id',array('eq' => $parentId));
    $class = ($isChild) ? "sub-cat-list" : "cat-list";
    //$children = Mage::getModel('catalog/category')->getCategories(7);
    foreach ($allCats as $category)
    {
   $prefix = '';
   $_category =  Mage::getModel('catalog/category')->load($category->getId());
   $lblval=$_category->getLevel()-3;
$catname = ($lblval==0)?strtoupper($_category->getName()):$_category->getName();
$catname =  str_prefix($catname,$lblval*2,"-");
        $html .= '<option lbl="'.$_category->getLevel().'" value="'.$_category->getId().'" caturl="'.$_cathelper->getCategoryUrl($_category).'" >'.$catname."</option>";
        $subcats = $category->getChildren();
        if($subcats != ''){
            $html .= getTreeCategories($category->getId(), true);
        }
    }
    return $html;
}
$catlistHtml = getTreeCategories(6, false);
?>

<!--NEW CODE ENDS--> 

Monday, August 12, 2013

Magento add datepicker to frontend

Code referece:

http://stackoverflow.com/questions/8335456/magento-how-do-i-add-a-frontend-date-picker-that-returns-dd-mm-yy-instead-of-m


STEPS:
1. Add js and css necessary for the datepicker in frontend
<reference name="head">
        <action method="addItem"><type>js_css</type><name>calendar/calendar-win2k-1.css</name><params/><!--<if/><condition>can_load_calendar_js</condition>--></action>
        <action method="addItem"><type>js</type><name>calendar/calendar.js</name><!--<params/><if/><condition>can_load_calendar_js</condition>--></action>
        <action method="addItem"><type>js</type><name>calendar/calendar-setup.js</name><!--<params/><if/><condition>can_load_calendar_js</condition>--></action>
</reference>
 
2.
 <block type="core/html_calendar" name="html_calendar" as="html_calendar" template="page/js/calendar.phtml"/> 

3.call that block in the phtml file where u want to implement datepicker.
<?php echo $this->getChildHtml('html_calendar') ?>
 
4. Last use the below code:
 
<script type="text/javascript">
  Calendar.setup({
  inputField : 'deliverydate',
  ifFormat : '%m/%e/%y',
  button : 'date_from_trig',
  align : 'Bl',
  singleClick : true
  });
</script> 

Tuesday, June 18, 2013

Magento signin signout links on any phtml file

 <ul class="links si_ac">
            <?php
            $signout =$baseurl.'customer/account/logout';
            if(!Mage::getSingleton('customer/session')->isLoggedIn()) {
            $signinUrl =$baseurl.'customer/account/login';
            $signup   =$baseurl.'customer/account/create';
             $linkks = "<li><a href='$signinUrl'>".$this->__("Sign In")."</a></li>
                <li class='last'><a  href='$signup'>".$this->__("Create an Account")."</a></li>";
            }else{
              $linkks = "<li class='last'><a  href='$signout'>".$this->__("Sign Out")."</a></li>";
            }
            echo $linkks;
            ?> 
         </ul>

Friday, May 17, 2013

magento display multi select attribute in admin grid with filter



I have created a custom module by name supplier , and displayed several supplier on the product page in admin like in the image above, Now the multiselected values were not appearing properly in the grid page.

It was appearing empty for multiselected values. although i managed to display single selected values properly by the post:

http://blog.chapagain.com.np/magento-how-to-search-or-filter-by-multiselect-attribute-in-admin-grid/

But still there was problem with multi selected values, so i defined "renderer"
$this->addColumn('supplier', array(
            'header'    => Mage::helper('catalog')->__('supplier'),
            'width'     => '180px',
            'index'     => 'supplier',
            'type'  => 'options',
            'options' => $item_types,
             'filter_condition_callback' => array($this, '_filterSupplierCallback'),
            'renderer'=>new Mage_Adminhtml_Block_Catalog_Product_Columns_Supplier()        ));

IN THE RENDERER I USED BELOW CODE TO RETURN THE LIST OF MULTI SELECTED SUPPLIER:

public function render(Varien_Object $row)
    {
        $suppliers=explode(',',$row->getSupplier());
        $suppstr="";
        if(count($suppliers)>0)
        {
            $suppstr="<ul>";
            foreach($suppliers as $value)
            {
                $productModel = Mage::getModel('catalog/product');
                $attr = $productModel->getResource()->getAttribute("supplier");
                if ($attr->usesSource()) {
                $suppstr   .= "<li>".$attr->getSource()->getOptionText("$value")."</li>";
                }

            }
            $suppstr   .= "</ul>";
  
        }
          return $suppstr;   
       
    }



And successfully displayed multiselected options in the grid.

Monday, April 29, 2013

magento add custom validation to admin section field

well... i had to create my own custom validation class for my magento extension because the client said that.
'For Video title- it should accept alphabets[A-Za-z], numerics and also special charater "Space" , and also it should not start with number'.
since changing core file is a bad habit , so i created  my own js file and add my custom validation class.But first let me tell u how u can do it fast by modifying core file.
//BAD BUT FAST WAY...
open  js/prototype/validation.js

some where at line 479-771, u will see lots of validation classess that magento uses. U can define your own validation class like i did.

I added below code after line 489.

  ['validate-alphanum-with-spaces-char-first', 'Please use only letters (a-z or A-Z), numbers (0-9) or spaces only in this field, first character should be a letter.', function(v) {
                return Validation.get('IsEmpty').test(v) ||  /^[a-z]+[a-z0-9 ]+$/.test(v)
            }],


 //NOW THE STANDARD WAY....
1. add your custom js file to the module.
     in my case it was video edit section in admin:

 app/design/adminhtml/default/default/layout/mymod_video.xml
<layout>
<adminhtml_video_video_edit>
     <reference name="head">
                    <action method="addJs"><script>alfasoft/videoext/myvalidation.js</script></action>
        </reference>

        <reference name="content">
          ....
        </reference>
        <reference name="left">
          ....
        </reference>
    </adminhtml_video_video_edit>

</layout>

2. upload your js i.e. myvalidation.js to the location js/alfasoft/videoext/

3. Add your code to myvalidation.js
   if(Validation)
    {
        Validation.addAllThese([
           
            ['validate-alphanum-with-spaces-char-first', 'Please use only letters (a-z or A-Z), numbers (0-9) or spaces only in this field, first character should be a letter.', function(v) {
                return Validation.get('IsEmpty').test(v) ||  /^[a-z]+[a-z0-9 ]+$/.test(v)
            }]     // this is my validation requirement, your could be anything else.


        ]);
    }

Now Let me explain the code. according to my requirement.

>the regular expression fit the best /^[a-z]+[a-z0-9 ]+$/.test(v) . your could be anything else.
>here my validation class name is  'validate-alphanum-with-spaces-char-first'. 
>And my error message is:
'Please use only letters (a-z or A-Z), numbers (0-9) or spaces only in this field, first character should be a letter.'

 Use your class in the form:
mine path was:
app/code/community/Alfasft/Video/Block/Adminhtml/Video/Edit/Tab/Form.php

$fieldset->addField('vtitle', 'text', array(
            'label' => Mage::helper('video')->__('Video Title'),
            'name'  => 'vtitle',
            'required'  => true,
            'class' => 'required-entry validate-alphanum-with-spaces-char-first',

        ));


 //I have assign this class to the field 'vtitle'.





Friday, April 26, 2013

magento validation alpha numeric with spaces

Magento has a class , use this for  this validation

validate-alphanum-with-spaces

Monday, April 8, 2013

magento admin redirect to same url after post

 Put the below code at the end of the action:

$this->_redirectReferer($this->getRequest()->getServer('HTTP_REFERER'));
        return;

Sunday, February 10, 2013

GET QUOTE ITEMS PRODUCT COUNT BY ATTRIBUTE


This code is for counting the total number to products in the cart having specific attribute code.

$items =Mage::getModel('checkout/cart')->getQuote()->getAllItems();
  $attriubtecnt=0;
 
   foreach($items as $item)
    {
$_product = Mage::getModel('catalog/product')->load($item->getProductId());
$att_value= $_product->getAttributeText('attributecode');

if(trim($att_value)=='lining')
{
                      $liningcnt +=$item->getTotalQty();
                 }

}

Wednesday, November 21, 2012

MAGENTO CHANGE CAPTCHA BACKGROUND LINES AND DOTS DENSITY

I had to reduce the density of dots and lines in captcha because it was un readable sometimes.

so here what i did.

Go to:

lib/Zend/Captcha/Image.php

protected $_dotNoiseLevel = 10;
protected $_lineNoiseLevel = 0;



magento:IP SPECIFIC LANGUAGE

 First download currency switcher from   
 http://www.magentocommerce.com/magento-connect/auto-currency-switcher-8671.html  
 //CODE TO DISPLAY LANGUAGE ACCORDING TO IP ADDRESS  
  if(Mage::getConfig()->getModuleConfig('Chapagain_AutoCurrency')->is('active', 'true'))  
  {   
                $geoIp = Mage::helper('autocurrency')->loadGeoIp();  
                $ipAddress = Mage::helper('autocurrency')->getIpAddress();  
                // get country code from ip address  
                 $countryCode = geoip_country_code_by_addr($geoIp, $ipAddress);   
                 $germancountries=array('CH','DE');  
                if(!isset($_COOKIE['frontstoreloc']))   
                {   
                 //$siteurl= $this->getUrl();  
                 $siteurl= "http://".$_SERVER['SERVER_NAME'];  
                      setcookie("frontstoreloc",session_id(),time()+60*60*24,"/","");  
                     switch(trim($countryCode))  
                     {  
                           case 'CH':  
                                    $url = $siteurl . '?___store=german';  
                                    header( 'Location:' . $url);die;  
                           break;  
                           case 'DE':  
                                         $url = $siteurl . '?___store=german';  
                                         header( 'Location:' . $url);die;  
                           break;  
                           case 'IN':  
                                     $url = $siteurl . '?___store=english';  
                                     header( 'Location:' . $url);die;  
                           break;  
                           default:  
                           $url = $siteurl . '?___store=usa';  
                                     header( 'Location:' . $url);die;  
                           break;  
                     }  
                 }  
            }  

MAGENTO GET STORE SPECIFIC ATTRIBUTE LABEL:

 <?php echo $_product->getResource()->getAttribute($_attribute->getAttributeId())->getStoreLabel();?>  

Magento error :Mage registry key "_singleton/core/resource" already exists

Magento invoice pdf : display custom options in one line



open default.php
at path:

app/code/local/Mage/Sales/Model/Order/Pdf/Items/Invoice

//REPLACE THE LINES  one that starts with if ($options) {
        //foreach ($options as $option) { with the followin lines.

       
       $options = $this->getItemOptions();
    if ($options) {
        foreach ($options as $option) {
            if ($option['value']) {
                $_printValue = isset($option['print_value']) ? $option['print_value'] : strip_tags($option['value']);
                $values = explode(', ', $_printValue);
                foreach ($values as $value) {
                    $optlabel= Mage::helper('core/string')->str_split(strip_tags($option['label']), 70, true, true);
                    $optval = Mage::helper('core/string')->str_split($value, 50, true, true);
                    $lines[][] = array(
                        'text' => htmlspecialchars_decode ($optlabel[0]." : ".$optval[0]),
                        'feed' =>35
                    );
                }
            }
        }
    }