Thursday, 19 December 2013

Display Objects accessibility of user

Here in this example we are going to show the Users with the objects which are accessible to that user.

Controller(class)
============
public class Profileobjectpermissions{
public List<ObjectPermissions>  lstperimissions{get;set;}
public Map<String, Schema.SObjectType> Allobjectmap{get;set;}
public Map<String,List<String>> profcustobjectsmap{get;set;}
public Map<String,Integer> objectcount{get;set;}
public Map<String,Integer> userscount{get;set;}
public Map<String,Profile> mapprofile{get;set;}
public Map<String,List<String>> mapprofileobjest{get;set;}
public Profileobjectpermissions(){
    //Allobjectmap=new Map<String,Schema.SobjectType>();
    Allobjectmap=Schema.getGlobalDescribe();
    lstperimissions=new List<ObjectPermissions>();
    objectcount=new Map<String,Integer>();
    userscount=new Map<String,Integer>();
    profcustobjectsmap=new Map<String,List<String>>();
    mapprofile=new Map<String,Profile>();
    mapprofileobjest=new Map<String,List<String>>();
 
    lstperimissions=[SELECT PermissionsRead,SobjectType,ParentId,Parent.label,Parent.IsOwnedByProfile,Parent.ProfileId,Parent.Profile.name,Parent.Profile.UserLicense.Name FROM ObjectPermissions where Parent.Profile.UserLicense.Name='Salesforce' and PermissionsRead=true];
    List<Profile> profilelst=[select id,name,UserLicense.Name,(select id,name from Users) from Profile where UserLicense.Name='Salesforce'];
    if(lstperimissions!=null && lstperimissions!=null){
        for(ObjectPermissions objper:lstperimissions){
         
            if(objper.PermissionsRead==true && Allobjectmap.get(objper.SobjectType)!=null &&  Allobjectmap.get(objper.SobjectType).getDescribe().isCustom()==true){
                if(profcustobjectsmap.get(objper.Parent.Profile.name)!=null)
                        profcustobjectsmap.get(objper.Parent.Profile.name).add(Allobjectmap.get(objper.SobjectType).getDescribe().getLabel());
                else
                        profcustobjectsmap.put(objper.Parent.Profile.name,new List<String>{Allobjectmap.get(objper.SobjectType).getDescribe().getLabel()});
            }
         
        }
    }
    if(profilelst!=null && profilelst.size()>0){
        for(Profile profobj:profilelst){
                    System.debug('profileName:'+profobj.name);
                    mapprofile.put(profobj.Name,profobj);                
                    //Users count
                    if(profobj.users!=null && profobj.users.size()>0){
                        userscount.put(profobj.name,profobj.users.size());
                    }
                    else{
                        userscount.put(profobj.name,0);
                    }
                    //Object Count
                    if(profcustobjectsmap.size()>0 && profcustobjectsmap.get(profobj.name)!=null && profcustobjectsmap.get(profobj.name).size()>0)
                            objectcount.put(profobj.name,profcustobjectsmap.get(profobj.name).size());
                    else
                        objectcount.put(profobj.name,0);
                    if(profcustobjectsmap.size()>0 && profcustobjectsmap.get(profobj.Name)!=null){
                        mapprofileobjest.put(profobj.Name,profcustobjectsmap.get(profobj.Name));
                    }
                    else{
                         mapprofileobjest.put(profobj.Name,new List<String>{'No custom objects accessible'});
                    }
                 
        }
        System.debug('objectcount.keyset();;;'+objectcount.keyset());
    }
         
}
}
Page
====
<apex:page controller="Profileobjectpermissions">
    <apex:form >
        <apex:pageBlock title="Chatter  User permissions">
            <apex:pageBlockTable value="{!objectcount}" var="perm">              
                    <apex:column headerValue="Profile Name">
                        <apex:outputLink value="/{!mapprofile[perm].Id}" target="_blank">{!perm}</apex:outputLink>
                    </apex:column>
                    <apex:column headerValue="Object Count" value="{!objectcount[perm]}"/>
                    <apex:column headervalue="Users Count" value="{!userscount[perm]}"/>
                    <apex:column headerValue="Objects" value="{!mapprofileobjest[perm]}"/>
                </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:form>
</apex:page>
===

Output:
=====

Row edit and save using wrapper class

Here in this example we are displaying the records with edit link.When we click "edit" link then it shows in editable mode there itself then we can update the record there itself.With this we can update record row wise without updating all the rows like in inlineediting.

Controller Page:
================
public class wrapperclass
{
 wrapper objwrapper;
 List<wrapper> lstwrapper=new List<wrapper>();
  public integer rowIndex{get;set;}
 
  public wrapperclass(){
  lst = new list<wrapper>();
     List<Account> lstaccount=[select name,industry,type from account];

     for(integer i=0;i<lstaccount.size();i++)
     {
       objwrapper=new wrapper();
       objwrapper.act=lstaccount[i];
        objwrapper.isEdit = false;
       objwrapper.rowNo = lst.size();
       lst.add(objwrapper);
     }
     
  }
 public List<wrapper> lst{get;set;}
 public pagereference editmethid(){
     if(lst.size()>rowIndex){
         lst[rowIndex].isEdit = true;
     }
     return null;
 }

  public pagereference savemethid(){
     if(lst.size()>rowIndex){
         update lst[rowIndex].act;  
         lst[rowIndex].isEdit = false;
     }
     return null;
 }

 public class wrapper{
 public Account act{get;set;}
 public integer rowNo {get;set;}
 public boolean isEdit{get;set;}
 }
}

