Wednesday, March 30, 2011

Configure Ext.Direct API with Ext Designer

Hello Folks,


Recently I tried Ext Designer for my ExtJs project. I am using Ext.Direct server pack at back end with ExtJs front end. I had a difficult time with Ext Designer to configure it from Ext Direct API. This the blog on this.


Following is the screen of Ext Designer where you have to add ext direct api settings if you are using Ext Direct.



There you have to add URL of your Ext Direct API. For Example

http://localhost/myproject/lib/direct/api.php

If you simple use above URL and try to save data it will give you error that. Ext.Direct remoting specifications failed to load. Actually Ext Designer expects remoting specifications in JSON format and Ext Direct API returns it in pure JavaScript format.


If you open this URL http://localhost/myproject/lib/direct/api.php in browser you will see following output.


Ext.ns('Remoting'); Remoting.API = {"url":"router.php","type":"remoting","actions":{"Time":[{"name":"get","len":0}]},"namespace":"Remoting"};

This is simple JavaScript out put that current Ext Designer version can not understand. It needs it in JSON format. So you need to edit your ext direct server code to support json format. If should support following URL.

http://localhost/myproject/lib/direct/api.php?format=json


Following should be output.


{"url":"router.php","type":"remoting","actions":{"Time":[{"name":"get","len":0}]},"namespace":"Remoting","descriptor":"Uniframe.API"};

Mark the descriptor field now its included in JSON output. This output can easily be interpreted by Ext Designer.

For this you have to edit your Ext direct code to get format from URL and output data accordingly. There might be some other ways to do it but I did it by modifying _print function in ExtDirect/API.php file. 


Following is my modified function.


private function _print($api) {
                   if(isset($_REQUEST['format'])){ 
                         $isJsonFormat = $_REQUEST['format']; 
                            if(strtolower($isJsonFormat) == 'json'){ 
                                  $api['descriptor'] = $this->_descriptor; 
                                  echo json_encode($api); 
                            }
                   }
                  else{ 
                         header('Content-Type: text/javascript'); 
                         echo ($this->_namespace ?
                'Ext.ns(\'' . substr($this->_descriptor, 0,             strrpos($this->_descriptor, '.')) . '\'); ' . $this->_descriptor:
                'Ext.ns(\'Ext.app\'); ' . 'Ext.app.REMOTING_API'
            ); 
                        echo ' = ';
            echo json_encode($api);
            echo ';'; 
                }
 }

Saturday, March 19, 2011

Ext.Direct and ExtJs form panel submit

Hello,

Recently I am working with Ext.Direct in one of my ExtJs project. So first of all let's see what is Ext.Direct? Ext.Direct is server side stack for Rich Internet Application. Using this you can call server side methods in client side script. Something like remoting in .Net and remote method invocation in Java.  You can set up Ext.Direct to work with ExtJs applications. So its kind of an API. Methods of PHP class can be called in JavaScript.  Following is the syntax to call server side methods.

Application.Init() 

I had some issues with ExtJs form panel. On form submit I was using Ext.Direct API to send parameters to back end. But it was not working as some thing was missing. So that's what I am going to describe here. How to use Ext.Direct with Form Panel.

When using Ext.Direct with Form panel following two extra things you need to add in Form Panel.

{

xtype : 'form',
defaultType : 'textfield',
labelWidth : 70,
frame : true,
labelAlign : 'right',
defaults : formItemDefaults,

api: {                        
                submit: Uniframe.Login.do_login
       },    
paramOrder: ['user_name', 'user_password']
}

Following should be your class definition.


class Login{
        /**
         * @remotable
         * @formHandler
         */
     public function do_login($user_credentials){
        }
}

Here @remotable means method is remotely available and @formHandler means this is method which is going to be called on form submit. All the post parameters you will get in an Array. For example above user_name and user_password can be accessed as follow.

$user_credentials['user_name'];
$user_credentials['user_passsword'];

So this is how you can use Ext.Direct with ExtJs Form Panel submit.

Saturday, March 12, 2011

ExtJs Grid Page Size Plugin

Hello,

Here is another ExtJs blog. Recently I got a requirement for page size plugin in ExtJs grid. User can control number of records in the grid. It should be displayed in grid bottom toolbar. See the image below.


So we created a plugin for it by extending Ext Combo Box. See the code below.


Ext.ux.PageSizePlugin = function() {
Ext.ux.PageSizePlugin.superclass.constructor.call(this, {
          store: new Ext.data.SimpleStore({
                 fields: ['text', 'value'],
                 data: [['50', 50], ['100', 100],['150', 150]]
          }),
                  mode: 'local',
          displayField: 'text',
          valueField: 'value',
          editable: false,
          allowBlank: false,
          triggerAction: 'all',
          width: 50
    });
};

