Tuesday, April 1, 2014

javascript classes - simulated using functions

Good resource for  Learn JavaScript Design Patterns
http://addyosmani.com/resources/essentialjsdesignpatterns/book/#detailmvc

Hello World Example for javascript classes - simulated using functions

Script
----------

<h2>Hello  javascript classes - simulated using functions</h2>
<script type="text/javascript">
    // A car "class"
    function Car( model ) {

        this.model = model;
        this.color = "red";
        this.year  = "2014";

        this.getInfo = function () {
            return this.model + " " + this.year;
        };

    }

    var myCar = new Car("toyota");

    myCar.year = "1999";

    console.log( myCar.getInfo() );


</script>


Sunday, May 5, 2013

Magento Module - Remove specific field from Catalog Filter

One of the common modification that most of client required was remove some fields from Magento catalog filter. Standard way for impalement above requirement Create new module and rewrite Catalog Layer View block. Hope following module will help you

app\code\local\kbtdeveloper\PriceFilterRemove\etc\config.xml


<?xml version="1.0" encoding="UTF-8"?>
<config>
    <global>
        <blocks>
            <catalog>
                <rewrite>
                    <layer_view>kbtdeveloper_PriceFilterRemove_Block_View</layer_view>
                </rewrite>
            </catalog>
        </blocks>
    </global>
</config>


\app\code\local\kbtdeveloper\PriceFilterRemove\Block\View.php



<?php

class kbtdeveloper_PriceFilterRemove_Block_View extends Mage_Catalog_Block_Layer_View {

    public function getFilters() {
        $filters = array();
        if ($categoryFilter = $this->_getCategoryFilter()) {
            $filters[] = $categoryFilter;
        }

        $filterableAttributes = $this->_getFilterableAttributes();
        foreach ($filterableAttributes as $attribute) {
        /**
        *Remove Price on Refine by block , store wise
        */
            if (Mage::app()->getStore()->getCode() == 'default') {
                if ($attribute->getAttributeCode() == 'price') {
                    continue;
                }
            }
            $filters[] = $this->getChild($attribute->getAttributeCode() . '_filter');
        }

        return $filters;
    }

}

Magento - Display Specific Massage when free shipping available

One of the easiest way for display specific message , when free shipping available is create static block and display it.

Create new static block
CMS -> Static Block -> Add new.

then edit relevant template file "\app\design\frontend\PACKAGE-NAME\THEAME-NAME\template\checkout\onepage\shipping_method\available.phtml"

on top of that file update as follow


    <?php
// Remove any other shipping methods if free shipping is available
    $isFreeShippingAllow = false;
if ( array_key_exists('freeshipping', $_shippingRateGroups )) {
    $_shippingRateGroups = array('freeshipping' => $_shippingRateGroups['freeshipping']);
    $isFreeShippingAllow = true;
}
?>

Finally Call predefined static block when free shipping available



<?php
    if($isFreeShippingAllow){
      echo $this->getLayout()->createBlock('cms/block')->setBlockId('Solar_Free_Shipping_Msg')->toHtml();
   }
    ?>


;) one of the simple trick  :)





Monday, February 11, 2013

Magento Extension - Set Payment Method Enable Threshold Amount


Magento Custom Extension that can Set threshold amount for only display payment option if carts that were over the threshold amount.

In Magento admin there is field(System->Configuration->Sales->Payment Methos Allow Threshold Amount) that Store Owner can set threshold amount and payment method code that want to implement restriction.


http://www.magentocommerce.com/magento-connect/catalog/product/view/id/16539/

Saturday, November 3, 2012

Magento Extention API for Bundle Products

Recently when i working Magento data migration team, some sort of reason we use magento SOAP API for migrate products details. one of the major issue that we face was migrate Bundle product via soap API. At the moment magento core API doesn't support create bundle product via API.

 There for i decided to create Custom extension for Create Bundle product via soap API. After spend few hours on web found the possible way to implement it. hope this will help any one who want create Bundle product in Magento via SOAP API.

Extension Files