Page Code:
=========
<apex:page controller="wrapperclass">
  <apex:form >
  <apex:pageBlock id="thePB">
  <apex:pageblocktable value="{!lst}" var="a">
  <apex:column headerValue="Action">
      <apex:commandlink value="Edit" rerender="thePB" rendered="{!NOT(a.isEdit)}" action="{!editmethid}">
          <apex:param name="rowNumber" value="{!a.rowNo}" assignTo="{!rowIndex}"/>
      </apex:commandLink>
      <apex:commandlink value="Save" rerender="thePB" rendered="{!a.isEdit}" action="{!savemethid}">
         <apex:param name="rowNumber" value="{!a.rowNo}" assignTo="{!rowIndex}"/>
      </apex:commandLink>        
  </apex:column>
  <apex:column HeaderValue="Name">
  <apex:outputField value="{!a.act.name}" rendered="{!NOT(a.isEdit)}"/>
  <apex:inputField value="{!a.act.name}" rendered="{!a.isEdit}"/>
  </apex:column>
  <apex:column HeaderValue="Type">
  <apex:outputField value="{!a.act.type}" rendered="{!NOT(a.isEdit)}"/>
  <apex:inputField value="{!a.act.type}" rendered="{!a.isEdit}"/>
  </apex:column>
  <apex:column HeaderValue="Industry">
  <apex:outputField value="{!a.act.industry}" rendered="{!NOT(a.isEdit)}" />
  <apex:inputField value="{!a.act.industry}" rendered="{!a.isEdit}"/>
  </apex:column>
  </apex:pageblocktable>
  </apex:pageBlock>
  </apex:form>
 
</apex:page>

==============
Output:
============

Searching In Google Search from Visua lforce page

Here in this example we just use "Search" custom object which can hold searchable things what we want to have in the vf page for searching we have sample tool bar with different links to navigate.

When we click on "Search Google" link in a particular row then it shows the search result of that record which we  displayed in vf page.

Class:
====
public with sharing class acccon2 {
    List<SearchObject__c> acc;
        public acccon2(ApexPages.StandardController controller) {

    }
    public String accid{get; set;}
   
    public List<SearchObject__c> getlstaccounts()
    {
    acc=[Select id,name, Search__c from SearchObject__c];
    return acc;
    }
   
    public pagereference ref()
    {
    pagereference ref= new pagereference('/'+accid);
    ref.setredirect(true);
    return ref;
    }
   
}

Page:
=====
<apex:page standardController="SearchObject__c" extensions="acccon2" showHeader="false" >

 <apex:toolbar >
 <apex:toolbarGroup itemSeparator="line" >
 <apex:outputLink value="http://mail.appshark.com" target="_blank" ><font color="white"  >AppsharkMail</font></apex:outputLink>
  <apex:outputLink value="http://www.gmail.com" target="_blank"><font color="white">Gmail</font></apex:outputLink>
  <apex:outputLink value="http://www.linkedin.com" target="_blank"><font color="white">LinkedIn</font></apex:outputLink>
  <apex:outputLink value="http://www.mypptsearch.com" target="_blank"><font color="white">MypptSearch</font></apex:outputLink>
   <apex:outputLink value="http://wiki.developerforce.com" target="_blank"><font color="white">WikiDeveloperforce</font></apex:outputLink>
    <apex:outputLink value="http://login.salesforce.com" target="_blank"><font color="white">SalesForcelogin</font></apex:outputLink>
  </apex:toolbarGroup>
  </apex:toolbar>




 <apex:form >
 <apex:pageBlock title="Search the following Things Here Itself" >
 <apex:pageBlockTable value="{!lstaccounts}" var="acc">

 <apex:column >
 <apex:commandLink value="{!acc.name}" action="{!ref}">
 <apex:param value="{!acc.Id}" name="accid" assignTo="{!accid}" />
 </apex:commandLink>
 </apex:column>
 <apex:column HeaderValue="Clickon Search Google">
 <apex:outputLink value="http://google.com/search" target="_blank">

        Search Google

        <apex:param name="q" value="{!acc.name}"/>

    </apex:outputLink>
 </apex:column>
  </apex:pageBlockTable>
 </apex:pageBlock>
 </apex:form>
</apex:page>

Outtput:
======




Row Expander with ExtJS (Account with list of contacts)

Here in this example we are showing all the accounts when we click on Account row then we are showing

related Contacts under the account.It is implemented in  ExtJs

Controller (class):
=============
global class rowExpanderCls {

    public PageReference fetch() {
        lstcon=[Select id, name, phone from contact where accountId=:recordId];
        System.debug('------------lstcon-------------------'+lstcon);
     
        return null;
    }

        @RemoteAction
        global static String getUserData(String recordId){
            List<Contact> lstcon=[Select id, name, phone from contact where accountId=:recordId];
            System.debug('------------lstcon-------------------'+lstcon);
            String JSONString = JSON.serialize(lstcon);
            //Depends on your needs and way you want to format your result. Lets just hardcode the status value for now.
            return '{"Records":' +JSONString+', "error": "null", "status":"SUCCESS"}';
         }
       
       
         @RemoteAction
        global static String check(){
            return 'hello';
        }
// public List<Contact> lstcon;
 public string recordId{get; set;}

@RemoteAction
global static String getContacts(string id){
    System.debug('---------->'+id);
    return id;
}

public List<Contact> lstcon{get; set;}

 public class wrapper{
   
     public boolean has_leaf{get; set;}
     public Account acc{get; set;}
   
     public wrapper(boolean b, Account a){
         has_leaf = b;
         acc= a;
     }

 }

 public List<wrapper> lstwrap{get; set;}
 public rowExpanderCls(){
         recordId='';
         lstcon = new List<Contact>();
         List<Account> lst =[Select id,name, phone ,(Select id, name from Contacts) from Account];
         lstwrap = new List<wrapper>();
         lstcon = [Select id, name, phone from contact];
         for(Account a:lst){
             if(a.contacts.size()>0)
             lstwrap.add(new wrapper(false, a));
             else
             lstwrap.add(new wrapper(true, a));
         }
 }

}


