Tuesday, January 28, 2014

Salesforce to Salesforce Integration using Apex Code

Hello Friends
This time is to integrate salesforce to salesforce  using custom code. First of all let's have a brief  idea of Salesforce to Salesforce integration. Let if any salesforce org wish to share their records with another salesforce, then we need to make a connection between both org. This phenomena to make connection between  any two salesforce org is called the Salesforce to Salesforce integration. To make the connection you need to follow some steps like following :-

1. Go set up(top corner of right side).
2. Customize -> Salesforce to Salesforce
3. Enable salesforce to salesforce
4. Next go to Connection tab
5. Create a new connection with another salesforce org.
    (This link may be used to just create a new connection                                                                                   http://wiki.developerforce.com/page/An_Introduction_to_Salesforce_to_Salesforce)

If we are using the customize way to integrate salesforce to saleforce , then it may be a bit confusion  that which record has been send to the connected org. To make a separation among records like sent or not, we will use  Apex Controller, VF page, Custom Field(checkbox) , Custom detail page button(on record which you want to share with another org.).
Just for a understanding we are using Lead sObject to share.

*************************Apex Controller******************************

public class ConnectionController
{
    String id;
    public ConnectionController(ApexPages.StandardController controller)
    {
        id = (String)controller.getRecord().id;
    }
    public void sendLead()
    {
        boolean flag=false;
        List<PartnerNetworkConnection> connMap = new List<PartnerNetworkConnection>();
        connMap=[select Id, ConnectionStatus, ConnectionName from PartnerNetworkConnection   where              ConnectionName = 'TechnoMile'] ;
        Lead ld =[Select id, Send_To_Other_ORG__c From Lead where id =: id];
        for(PartnerNetworkConnection network : connMap) {
             PartnerNetworkRecordConnection newrecord = new PartnerNetworkRecordConnection();
            newrecord.ConnectionId = network.Id;
            newrecord.LocalRecordId = ld.id;
            newrecord.SendClosedTasks = true;
            newrecord.SendOpenTasks = true;
            newrecord.SendEmails = true;
            insert newrecord;
            if(newrecord.id != null)
                flag=true;
        }
        if(flag)
        {
            ld.Send_To_Other_ORG__c = true;
            update ld;
        }
       
    }
   
}



Here Send_To_Other_ORG__c is custom field of chekbox type. If this is true mean , this record has been sent to the connected org otherwise not.


***************************VF Page********************************************

<apex:page standardController="Lead" extensions="ConnectionController" action="{!sendLead}">
 
</apex:page>

This vf page will be called by a detail page button. That button will exist on the detail page of the lead.



Friday, January 24, 2014

Get all the required fields of sObject dynamically

Now time to post related to the schema in salesforce. Generally we use the following methods to use sObject in class.
                             Account acc = new Account();
But some time we need object dynamically.  In that situation we all need of Schema of Salesforce.
Here i am posting some apex code to use schema in calss.

Map<String, Schema.SObjectType> m  = Schema.getGlobalDescribe() ;
Schema.SObjectType s = m.get(so.apiName) ;
Schema.DescribeSObjectResult r = s.getDescribe() ;
Map<String,Schema.SObjectField> fields = r.fields.getMap() ;

for(String f : fields.keyset())
{
 Schema.DescribeFieldResult desribeResult = fields.get(f).getDescribe();
 if( desribeResult.isCreateable()  && !desribeResult.isNillable() && !desribeResult.isDefaultedOnCreate() )
 {
//This is mandatory / required field
 }
}

Sequence of Trigger and automation rules run in Salesforce.com

It's important to know that what thing will be executed first when any record is about insert or delete or update. So let's have a look on all execution in their execution order.

  1. Old record loaded from database (or initialized for new inserts)
  2. New record values overwrite old values
  3. System Validation Rules
  4. Before triggers 
  5. Custom Validation Rules
  6. Record saved to database 
  7. Record reloaded from database
  8. After triggers 
  9. Assignment rules
  10. Auto-response rules
  11. Workflow rules
  12. Escalation rules
  13. Parent Rollup Summary Formula value updated (if present)
  14. Database commit
  15. Post-commit logic (sending email)
  

Thursday, January 23, 2014

Merge Accounts

Hello Salesforce guys.
Now time to post something new. Today i am going to post Apex code for Merge Account. First of all the exact mean of Merge Account. As we all know that Account have related list of Contact , Opportunity , Attachment, Activity, Events and Notes(May me related list of custom object). Now we have to merge merge Contact , Opportunity , Attachment, Activity, Events and Notes(May be related list of custom object) of any two Accounts in a single Account. For example we have two Accounts A and B. We have to merge Contact , Opportunity , Attachment, Activity, Events and Notes(May be related list of custom object) of both A and B into B.
To implement this we need following Apex Controller and VF page.

VF page :- 

<apex:page controller="MergeAccount" tabStyle="Account">
 <apex:sectionHeader title="Account" subtitle="Merge"/>
  <apex:form >
      <apex:pageBlock >
          <apex:pageBlockButtons >
              <apex:commandButton value="Merge" action="{!add}"/>
         </apex:pageBlockButtons>
          FROM-:<apex:selectList value="{!selectList}" size="1">
            <apex:selectOptions value="{!options}"/> 
          </apex:selectList>
          &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
          TO-:<apex:selectList value="{!selectListTo}" size="1">
            <apex:selectOptions value="{!optionsTo}"/> 
          </apex:selectList>
      </apex:pageBlock>
  </apex:form>

</apex:page>

Controller :- 
public class MergeAccount{
    public List<Account> accListFrom {get; set;}
    public List<Account> accListTo {get; set;}
    public string selectList {get; set;}
    public string selectListTo {get; set;}
    public List<selectOption> options {get; set;}
    public List<selectOption> optionsTo {get; set;}
    Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();
    public List<String> SelectedFields {get; set;}
    public Account acc {get; set;}
    public Account accTo {get; set;}
    public Test__c tec {get; set;}
    public MergeAccount(){
        accListFrom = new List<Account>();
        accListTo = new List<Account>();
        options = new List<selectOption>();
        optionsTo = new List<selectOption>();
        SelectedFields = new List<String>() ;
        accListFrom = [select id, name from account];
        accListTo = [select id, name from account];
        
        for(Account ac : accListFrom){
            options.add(new selectOption(ac.id, ac.name));
        }
        for(Account ac : accListTo){
            optionsTo.add(new selectOption(ac.id, ac.name));
        }
        
    }
    public Pagereference add(){
        List<Contact> conFrom = new List<Contact>();
        conFrom = [select id, name, AccountId from contact where AccountId =: selectList];
        if(conFrom.size() > 0){
            for(Contact con : conFrom){
                con.AccountId = selectListTo;
            }
        }
        update conFrom;
        List<Opportunity> oppList = new List<Opportunity>();
        oppList = [select id, name , AccountId from Opportunity where AccountId =: selectList];
        if(oppList.size() > 0){
            for(Opportunity opp : oppList){
                opp.AccountId = selectListTo;
            }
        }
        update oppList;
        List<Case> ca = new List<Case>();
        ca = [select id,  AccountId from case where AccountId =: selectList];
        if(ca.size() > 0){
            for(Case cs : ca){
                cs.AccountId = selectListTo;
            }
        }
        update ca;
        List<Task> tsk = new List<Task>();
        tsk = [select id, AccountId, WhatId from task where AccountId =: selectList];
        if(tsk.size() > 0){
            for(task tk : tsk){
                tk.WhatId = selectListTo;
            }
        }
        update tsk;
        List<Event> evnt = new List<Event>();
        evnt = [select id, AccountId, whatId from event where AccountId =: selectList];
        if(evnt.size() > 0){
            for(Event ev : evnt){
                ev.whatId = selectListTo;
            }
        }
        update evnt;
        List<Attachment> attach = new List<Attachment>();
        attach = [select id, name , parentid, body from Attachment where parentId =: selectList];
        List<Attachment> attachmnt = new List<Attachment>();
        if(attach.size() > 0){
            for(Attachment att : attach){
                Attachment attch = new Attachment();
                attch.body = att.body;
                attch.name = att.name;
                attch.Parentid = selectListTo;
                attachmnt.add(attch);
            }
            insert attachmnt;
            delete attach;
        List<Note> notes = new List<Note>(); 
        notes =  [select id,   parentid, body, title from Note where parentId =: selectList]; 
        List<Note> noter = new List<Note>(); 
        if(notes.size() > 0){
            for(Note nt : notes){
                Note nts = new Note();
                nts.body = nt.body;
                nts.title = nt.title;
                nts.parentId = selectListTo;
                noter.add(nts);
            }
            insert noter;
            delete notes;
        } 
        }    
        return null;
    }
    

}

CSS in Vf page

Hello
Some time we guys need to make website in salesforce. To implement that requirement we use site.com. The pages what are added in site.com may be accessed publicly. Each page of the website requires some css to make attractive look. So having  this type of requirement in mind i am going to post the vf page code. In this page you will be able to use mouseOn and menuOff. This post is aslo helpful to use javascript in the vf page. Using the java script you will be able to show a time bar on vf page according to the Country.

<apex:page sidebar="false" showHeader="false">
  <apex:form >
  <apex:stylesheet value="{!$Resource.StyleCss}"/>
  <apex:includeScript value="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"/>
  <apex:includeScript value="http://techtricky.com/wp-content/jquery/jquery.jclock.js"/>
   <script type="text/javascript">
         $(document).ready(
             function() {
           //$('#time').jclock();
           $("#zones").change(function(){
           if ($('#time-cont .time').length>0){ $('#time-cont .time').remove();}
           var offset = $(this).val();  
           if (offset == '') return;    
           $('#time-cont').append('<div class="time"></div>');
            var options = {
            format:'<span class=\"dt\">%A, %d %B %I:%M:%S %P</span>',
            timeNotation: '12h',
            am_pm: true,
            fontFamily: 'Verdana, Times New Roman',
            fontSize: '20px',
            foreground: 'black',
            background: 'yellow',
            utc:true,
            utc_offset: offset
          }
         
          $('#time-cont .time').jclock(options);
     
           });
     });
    </script>
 
 <style>
    td.menuon { background-color: #0000FF;  }
    td.menuoff { background-color: #00008B;  }
     table tr td a font{
   
       backgroundcolor:# white;
     }
   
     table tr td a font: hover{
   
         backgroundcolor:#0000FF;
      }
      a.changeBlue:link { /* default link color */
      color: white;
        }
        a.changeBlue:hover { /* change to blue on mouseover */
             color: pink;
}
</style>
  <table bgcolor="yellow" width="100%" style="position:fixed;">
      <tr>
          <td>
              <center><table border="0" width= "80%">
                  <tr>
                      <td style="width:400px">
                          <apex:commandButton image="{!$Resource.FbImage}"/>&nbsp;&nbsp;
                          <apex:commandButton image="{!$Resource.twitterImage}"/>&nbsp;&nbsp;
                          <apex:commandButton image="{!$Resource.LinkedInImage}"/>
                      </td>
                     <td align="center" bgcolor="#DC143C">
                         <a class="changeBlue" href="#" style="text-decoration: none;"><font face="Blackadder                                    ITC" size="4">services</font></a>
                     </td>
                      <td align="center" bgcolor="#DC143C">
                         <a class="changeBlue" href="#" style="text-decoration: none;"><font face="Blackadder                                  ITC" size="4">trablehe cansio</font></a>
                     </td>
                      <td align="center" bgcolor="#DC143C">
                         <a class="changeBlue" href="#" style="text-decoration: none;"><font face="Blackadder                                  ITC" size="4">portal do cleinte</font></a>
                     </td>
                      <td align="center" bgcolor="#DC143C">
                         <a class="changeBlue" href="#" style="text-decoration: none;"><font face="Blackadder                                   ITC" size="4">contacto</font></a>
                     </td>
                  </tr>
              </table>
             </center>
          </td>
      </tr>
  </table><br/><br/><br/><br/><br/><br/>
  <center><table>
   <tr>
   <td>
   <select id="zones">
    <option value="">--Select--</option>
    <option value="10">Australia</option>
    <option value="-3">Brazil</option>
    <option value="-5">Canada</option>
    <option value="8">China</option>
    <option value="1">Germany</option>
    <option value="5.5">India</option>
    <option value="9">Japan</option>
    <option value="8">Malaysia</option>
    <option value="12">Newzealand</option>
    <option value="0">UK</option>
    <option value="-5">US EST</option>
</select>
<div id="time-cont"></div>
</td></tr></table></center>
  <center><table width="80%">
       <tr>
          <td style="width:400px">
              <apex:image value="{!$Resource.Aimage}" height="100" width="100"/>
          </td>
          <td>
           <table border="0" width="100%" >
            <tr>
              <td align="center" class="menuoff" onmouseover="className='menuon';"                                                        onmouseout="className='menuoff';">
                     <a href="#" style="text-decoration: none;"><font color="white" size="3">initial</font></a>
              </td>
              <td align="center" class="menuoff" onmouseover="className='menuon';"                                                         onmouseout="className='menuoff';">
                     <a href="#" style="text-decoration: none;"><font color="white" size="3">queem somas</font></a>
              </td>
              <td align="center" class="menuoff" onmouseover="className='menuon';"                                                            onmouseout="className='menuoff';">
                     <a href="#" style="text-decoration: none;"><font color="white" size="3">flag</font></a>
              </td>
              <td align="center" class="menuoff" onmouseover="className='menuon';"                                                            onmouseout="className='menuoff';">
                     <a href="#" style="text-decoration: none;"><font color="white" size="3">portfolio</font></a>
              </td>
           </tr>
          </table>    
        </td>
      </tr>
  </table></center>
  <center><table>
   
      <tr>
          <td>
              <font color="#8B008B" size="6">Bem Vindo</font><br/>
              &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
              &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
              <font color="#FF8C00" size="6">ao futro</font><br/>
              <font color="#4169E1" size="6">em gesto de negocias</font>
          </td>
          <td>
              <apex:image value="{!$Resource.Proffesion}" height="300" width="400"/>
          </td>
      </tr>
   </table></center>
   <table border="0" bgcolor="#0000FF" width="100%" >
     <tr>
      <td>
       <center>
       <table border="1" bgcolor="#0000FF" width="80%">
       <tr>
           <td align="center">
               <font  color="yellow" size="3">Salesforce CRM</font><br/>
               <apex:image value="{!$Resource.network}" height="100" width="100"/><br/>
               <font color="white" size="1">Tenha uma visão 360° de tudo o que está acontecendo na sua empresa.</font>
             
           </td>
           <td align="center">
               <font face="Blackadder ITC" color="yellow" size="3">Business Intelligency</font><br/>
               <apex:image value="{!$Resource.BrainImage}" height="100" width="100"/><br/>
               <font color="white" size="1">Mensure os resultados do seu negócio em tempo real com indicadores de desempenho.</font>
           </td>
           <td align="center">
               <font style="font-family: DakotaRegular" color="yellow" size="3">Marketing BPO</font><br/>
               <apex:image value="{!$Resource.bulbimage}" height="100" width="100"/><br/>
               <font color="white" size="1">A Atile.branding possui uma equipe de profissionais especializados para servir sua empresa da maneira mais eficiente possível.</font>
           </td>
           <td align="center">
               <font color="yellow" size="3">Desimolvimento web</font><br/>
               <apex:image value="{!$Resource.searchimage}" height="100" width="100"/><br/>
               <font color="white" size="1">Equipes treinadas e preparadas para a solução que a sua empresa precisa..</font>
           </td>
       </tr>
       </table>
       </center>
       </td>
      </tr>
   </table>
 </apex:form>
</apex:page>


For Demo Use Following Link:-
http://vikasgaur-developer-edition.ap1.force.com/AtilePage

Wednesday, January 22, 2014

PickList controller via Apex

Here i am going to post the apex code to make pickList dependencies. Some time it we need to show a contacts of related account. Then we can use pickList dependencies

VF page :-
<apex:page controller="PicklistController">
  <apex:sectionHeader title="Picklist dependency"/>
  <apex:form id="frm">
      <apex:actionFunction name="change" action="{!con}" status="status" reRender="frm"/>
      <apex:actionStatus startText="Please wait" id="status"></apex:actionStatus>
      <apex:pageBlock >
          Account : <apex:selectList value="{!selectList}" size="1" onchange="change(); return false;">
                      <apex:selectOptions value="{!accts}">
                      </apex:selectOptions>
                    </apex:selectList><br/><br/><br/>
         contact : <apex:selectList value="{!selectList1}" size="1">
                      <apex:selectOptions value="{!options1}">
                      </apex:selectOptions>
                    </apex:selectList>        
      </apex:pageBlock>
  </apex:form>
</apex:page>

Apex Controller  :-

//class..
public class PicklistController{
    List<Account> acc {get; set;}
    public string selectlist {get; set;}
    public string selectlist1 {get; set;}
    public  List<selectOption> options {get; set;}
    public  List<selectOption> options1 {get; set;}
    //constructor...
    public PicklistController(){
        acc = new List<Account>();
        acc = [select id , name from account];
     }
    public List<selectOption> getaccts(){
        options = new List<selectOption>();
        options.add(new selectOption('', '- None -'));
        for(Account ac : acc){
            options.add(new selectOption(ac.id, ac.Name));
        }
        return options;
    }
    public pagereference con(){
        options1 = new List<selectOption>();
        options1.add(new selectOption('', '- None -'));
        for(contact cont : [select id, name from contact where contact.accountid =: selectlist]){
            options1.add(new selectOption(cont.id, cont.Name));
        }
        return null;
    }

}