/www/magento/app/etc/Company_Bundleapi.xml
/www/magento/app/code/local/Company/Bundleapi/Model/Objectmodel/Api.php
/www/magento/app/code/local/Company/Bundleapi/etc/api.xml
/www/magento/app/code/local/Company/Bundleapi/etc/config.xml

Source Code

/www/magento/app/etc/Company_Bundleapi.xml

<?xml version="1.0"?>
<config>
    <modules>
        <Company_Bundleapi>
            <active>true</active>
            <codePool>local</codePool>
        </Company_Bundleapi>
    </modules>
</config>

 

/www/magento/app/code/local/Company/Bundleapi/etc/api.xml

<?xml version="1.0"?>
<config>
    <api>
        <resources>
            <bundle_link translate="title" module="company_bundleapi">
            <title>Title Of Bundle link</title>
            <model>bundleapi/objectmodel_api</model>
            <methods>
                <createlink translate="title" module="company_bundleapi">
                    <title>Title Of Create link method</title>
                </createlink>
            </methods>
            </bundle_link>
        </resources>
    </api>
</config>




 /www/magento/app/code/local/Company/Bundleapi/etc/config.xml 

<?xml version="1.0" encoding="UTF-8"?>
<config>
    <modules>
        <Company_Bundleapi>
            <version>0.1.0</version>
        </Company_Bundleapi>
    </modules>
    <global>
        <models>
            <bundleapi>
                <class>Company_Bundleapi_Model</class>
            </bundleapi>
        </models>
    </global>
</config>

 

/www/magento/app/code/local/Company/Bundleapi/Model/Objectmodel/Api.php

<?php
class Company_Bundleapi_Model_ObjectModel_Api extends Mage_Api_Model_Resource_Abstract
{

 public function createlink($pitems,$pselectionRawData, $pproductId, $storeid)
    {
        $selections = array();
          
            $selections = $pselectionRawData;

            $productId = $pproductId;
            $product    = Mage::getModel('catalog/product')->setStoreId($storeid);
           
            if ($productId) {
                $product->load($productId);
            }
            Mage::register('product', $product);
            Mage::register('current_product', $product);
            $product->setCanSaveConfigurableAttributes(false);
            $product->setCanSaveCustomOptions(true);

            $product->setBundleOptionsData($pitems);
            $product->setBundleSelectionsData($selections);
            $product->setCanSaveCustomOptions(true);
            $product->setCanSaveBundleSelections(true);

            $product->save();
            return $product->getName();
    }

}
?>





Usage

 
$items[] = array(
                            'title' => 'Bundle Option',
                            'option_id' => '',
                            'delete' => '',
                            'type' => 'radio',
                            'required' => 1,
                            'position' => 0);

                        $selectionRawData[$i][0] = array(
                            'selection_id' => '',
                            'option_id' => '',
                            'product_id' => $magento_pr_id,
                            'delete' => '',
                            'selection_price_value' => 0,
                            'selection_price_type' => 0,
                            'selection_qty' => 1,
                            'is_default' => 1,
                            'selection_can_change_qty' => 0,
                            'position' => 0);

$resultretun = $proxy->call($sessionId, 'bundle_link.createlink', array($items, $selectionRawData, $productId, $storeid));
          
                   


Tuesday, May 15, 2012

Smarty php add multiple forms into single page and submit via javascript

Smarty is a web template system. It facilitates a manageable way to separate application logic and content from its presentation. Few times ago i have work with smarty web application. When i work on this i face few problem. One of the major one is when i try to add multiple HTML forms into same web page and then submit on one form, other form also try to submit. i think there are few possible way to slove above problem. i just go though the following way.

multipleforms.html


<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>External Seller | Control Panel</title>
</head>
<script language="JavaScript" type="text/javascript">
{literal}
function submitform(){
   document.form1.submit();
}

function submitform2(){
   document.form2.submit();
}
{/literal}
</script>
<body>
<form action="form1.php" name ="form1" id="form1" method="post">
    <input name="txt1" type="text"  id="txt1" value="{$server_obj->getValue()}"  size="50" />
    <input type="button" onclick="javascript: submitform()" id="submit1" value="Update First" class="button" />