Page:
=====
<apex:page controller="rowExpanderCls" sidebar="false" >
    <apex:includeScript value="{!$Resource.Extjs4Vf}/ext-3.0.0/adapter/ext/ext-base.js"/>
    <apex:includeScript value="{!$Resource.Extjs4Vf}/ext-3.0.0/ext-all.js"/>
    <apex:includeScript value="{!$Resource.Rowexpandar}"/>
    <apex:stylesheet value="{!$Resource.Extjs4Vf}/ext-3.0.0/resources/css/ext-all.css"/>

    <script type="text/javascript">
    Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
    Ext.onReady( function() {
       //Ext.Msg.alert('hi');
       //alert('{!lstwrap}');
    var data = [
        <apex:repeat value="{!lstwrap}" var="w">
            ['{!w.acc.name}','{!w.acc.phone}','{!w.has_leaf}','{!w.acc.id}'],
        </apex:repeat>
    ];
     
    var secondData =[
     
    ]  
    /**
     * Custom function used for column renderer
     * @param {Object} val
     */
    function change(val) {
        if (val > 0) {
            return '<span style="color:green;">' + val + '</span>';
        } else if (val < 0) {
            return '<span style="color:red;">' + val + '</span>';
        }
        return val;
    };

    /**
     * Custom function used for column renderer
     * @param {Object} val
     */
        function pctChange( val) {
            if (val > 0) {
                return '<span style="color:green;">' + val + '%</span>';
            } else if (val < 0) {
                return '<span style="color:red;">' + val + '%</span>';
            }
            return val;
        };

        var firststore = new Ext.data.ArrayStore({
            fields: [
                { name: 'Company' },
                { name: 'Phone', type: 'string'},
                { name: 'is_leaf', type: 'bool' },
                { name: 'Id', type: 'string' }
            ],
            data: data
        });
       
     
        var secondstore = new Ext.data.JsonStore({
            fields: [
                        {name: 'Id'},
                        {name: 'Name', type: 'string'},
                        {name: 'Phone', type: 'string'}
            ],
            data: secondData,
            type: 'json'
         
        });
   var oldIndex = 0;
   var getGrid = function( data, store, element, type) {
     
        var expander = new Ext.ux.grid.RowExpander({
            tpl              : '<div class="ux-row-expander-box"></div>',
            actAsTree        : true,
            treeLeafProperty : 'is_leaf',
           
            listeners        : {
                 beforeExpand: function(record, body, rowIndex){
                    //alert('hi');
                    //alert(rowIndex);
                    //alert(record);
                    //alert(body);
                    //alert(oldIndex);
                  //alert(Ext.fly(rowIndex).hasClass(this.rowCollapsedClass));
                  //alert(Ext.fly(rowIndex));
                  expander.collapseRow(oldIndex);
                  //for(i = 0; i <= grid.getStore().getCount(); i++) {
                  //    expander.collapseRow(i);
                  //}
                   
                 
                   
                 },  
                expand : function( expander, record, body, rowIndex) {
                   //alert(rowIndex)
                   secondstore.removeAll();
                   var recId = grid.getStore().getAt(rowIndex).get('Id');
                   rowExpanderCls.getUserData(recId,function(result, er){ //This method is used to call our controller method
                   var res = Ext.decode(result);
                   secondstore.loadData(res.Records);
                   }, {escape:false});
                 
                   getGrid1(secondData,secondstore,Ext.get(this.grid.getView().getRow(rowIndex)).child('.ux-row-expander-box'));                
                   oldIndex = rowIndex;
                },
                 collapse: function( expander, record, body, rowIndex) {
                     //alert(rowIndex);
                 }
               
               
            }
        });
       
             
        var grid = new Ext.grid.GridPanel({
            id: 'parentgrid',
            store: store,
            columns: [
                expander,
                { id:'company',header: 'Company', width: 160, sortable: true, dataIndex: 'Company'},
                {header: 'Phone', width: 150, sortable: true, dataIndex: 'Phone'},
            ],
            stripeRows: true,
            autoExpandColumn: 'company',
            autoHeight: true,
            border: false,
            width: '100%',
            stateful: false,
            stateId: 'grid',
            listeners: {
                headerclick: function(g, index, ev) {
                    alert('Hi');
                    rowExpanderCls.check(function(result, er){ //This method is used to call our controller method
                    alert(result);
                    }, {escape:false});
                }
            },
            plugins: expander
        });
        element && grid.render( element);
        return grid;
    };
   
     var getGrid1 = function( data, store, element) {
       //alert('called');
       //alert(store);
     
     
       var grid = new Ext.grid.GridPanel({
             id: 'childgrid',
            store: store,
            columns: [
                { id:'name',header: 'Name', width: 150, sortable: true, dataIndex: 'Name' },
                { header: 'Phone', width: 150, sortable: true , dataIndex: 'Phone' },
            ],
            stripeRows: true,
            autoExpandColumn: 'name',
            autoHeight: true,
            border: false,
            width: '100%',
            stateful: true,
            stateId: 'grid',
         
        });
        element && grid.render( element);
        return grid;
    };

    var panel = new Ext.Panel({
        title      : "Nested Grids Example",
        autoHeight : true,
        items      : [getGrid(data,firststore)],
        applyTo    : 'grid-box'
    });

});
    </script>
    <apex:form id="form" >
   
    <div id="grid-box"></div>  
    </apex:form>
</apex:page>

output:
=====







Showing List of contacts under each Account in Ext JS grid

Here we are showing all the list of contacts under particular account when we click on that as shown below.

Controller:
==========
public class accountdatacls231{
public string id{get;set;}
public integer rowindex1{get;set;}
public List<Account> lstaccount{get;set;}
List<wraper1> lstwraper;
public void rendering(){
        lstaccount=[select id,name,industry,type,(select id,name,firstname,lastname from contacts) from account where id=:id];
         //if(lstwraper.size()>rowindex1)
              for(wraper1 objwraper1:lstwraper)
                  objwraper1.ren='none';
                lstwraper[rowindex1].ren='block';
               
               
     

}
public List<wraper1> getAccounts1(){
    if(lstwraper == null || lstwraper .size()==0){
        integer i=0;
        lstwraper=new List<wraper1>();
        wraper1 wrapobj;
         for(Account acc:[select id,name,industry,type,(select id,name,firstname,lastname from contacts) from account]){
                wrapobj=new wraper1();
                wrapobj.accobj=acc;
                wrapobj.ren='none';
                wrapobj.rowindex=i;
                lstwraper.add(wrapobj);
                i++;
               
        }
    }
    return lstwraper;
}
public class wraper1{
    public Account accobj{get;set;}
    public integer rowindex{get;set;}
    public string ren{get;set;}
    public List<Contact> contobj{get;set;}

}

}