After this extend Ext combo and add the required listeners.

Ext.extend(Ext.ux.PageSizePlugin, Ext.form.ComboBox, {
init: function(paging) {
      paging.on('render', this.onInitView, this);
},

onInitView: function(paging) {
       paging.add('-',
      this,
      'Items per page'
);
this.setValue(paging.pageSize);
        this.on('select', this.onPageSizeChanged, paging);
},

onPageSizeChanged: function(combo) {
       this.pageSize = parseInt(combo.getValue());
       this.doLoad(0);
}
});

So our plugin is ready. Now add it to paging toolbar.

var pager = new Ext.PagingToolbar({
pageSize: 50,
store: store,
displayInfo: true,
displayMsg: 'Displaying topics {0} - {1} of {2}',
emptyMsg: "No topics to display",
plugins: [new Ext.ux.PageSizePlugin()],
listeners: {
beforechange : function (pager, params )  {
}
}
});

Add this toolbar in bottom tool bar of the ExtJs grid.

After this we can use page size while reloading grid data store.

store.load({params:{limit: pager.pageSize}});

Use this limit parameter in your database query.

Saturday, March 5, 2011

Working with Channel Advisor API with PHP

Hello Guys,

Recently I was working with Channel Advisor(CA) API in PHP script. Script was built to get product information from CA and  update product information in CA. First of all lets see what is Channel Advisor platform?

It's a SaaS(Software As A Service) provider which enables retailers to sell products online through various channels like eBay, Amazon etc. It has certain features like product inventory using which retailer can store product information. Those products can be synchronized in various e commerce channels. User can track sales through each channel. Detailed reports are also available.


This platform is built upon .Net Framework and it offers Asp.Net web services to use its API. Using those web service we can use that platform from the third party application. To use web services you have to register as a developer and get developer key and password. After this channel advisor admin will approve your developer account and provides a account ID and local id that developer can use in the scripts. 


Now as we all know that Asp.Net web services use SOAP protocol so we need some soap client in PHP. PHP 5.1 and above has soap pears available while for older version one need to install it separately.


Following is the code to use CA web service.

$developerKey = 'your developer key';
$password = 'password';
$localID = '1111111050';
$accountID = 'account id';


$client = new SoapClient("https://api.channeladvisor.com/ChannelAdvisorAPI/v3/InventoryService.asmx?WSDL");


$headersData = array('DeveloperKey' => $developerKey, 'Password' => $password);


$head = new SoapHeader("http://api.channeladvisor.com/webservices/","APICredentials",$headersData);
$client->__setSoapHeaders($head);


That's it and you have Soap client available now you can call any method which is provided by web service. See the example below.
$result = $client->GetInventoryItemQuantityInfo(array('accountID'=>$accountID,'sku' => $sku));
Above code gives quantity of product specified by sku. 


So this is how you can integrate channel advisor API in PHP. Above example is of inventory service. There are other services also available. Each method in services needs some input. Some are the required fields like product SKU etc. for example cosider following example of SynchInventoryItem method. This is the method used to add or update product in inventory. While working in PHP all the parameters need to be sent in format of an array.



$iteminfo = array('Sku'=>$sku,
                      'Title'=>$title,
                      'Subtitle'=>$title, 
                      'ShortDescription'=>$shortdescription,
                      'Description'=>$description,
                      'Weight'=>$weight,
                      'UPC'=>$upc,
                      'Manufacturer'=>$manufacturer,
                      'Brand'=>$brand,                      
                      
                      'QuantityInfo'=>array('UpdateType'=>'Absolute',
                                            'Total'=>$total
                                            ),
                      'PriceInfo'=>array('Cost'=>$cost,
                                         'RetailPrice'=>$price,
                                         'TakeItPrice'=>$special_price
                                         ),
                      'ImageList'=>array(
                                'ImageInfoSubmit'=>array(
                                'PlacementName'=>'ITEMIMAGEURL1',
                                'FilenameOrUrl'=>$imageurl)),                      
                      'Classification'=>$classification,
                      'AttributeList'=>array(
                                            'AttributeInfo'=>array(
                                                         array(
                                                              'Name'=>'Size',
                                                              'Value'=>$size
                                                           ),
                                                         array(
                                                              'Name'=>'Brand',
                                                              'Value'=>$brand)
                                                           )
                      ),
                      'VariationInfo'=>array('IsInRelationship'=>true,
                                             'RelationshipName'=>'Color',
                                             'IsParent'=>false,
                                             'ParentSku'=>$parent_sku
                                      ),   
                                      
                       );


Then we need to send above array as a parameter in the method.

$arrData = array(
'accountID'=>$accountID,
'item'=>$iteminfo,
);
                
$result=$client->SynchInventoryItem($arrData);
So this is how you can use CA API in PHP script.