</form>

    <br>
   
<form action="form2.php" name ="form2" id="form2" method="post">
    <input name="txt2" type="text"  id="txt2" value="{$server_obj2->getValue2()}"  size="50" />
    <input type="button" onclick="javascript: submitform2()" id="submit2" value="Update Second" class="button" />
</form>      
</body>
</html>

In the above example, i have use normal button instead of using submit button. On the button onclick event i have call JavaScript and submit form via that JavaScript. very Simple ;)

Wednesday, May 9, 2012

eKomi Frontend Integration

This Post show eKomi Fronted Integration with zend application.
In this example i have create ItemreviewServise file for connect eKomi API get reviews and store those reviews on local database. For performance reasons eKomi recommend to store the reviews in local database.

class Itemreview_Service_ItemreviewService  extends Base_Model_Service {

public function ekomiItemreview($language)
        {
                $ekomicertificate = '';
                $errorlang = "";

                if($language == "english"){
                    $interfaceid = $configItem->ekomiInterfaceId;
                    $ekomipassword = $configItem->ekomiPassword;
                    $errorlang = "English";
                }
           
           
        try
        {

                   
                        $Url = $config->ekomiProFeedbakUrl;
                        $Service = new Itemreview_Service_ClassAPIwebService($Url, "GET", "ISO-8859-1");

                        $Params["interface_id"]   = $interfaceid;           
                        $Params["interface_pw"] = $ekomipassword;             
                        $Params["type"] = "csv";


                        $Params["range"] = $config->ekomiRange;
                        flush();
                        $Response = $Service->SendRequest($Params);
                        $CSVBODY = $Response["Body"];


                        $ItemreviewServicearray = new Itemreview_Service_ItemreviewService();                  
                        $retunval = $ItemreviewServicearray->csv_to_array($CSVBODY);                     
                        foreach ($retunval as $key => $arrParam) {
                           
                               try
                                {
                                        $ItemreviewService = new Itemreview_Service_ItemreviewService();
                                        $Itemreviwentity = new Itemreview_Entity_Itemreview();
                                        $Itemreviwentity->setItm_id($arrParam['product_id']);
                                        $Itemreviwentity->setLang_id(66);
                                        $Itemreviwentity->set_auther("eKomi");
                                        $Itemreviwentity->setRe_text($arrParam['feedback']);
                                        $Itemreviwentity->setRe_text($replasequote);
                                       
                                        $Itemreviwentity->set_rating($arrParam['star_rating']);
                                        $Itemreviwentity->set_reviewlink("$ekomicertificate");
                                        $Itemreviwentity->setRe_isenable(1);
                                        $Itemreviwentity->set_unixtime($arrParam['UNIXTIME']);
                                        $Itemreviwentity->set_orderid($arrParam['order_id']);
                   
                                        $ItemreviewDAO = new Itemreview_Dao_ItemreviewDao();
                                        $ItemreviewDAO->addEkomireview($Itemreviwentity);
                                }
                                catch ( Exception $e)
                                {
                                        print_r("error ...!!");

                                }                    
                        }

        }
        catch ( Exception $e)
        {
                        print_r("record fail-$errorlang ---!!!");
        }  
        }
       
        public static function csv_to_array($csv, $delimiter = ',', $enclosure = '"', $escape = '\\', $terminator = "\n") {
                                $r = array();
                                $filecsv = APPLICATION_PATH."/xml/eKomiresponce.csv";
                                if(file_exists($filecsv)){
                                    unlink($filecsv);
                                }                               
                                $fp = fopen($filecsv, 'w');
                                fwrite($fp, $csv);
                                fclose($fp);
                               
                                $name_columns = array("UNIXTIME", "order_id", "product_id", "star_rating", "feedback");
                                $handle = fopen ($filecsv, 'r');
                                                while (($data = fgetcsv($handle, 1000, ',', '"')) !== FALSE)
                                                {
                                                      $r[] = array_combine($name_columns,$data);
                                                }             
                                return $r;
                              
                        }     






Following Class , i use to connect eKomi web service and get reviews




class Itemreview_Service_ClassApiwebService
{
    const TIME_OUT = 10;