Page:
====
<apex:page controller="accountdatacls231">
    <apex:includeScript value="{!$Resource.Extjs4Vf}/ext-3.0.0/adapter/ext/ext-base.js"/>
    <apex:includeScript value="{!$Resource.Extjs4Vf}/ext-3.0.0/ext-all.js"/>
    <apex:stylesheet value="{!$Resource.Extjs4Vf}/ext-3.0.0/resources/css/ext-all.css"/>
<apex:form id="fm">
    <table border="1">
        <tr>
           <th>AccountName</th>
       </tr>
          <tr>
            <td><apex:repeat value="{!Accounts1}"  var="a">
                <tr>
                  <td>
                      <apex:commandLink value="{!a.accobj.name}" action="{!rendering}"  reRender="fm">
                         <apex:param value="{!a.accobj.id}" name="id" assignTo="{!id}"/>
                         <apex:param value="{!a.rowindex}" name="rowindex1" assignTo="{!rowindex1}"/>
                     </apex:commandLink>
                     <apex:outputText >{!a.rowindex}</apex:outputText>
                     <div id="{!a.accobj.id}" style="display:{!a.ren}">
                       <script type="text/javascript">

                             Ext.onReady(function() {
                                var showIndividualGraph = function(firstgrid,rowIndex,e){
                                        //var rec = grid.getStore().getAt(rowIndex);
                                        //var columnName = grid.getColumnModel().getDataIndex(cellIndex);
                                        Ext.MessageBox.alert('Clicked!','You Clicked row!'+rowIndex);
                                }
                                     
                             var myData = {
                           
                                records : [
                                            <apex:repeat value="{!lstaccount}" var="con" id="ContactRepeat">
                                                <apex:repeat value="{!con.contacts}" var="con">
                                                      {name:"{!con.name}",column1:"{!con.firstname}",column2:"{!con.lastname}"},
                                                </apex:repeat>
                                            </apex:repeat>
                                        ]
                              };
                              var fields = [
                           
                                     {name: 'name', mapping : 'name'},                              
                                     {name: 'column1', mapping : 'column1'},                              
                                     {name: 'column2', mapping : 'column2'}                              
                              ];
                             var firstGridStore = new Ext.data.JsonStore({
                           
                                    fields : fields,                          
                                    data   : myData,                          
                                    root   : 'records'                          
                                });
                           
                            var cols = [                          
                                { id : 'name', header: "Contact Name", width: 160, sortable: true, dataIndex: 'name'},                          
                                {header: "First Name", width: 160, sortable: true,dataIndex: 'column1'},                          
                                {header: "Last Name", width: 160, sortable: true, dataIndex: 'column2'}                          
                              ];
                            var firstGrid = new Ext.grid.GridPanel({
                           
                                   ddGroup        : 'secondGridDDGroup',                          
                                    store            : firstGridStore,                          
                                    columns          : cols,                          
                                    enableDragDrop   : true,                                  
                                    stripeRows       : true,                                  
                                    autoExpandColumn : 'name',                          
                                    width            : 650,
                                    height           : 300,  
                                    region           : 'west',
                                    renderTo : '{!a.accobj.id}',                          
                                    title            : 'First Grid',
                                    listeners : {
                                            'celldblclick':showIndividualGraph ,
                                    }
                                   
                           
                                });
                             

                            });
                                               
                    </script>
                <!-- <div  style="backgroud-color:red;Color:green;display:{!a.ren};"></div> -->
                </div>
               
                  </td>
                </tr>        
               </apex:repeat>
             
             </td>
          </tr>
       
    </table>
 </apex:form>
</apex:page>

Output:
=====





Grid with all Accounts in Ext Js (Column Sorting and add or remove columns)

Here we are going to display the account in our org to grid implemented in extjs as shown below.

It is having the capability to sort the columns and remove and add columns in the grid.

Controller:
==============
public class ExtJSDataGrid1Controller {
  public list<account> getmycontacts(){
      list<account> lstacc=[select id,name,industry,type from account];
     return lstacc;  
  }
}

Page with extjs script:
==================
<apex:page showHeader="false" standardStylesheets="false" controller="ExtJSDataGrid1Controller" >
  <apex:includeScript value="{!$Resource.Extjs4Vf}/ext-3.0.0/adapter/ext/ext-base.js"/>
    <apex:includeScript value="{!$Resource.Extjs4Vf}/ext-3.0.0/ext-all.js"/>
    <apex:includeScript value="{!$Resource.ux}"/>
    <apex:stylesheet value="{!$Resource.Extjs4Vf}/ext-3.0.0/resources/css/ext-all.css"/>
    <script type="text/javascript">
Ext.onReady(function(){
Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
var myDataString = 'var myData = [ ';
<apex:repeat value="{!myContacts}" var="con" id="ContactRepeat">
myDataString += "['{!con.Id}','{!con.Name}','{!con.Industry}','{!con.Type}'],";
</apex:repeat>
myDataString += "['','',''] ];";
eval(myDataString);
var store = new Ext.data.SimpleStore({fields:[{name:'ID'},{name:'FirstName'},{name:'LastName'},{name:'Fax'}]});
store.loadData(myData);
// CREATE THE GRID
var grid = new Ext.grid.GridPanel({store: store, columns: [
{id: 'ID', header: "ID", width: 50, sortable: true, dataIndex: 'ID'},
{id: 'FirstName', header: "AccountName", width: 150, sortable: true, dataIndex: 'FirstName'},
{id: 'LastNme', header: "Industry", width: 150, sortable: true, dataIndex: 'LastName'},
{id:'Fax',header:"Type",width:150,sortable:true,dataIndex:'Fax'}
],
stripeRows:true, autoExpandColumn: 'ID', height: 500, width: 1000, title: 'MY EXT JS Account List'});

Ext.namespace('Ext.ux.dd');

Ext.ux.dd.GridDragDropRowOrder = Ext.extend(Ext.util.Observable,
{
    copy: false,

    scrollable: false,

    constructor : function(config)
    {
        if (config)
            Ext.apply(this, config);

        this.addEvents(
        {
            beforerowmove: true,
            afterrowmove: true,
            beforerowcopy: true,
            afterrowcopy: true
        });

       Ext.ux.dd.GridDragDropRowOrder.superclass.constructor.call(this);
    },

    init : function (grid)
    {
        this.grid = grid;
        grid.enableDragDrop = true;

        grid.on({
            render: { fn: this.onGridRender, scope: this, single: true }
        });
    },

    onGridRender : function (grid)
    {
        var self = this;

        this.target = new Ext.dd.DropTarget(grid.getEl(),
        {
            ddGroup: grid.ddGroup || 'GridDD',
            grid: grid,
            gridDropTarget: this,

            notifyDrop: function(dd, e, data)
            {
                // Remove drag lines. The 'if' condition prevents null error when drop occurs without dragging out of the selection area
                if (this.currentRowEl)
                {
                    this.currentRowEl.removeClass('grid-row-insert-below');
                    this.currentRowEl.removeClass('grid-row-insert-above');
                }

                // determine the row
                var t = Ext.lib.Event.getTarget(e);
                var rindex = this.grid.getView().findRowIndex(t);
                if (rindex === false || rindex == data.rowIndex)
                {
                    return false;
                }
                // fire the before move/copy event
                if (this.gridDropTarget.fireEvent(self.copy ? 'beforerowcopy' : 'beforerowmove', this.gridDropTarget, data.rowIndex, rindex, data.selections, 123) === false)
                {
                    return false;
                }

                // update the store
                var ds = this.grid.getStore();

                // Changes for multiselction by Spirit
                var selections = new Array();
                var keys = ds.data.keys;
                for (var key in keys)
                {
                    for (var i = 0; i < data.selections.length; i++)
                    {
                        if (keys[key] == data.selections[i].id)
                        {
                            // Exit to prevent drop of selected records on itself.
                            if (rindex == key)
                            {
                                return false;
                            }
                            selections.push(data.selections[i]);
                        }
                    }
                }

                // fix rowindex based on before/after move
                if (rindex > data.rowIndex && this.rowPosition < 0)
                {
                    rindex--;
                }
                if (rindex < data.rowIndex && this.rowPosition > 0)
                {
                    rindex++;
                }

                // fix rowindex for multiselection
                if (rindex > data.rowIndex && data.selections.length > 1)
                {
                    rindex = rindex - (data.selections.length - 1);
                }

                // we tried to move this node before the next sibling, we stay in place
                if (rindex == data.rowIndex)
                {
                    return false;
                }

                // fire the before move/copy event
                /* dupe - does it belong here or above???
                if (this.gridDropTarget.fireEvent(self.copy ? 'beforerowcopy' : 'beforerowmove', this.gridDropTarget, data.rowIndex, rindex, data.selections, 123) === false)
                {
                    return false;
                }
                */

                if (!self.copy)
                {
                    for (var i = 0; i < data.selections.length; i++)
                    {
                        ds.remove(ds.getById(data.selections[i].id));
                    }
                }

                for (var i = selections.length - 1; i >= 0; i--)
                {
                    var insertIndex = rindex;
                    ds.insert(insertIndex, selections[i]);
                }

                // re-select the row(s)
                var sm = this.grid.getSelectionModel();
                if (sm)
                {
                    sm.selectRecords(data.selections);
                }

                // fire the after move/copy event
                this.gridDropTarget.fireEvent(self.copy ? 'afterrowcopy' : 'afterrowmove', this.gridDropTarget, data.rowIndex, rindex, data.selections);
                return true;
            },

            notifyOver: function(dd, e, data)
            {
                var t = Ext.lib.Event.getTarget(e);
                var rindex = this.grid.getView().findRowIndex(t);

                // Similar to the code in notifyDrop. Filters for selected rows and quits function if any one row matches the current selected row.
                var ds = this.grid.getStore();
                var keys = ds.data.keys;
                for (var key in keys)
                {
                    for (var i = 0; i < data.selections.length; i++)
                    {
                        if (keys[key] == data.selections[i].id)
                        {
                            if (rindex == key)
                            {
                                if (this.currentRowEl)
                                {
                                    this.currentRowEl.removeClass('grid-row-insert-below');
                                    this.currentRowEl.removeClass('grid-row-insert-above');
                                }
                                return this.dropNotAllowed;
                            }
                        }
                    }
                }

                // If on first row, remove upper line. Prevents negative index error as a result of rindex going negative.
                if (rindex < 0 || rindex === false)
                {
                    this.currentRowEl.removeClass('grid-row-insert-above');
                    return this.dropNotAllowed;
                }

                try
                {
                    var currentRow = this.grid.getView().getRow(rindex);
                    // Find position of row relative to page (adjusting for grid's scroll position)
                    var resolvedRow = new Ext.Element(currentRow).getY() - this.grid.getView().scroller.dom.scrollTop;
                    var rowHeight = currentRow.offsetHeight;

                    // Cursor relative to a row. -ve value implies cursor is above the row's middle and +ve value implues cursor is below the row's middle.
                    this.rowPosition = e.getPageY() - resolvedRow - (rowHeight/2);

                    // Clear drag line.
                    if (this.currentRowEl)
                    {
                        this.currentRowEl.removeClass('grid-row-insert-below');
                        this.currentRowEl.removeClass('grid-row-insert-above');
                    }

                    if (this.rowPosition > 0)
                    {
                        // If the pointer is on the bottom half of the row.
                        this.currentRowEl = new Ext.Element(currentRow);
                        this.currentRowEl.addClass('grid-row-insert-below');
                    }
                    else
                    {
                        // If the pointer is on the top half of the row.
                        if (rindex - 1 >= 0)
                        {
                            var previousRow = this.grid.getView().getRow(rindex - 1);
                            this.currentRowEl = new Ext.Element(previousRow);
                            this.currentRowEl.addClass('grid-row-insert-below');
                        }
                        else
                        {
                            // If the pointer is on the top half of the first row.
                            this.currentRowEl.addClass('grid-row-insert-above');
                        }
                    }
                }
                catch (err)
                {
                    console.warn(err);
                    rindex = false;
                }
                return (rindex === false)? this.dropNotAllowed : this.dropAllowed;
            },

            notifyOut: function(dd, e, data)
            {
                // Remove drag lines when pointer leaves the gridView.
                if (this.currentRowEl)
                {
                    this.currentRowEl.removeClass('grid-row-insert-above');
                    this.currentRowEl.removeClass('grid-row-insert-below');
                }
            }
        });

        if (this.targetCfg)
        {
            Ext.apply(this.target, this.targetCfg);
        }

        if (this.scrollable)
        {
            Ext.dd.ScrollManager.register(grid.getView().getEditorParent());
            grid.on({
                beforedestroy: this.onBeforeDestroy,
                scope: this,
                single: true
            });
        }
    },

    getTarget: function()
    {
        return this.target;
    },

    getGrid: function()
    {
        return this.grid;
    },

    getCopy: function()
    {
        return this.copy ? true : false;
    },

    setCopy: function(b)
    {
        this.copy = b ? true : false;
    },

    onBeforeDestroy : function (grid)
    {
        // if we previously registered with the scroll manager, unregister
        // it (if we don't it will lead to problems in IE)
        Ext.dd.ScrollManager.unregister(grid.getView().getEditorParent());
    }
});

grid.render('myContactList-grid');
grid.getSelectionModel().selectFirstRow();
});
</script>
 <div id="myContactList-grid"></div>
 <div id="uploader"></div>