    private $UserAgent;
    private $Method;
    private $CharSet;
    private $Url;
   
   
    public function __construct($ServerUrl, $Method, $CharSet, $UserAgent="")
    {

        error_reporting(E_ERROR | E_WARNING | E_PARSE);

        if (function_exists(domxml_open_mem))
            throw new Exception("Please comment out the line 'extension=php_domxml.dll' in Apache/bin/php.ini and restart the server!");
       
        if (empty($UserAgent)) $UserAgent = "PHP WebService Client";
       
        $this->Url       = parse_url($ServerUrl);
        $this->UserAgent = $UserAgent;
        $this->Method    = strtoupper($Method);
        $this->CharSet   = $CharSet;
       
        if (empty($this->Url["path"])) $this->Url["path"] = "/";
    }
   
    public function SendRequest($Data, $SoapAction="")
    {
        if (is_array($Data))
        {
            $Params = array();
            foreach ($Data as $Key => $Value)
            {
                $Encode = str_replace('%7E', '~', rawurlencode($Value));
                $Params[] = "$Key=$Encode";
            }
            $Query = implode('&', $Params);
        }
        else $DispParams = $Data;
       
        switch ($this->Method)
        {
        case "GET":
            $SendData  = "GET ".$this->Url["path"]."?$Query HTTP/1.0\r\n";
            $SendData .= "Host: " . $this->Url['host'] . "\r\n";
            $SendData .= "User-Agent: " . $this->UserAgent . "\r\n";
            $SendData .= "\r\n";
            break;

        case "POST":
            $SendData  = "POST ".$this->Url["path"]." HTTP/1.0\r\n";
            $SendData .= "Host: " . $this->Url['host'] . "\r\n";
            $SendData .= "Content-Type: application/x-www-form-urlencoded; charset=".$this->CharSet."\r\n";
            $SendData .= "Content-Length: " . strlen($Query) . "\r\n";
            $SendData .= "User-Agent: " . $this->UserAgent . "\r\n";
            $SendData .= "\r\n";
            $SendData .= $Query;
            break;

        default:
            throw new Exception("Invalid Method: ".$this->Method);   
        }
       

        $Port = array_key_exists('port',$this->Url) ? $this->Url['port'] : null;

        switch ($this->Url['scheme'])
        {
            case 'https':
                if (!function_exists(openssl_verify))
                    throw new Exception("Please remove the comment in the line ';extension=php_openssl.dll' in Apache/bin/php.ini and restart the server!");

                $Scheme = 'ssl://';
                $Port = ($Port === null) ? 443 : $Port;
                break;

            case 'http':
                $Scheme = '';
                $Port = ($Port === null) ? 80 : $Port;
                break;
               
            default:
                throw new Exception("Invalid protocol in: ".$this->ServerUrl);
        }
    
        $Socket = @fsockopen($Scheme . $this->Url['host'], $Port, $ErrNo, $ErrStr, 10);
        if (!$Socket)
            throw new Exception ("Unable to establish connection to host " . $this->Url['host'] . " $ErrStr");
       
        fwrite($Socket, $SendData);

        $Response = "";
        while (!feof($Socket))
        {

            $Response .= fgets($Socket, 1000);
        }
        fclose($Socket);
        // Between Header and ResponseBody there are two empty lines
        list($Header, $ResponseBody) = explode("\r\n\r\n", $Response, 2);
       
        $Split = preg_split("/\r\n|\n|\r/", $Header);

        list($Protocol, $StatusCode, $StatusText) = explode(' ', trim(array_shift($Split)), 3);
       
        $RetArray["Status"] = $StatusCode;
        $RetArray["Body"]   = $ResponseBody;
       
        return $RetArray;
    }
}

Hope this will help :)