</apex:page>

outputPut:
========

Drag and Drop with ExtJs

Here

We have implementation of drag and drop  using ExtJs.

To work with ExtJs properties and methods we need to include some of the basic files in the page as shown below.We have different things to use in the following example to get dragdrop functionality.

Page Code:
======

<apex:page showHeader="false" standardStylesheets="false">

  <apex:includeScript value="{!$Resource.Extjs4Vf}/ext-3.0.0/adapter/ext/ext-base.js"/>
    <apex:includeScript value="{!$Resource.Extjs4Vf}/ext-3.0.0/ext-all.js"/>
    <apex:stylesheet value="{!$Resource.Extjs4Vf}/ext-3.0.0/resources/css/ext-all.css"/>

 <script type="text/javascript">

 Ext.onReady(function() {
var strTest= '{ name : "Rec 0", column1 : "0", column2 : "0",column3:"0" },';
    var myData = {

    records : [

       
      {name:"Rec 0",column1:"1",column2:"0"},
      { name : "Rec 1", column1 : "1", column2 : "1",column3:"1" },

      { name : "Rec 2", column1 : "2", column2 : "2",column3:"2" },

      { name : "Rec 3", column1 : "3", column2 : "3",column3:"3" },

      { name : "Rec 4", column1 : "4", column2 : "4",column3:"4" },

      { name : "Rec 5", column1 : "5", column2 : "5",column3:"5"},

      { name : "Rec 6", column1 : "6", column2 : "6",column3:"6"  },

      { name : "Rec 7", column1 : "7", column2 : "7",column3:"7" },

      { name : "Rec 8", column1 : "8", column2 : "8",column3:"8" },

      { name : "Rec 9", column1 : "9", column2 : "9",column3:"9" }

    ]

  };


  // Generic fields array to use in both store defs.

  var fields = [

     {name: 'name', mapping : 'name'},

     {name: 'column1', mapping : 'column1'},

     {name: 'column2', mapping : 'column2'},
     {name:'column3',mapping:'column3'}

  ];



    // create the data store

    var firstGridStore = new Ext.data.JsonStore({

        fields : fields,

    data   : myData,

    root   : 'records'

    });
  // Column Model shortcut array

  var cols = [

    { id : 'name', header: "Record Name", width: 160, sortable: true, dataIndex: 'name'},

    {header: "column1", width: 50, sortable: true, dataIndex: 'column1'},

    {header: "column2", width: 50, sortable: true, dataIndex: 'column2'},
    {header:"column3",width:50,sortable:true,dataIndex:'column3'}

  ];



  // declare the source Grid

    var firstGrid = new Ext.grid.GridPanel({

  ddGroup          : 'secondGridDDGroup',

        store            : firstGridStore,

        columns          : cols,

  enableDragDrop   : true,

        stripeRows       : true,

        autoExpandColumn : 'name',

        width            : 325,

  region           : 'west',

        title            : 'First Grid',
        viewConfig: {
        plugins: {
            ptype: 'gridviewdragdrop',
            dragText: 'Drag and drop to reorganize'
        }
    }

    });



    var secondGridStore = new Ext.data.JsonStore({

        fields : fields,

    root   : 'records'

    });
    // create the destination Grid

    var secondGrid = new Ext.grid.GridPanel({

  ddGroup          : 'firstGridDDGroup',

        store            : secondGridStore,

        columns          : cols,

  enableDragDrop   : true,

        stripeRows       : true,

        autoExpandColumn : 'name',

        width            : 325,

  region           : 'center',

        title            : 'Second Grid'

    });
  //Simple 'border layout' panel to house both grids

  var displayPanel = new Ext.Panel({

    width    : 650,

    height   : 300,

    layout   : 'border',

    renderTo : 'panel',

    items    : [

      firstGrid,

      secondGrid

    ],

    bbar    : [

      '->', // Fill

      {

        text    : 'Reset both grids',

        handler : function() {

          //refresh source grid

          firstGridStore.loadData(myData);



          //purge destination grid

          secondGridStore.removeAll();

        }

      }

    ]

  });



  // used to add records to the destination stores

  var blankRecord =  Ext.data.Record.create(fields);



  /****

  * Setup Drop Targets

  ***/

  // This will make sure we only drop to the view container

  var firstGridDropTargetEl =  firstGrid.getView().el.dom.childNodes[0].childNodes[1];

  var firstGridDropTarget = new Ext.dd.DropTarget(firstGridDropTargetEl, {

    ddGroup    : 'firstGridDDGroup',

    copy       : true,

    notifyDrop : function(ddSource, e, data){



      // Generic function to add records.

      function addRow(record, index, allItems) {



        // Search for duplicates

        var foundItem = firstGridStore.findExact('name', record.data.name);

        // if not found

        if (foundItem  == -1) {

          firstGridStore.add(record);



          // Call a sort dynamically

          firstGridStore.sort('name', 'ASC');



          //Remove Record from the source

          ddSource.grid.store.remove(record);

        }

      }



      // Loop through the selections

      Ext.each(ddSource.dragData.selections ,addRow);

      return(true);

    }

  });





  // This will make sure we only drop to the view container

  var secondGridDropTargetEl = secondGrid.getView().el.dom.childNodes[0].childNodes[1]



  var destGridDropTarget = new Ext.dd.DropTarget(secondGridDropTargetEl, {

    ddGroup    : 'secondGridDDGroup',

    copy       : false,

    notifyDrop : function(ddSource, e, data){



      // Generic function to add records.

      function addRow(record, index, allItems) {



        // Search for duplicates

        var foundItem = secondGridStore.findExact('name', record.data.name);

        // if not found

        if (foundItem  == -1) {

          secondGridStore.add(record);

          // Call a sort dynamically

          secondGridStore.sort('name', 'ASC');



          //Remove Record from the source

          ddSource.grid.store.remove(record);

        }

      }

      // Loop through the selections

      Ext.each(ddSource.dragData.selections ,addRow);

      return(true);

    }

  });

});

</script>
<div id="panel" style="scroll:auto"></div>


</apex:page>


output:
====


Changing the colors for each cell in the pageblocktable

Here,

I have an object Employeetest__c with fields Name(Text),Status__c(check box) and Salary__c(Number)

Now  i want to change the color of each cell under the Salary column based on condition(for eg:if "salary<5000 then red color otherwise blue etc..) and placing the String literal for each cell under the Status column. (when checkbox is  checked it should be "Active" otherwise "InActive").

For i am writing a controller below:


public class employeetestController{

    public List<Employeetest__c> lstemp=new List<Employeetest__c>();
 
 
    public List<Employeetest__c> getrecs(){
 
        lstemp=[select name,salary__c,status__c from Employeetest__c];
        return lstemp;
 
    }
}

I am writing visualforce page using the above controller as shown below:


<apex:page controller="employeetestController"  sidebar="false">
<apex:form >
<apex:pageBlock >
<apex:pageblocktable value="{!recs}" var="e">
<apex:column value="{!e.name}"/>

<apex:column >
<apex:facet name="header">Salary</apex:facet>
<div style="background-color:{!If(e.Salary__c>=7000 &&    e.Salary__c<10000,'#7CFC00',If(e.Salary__c>=10000 && e.Salary__c<100000,'#DEB887','#DC143C'))}">
{!e.Salary__c}
</div>
</apex:column>
<apex:column >
<apex:facet name="header">Status</apex:facet>
<div>
     {!IF(e.Status__c==true,'Active','InActive')}
</div>
</apex:column>
</apex:pageblocktable>
</apex:pageBlock>
</apex:form>
 </apex:page>






Displaying Opportunities Amount Sums for All Accounts per year and months(Aggregate Query with multiple groupings)

Here we are displaying the all accounts with opportunities amounts sum for different months in a year.

Here in the following controller (class) i just used aggregate with grouping of Account Name,Calendar Month of closedate ,Calendar year of closed date.

I am using static year 2013 we can pass dynamically and we can get results with the same code.

Its very helpful if we need more than one grouping.

Controller for this:
==============
Account with Opportunity Sum for every month
========================

public  class Accountwithopportunitiesamountcls {
    public integer year{get;set;}
    public List<Amountcls> accountamountlst{get;set;}
    Set<String> accnames=new Set<String>();
    public Accountwithopportunitiesamountcls(){
        accountamountlst=new List<Amountcls>();
        year=2013;
        Amountcls amountobj=new Amountcls();       
        amountobj.accountName='Total';
        for(AggregateResult agtobj:[select Sum(Amount) sum,Calendar_Month(closedate) month,Calendar_year(closedate) year,Account.Name acname
            from Opportunity where Calendar_year(closedate)=:year group by Calendar_Month(closedate),Calendar_year(closedate),Account.Name]){
                Amountcls accobj=new Amountcls();
                if(!accnames.contains((String)agtobj.get('acname'))){
                    accnames.add((String)agtobj.get('acname'));
                    accobj.accountname=(String)agtobj.get('acname');
                    if(agtobj.get('month')==1){
                        accobj.jan= integer.valueof(agtobj.get('sum'));
                        if(amountobj.jan!=null)
                            amountobj.jan+=accobj.jan!=null?accobj.jan:0;
                        else
                            amountobj.jan=accobj.jan!=null?accobj.jan:0;
                    }
                   
                    if(agtobj.get('month')==2){
                        accobj.feb= integer.valueof(agtobj.get('sum'));
                        if(amountobj.feb!=null)
                            amountobj.feb+=accobj.feb!=null?accobj.feb:0;
                        else
                            amountobj.feb=accobj.feb!=null?accobj.feb:0;
                        //amountobj.feb+=accobj.feb;                       
                    }
                    if(agtobj.get('month')==3){
                        accobj.mar= integer.valueof(agtobj.get('sum'));
                        if(amountobj.mar!=null)
                            amountobj.mar+=accobj.mar!=null?accobj.mar:0;
                        else
                            amountobj.mar=accobj.mar!=null?accobj.mar:0;
                        //amountobj.mar+=accobj.mar;                   
                    }
                    if(agtobj.get('month')==4){
                        accobj.apr= integer.valueof(agtobj.get('sum'));
                        if(amountobj.apr!=null)
                            amountobj.apr+=accobj.apr!=null?accobj.apr:0;
                        else
                            amountobj.apr=accobj.apr!=null?accobj.apr:0;
                    }
                    if(agtobj.get('month')==5){
                        accobj.may= integer.valueof(agtobj.get('sum'));
                        if(amountobj.may!=null)
                            amountobj.may+=accobj.may!=null?accobj.may:0;
                        else
                            amountobj.may=accobj.may!=null?accobj.may:0;
                       
                    }
                    if(agtobj.get('month')==6){
                        accobj.jun= integer.valueof(agtobj.get('sum'));
                        if(amountobj.jun!=null)
                            amountobj.jun+=accobj.jun!=null?accobj.jun:0;
                        else
                            amountobj.jun=accobj.jun!=null?accobj.jun:0;
                    }
                    if(agtobj.get('month')==7){
                        accobj.jul= integer.valueof(agtobj.get('sum'));
                        if(amountobj.jul!=null)
                            amountobj.jul+=accobj.jul!=null?accobj.jul:0;
                        else
                            amountobj.jul=accobj.jul!=null?accobj.jul:0;
                    }
                    if(agtobj.get('month')==8){
                        accobj.aug= integer.valueof(agtobj.get('sum'));
                        if(amountobj.aug!=null)
                            amountobj.aug+=accobj.aug!=null?accobj.aug:0;
                        else
                            amountobj.aug=accobj.aug!=null?accobj.aug:0;
                    }
                    if(agtobj.get('month')==9){
                        accobj.sep= integer.valueof(agtobj.get('sum'));
                        if(amountobj.sep!=null)
                            amountobj.sep+=accobj.sep!=null?accobj.sep:0;
                        else
                            amountobj.sep=accobj.sep!=null?accobj.sep:0;
                    }
                    if(agtobj.get('month')==10){
                        accobj.oct= integer.valueof(agtobj.get('sum'));
                        if(amountobj.oct!=null)
                            amountobj.oct+=accobj.oct!=null?accobj.oct:0;
                        else
                            amountobj.oct=accobj.oct!=null?accobj.oct:0;   
                    }
                    if(agtobj.get('month')==11){
                        accobj.nov= integer.valueof(agtobj.get('sum'));
                        if(amountobj.nov!=null)
                            amountobj.nov+=accobj.nov!=null?accobj.nov:0;
                        else
                            amountobj.nov=accobj.nov!=null?accobj.nov:0;   
                    }
                    if(agtobj.get('month')==12){
                        accobj.dec= integer.valueof(agtobj.get('sum'));
                        if(amountobj.dec!=null)
                            amountobj.dec+=accobj.dec!=null?accobj.dec:0;
                        else
                            amountobj.dec=accobj.dec!=null?accobj.dec:0;   
                    }  
                   
                    accobj.total=(accobj.jan!=null?accobj.jan:0)+(accobj.feb!=null?accobj.feb:0)+(accobj.mar!=null?accobj.mar:0)+(accobj.apr!=null?accobj.apr:0)+(accobj.may!=null?accobj.may:0)+
                            +(accobj.jun!=null?accobj.jun:0)+(accobj.jul!=null?accobj.jul:0)+(accobj.aug!=null?accobj.aug:0)
                            +(accobj.sep!=null?accobj.sep:0)+(accobj.oct!=null?accobj.oct:0)+(accobj.nov!=null?accobj.nov:0)
                            +(accobj.dec!=null?accobj.dec:0);
                    if(amountobj.total!=null){
                        amountobj.total+=accobj.total!=null?accobj.total:0;
                    }
                    else{
                        amountobj.total=accobj.total!=null?accobj.total:0;
                    }
                    accountamountlst.add(accobj);
                }
                System.debug('accountamountlst:'+accountamountlst);
            }
            accountamountlst.add(amountobj);
    }
    public class Amountcls{
        public String accountname{get;set;}
        public integer jan{get;set;}
        public integer feb{get;set;}
        public integer mar{get;set;}
        public integer apr{get;set;}
        public integer may{get;set;}
        public integer jun{get;set;}
        public integer jul{get;set;}
        public integer aug{get;set;}
        public integer sep{get;set;}
        public integer oct{get;set;}
        public integer nov{get;set;}
        public integer dec{get;set;}
        public integer total{get;set;}
    }

}


Page Code:
==========

<apex:page controller="Accountwithopportunitiesamountcls" sidebar="false">
            <apex:form >
                        <apex:pageBlock >
                                    <apex:pageBlockTable value="{!accountamountlst}" var="acc">
                                                <apex:column headerValue="Account Name" value="{!acc.Accountname}"/>
                                                <apex:column headerValue="Jan" value="{!acc.jan}"/>               
                                                <apex:column headerValue="Feb" value="{!acc.feb}"/>              
                                                <apex:column headerValue="Mar" value="{!acc.mar}"/>              
                                                <apex:column headerValue="Apr" value="{!acc.apr}"/>   
                                                <apex:column headerValue="May" value="{!acc.may}"/>            
                                                <apex:column headerValue="Jun" value="{!acc.jun}"/>               
                                                <apex:column headerValue="Jul" value="{!acc.jul}"/>                                                                 
                                                <apex:column headerValue="Aug" value="{!acc.aug}"/> 
                                                <apex:column headerValue="Oct" value="{!acc.sep}"/>              
                                                <apex:column headerValue="Sep" value="{!acc.oct}"/>              
                                                <apex:column headerValue="Nov" value="{!acc.nov}"/>             
                                                <apex:column headerValue="Dec" value="{!acc.dec}"/>             
                                                <apex:column headerValue="Total" value="{!acc.total}"/>                       
                                    </apex:pageBlockTable>                      
                        </apex:pageBlock>                  
            </apex:form>
</apex:page>


Output:
=======



What’s the difference between Einstein Article Recommendations and Suggested Articles?

How Does Einstein Article Recommendations Work? Einstein Article Recommendations helps support agents resolve customer cases efficiently by ...