Monday, October 6, 2014

Case Team via Apex

Hello Guys,

I am back with new topic. This time we all are going to discuss about Case Team Via Apex. So first of all let's brief discussion on  Case Team.
 A case team is a team of users that work together on a case. For example, your case team may include a support rep, support manager, and a product manager.

So the requirement is that whenever a new case is created then creator should be added in Case Team.
The user who edit the case , will be added on that case based on last modified.

To implement this you will need following two main things

  1.  Case Team Roles 
  2.  Related List of Case Team in Case detail page.  


trigger addTeamMembers on Case (after insert, After Update) {
   User Us = [SELECt id, name , profile.name from User WHERE id =: UserInfo.getUserId( )];
   if(checkRecursive.runOnce()){
   if(us.profile.name != 'TM Customer Community Login'){
       Map<Id, CaseTeamMember> membersToAdd = new Map<Id, CaseTeamMember>();
       if(trigger.isAfter){
            List<Case> cases = [Select Id,OwnerId, LastModifiedById from Case where id IN :Trigger.newMap.keySet()];
            if(trigger.IsInsert){
                for (Case c : cases) {
                      membersToAdd.put(c.Id, new CaseTeamMember(ParentId = c.Id, MemberId = UserInfo.getUserId( )));
                }
            }
            if(trigger.IsUpdate){
               for (Case c : cases) {
                      membersToAdd.put(c.Id, new CaseTeamMember(ParentId = c.Id, MemberId = c.LastModifiedById));
                } 
            }    
            if (!membersToAdd.isEmpty()) {
              try {
                CaseTeamRole caseTeamRole = [SELECT Id FROM CaseTeamRole WHERE Name = 'Immerti' LIMIT 1];
        
                for (CaseTeamMember ctm : membersToAdd.values()) {
                  ctm.TeamRoleId = caseTeamRole.Id;
                }
              for (CaseTeamMember ctm : [SELECT Id, MemberId, ParentId FROM CaseTeamMember
                                           WHERE ParentId IN :membersToAdd.keySet()
                                           AND MemberId = :UserInfo.getUserId()
                                           ORDER BY ParentId]) {
                 if (membersToAdd.containsKey(ctm.ParentId)) {
                    membersToAdd.remove(ctm.ParentId);
                  }
                }
                
                if (!membersToAdd.isEmpty()) {
                  insert membersToAdd.values();
                }
              } catch (System.QueryException qe) {}
           }
        }
      }else{
           User u1 = [SELECT id, name from User WHERE name = 'Carla Martin'];
           User u = [SELECT id, name from User WHERE name = 'Zina Sejdic'];
           set<Id> csId = new set<Id>();
           if(trigger.isInsert){
           if(trigger.isAfter){
               for(Case c : trigger.new){
                   csId.add(c.id);  
               }
             if(csId.size() > 0){
                  Case cs = [SELECT id, ownerId from case WHERE id IN : csId];
                  cs.ownerId = u1.id;
                  update cs;
                  CaseTeamRole caseTeamRole = [SELECT Id FROM CaseTeamRole WHERE Name = 'Immerti' LIMIT 1];
                  CaseTeamMember tm = new CaseTeamMember();
                  tm.ParentId = cs.id;
                  tm.MemberId = u.id;
                  tm.TeamRoleId = caseTeamRole.id;
                  insert tm;
            }     
          }
        }
     }
   } 
}






~Vikas

Thursday, March 13, 2014

Sorting Table Using Apex

Hey guys, i am back to blog  with sorting table.
In standard UI of salesforce, if we are looking any list view, then salesforce provides the sorting in both way(ASC && DESC). The same functionally may be achieved using apex. Here i am going to write the code of Sorting the table using the Apex Class and VF page.


********************Controller**************************

public class SortTableController{
    public List<Account> acc {get; set;}
    public string uparr {get; set;}
    public boolean NameUpArrow {get; set;}
    public boolean NameDownArrow {get; set;}
    public boolean TypeDownArrow {get; set;}
    public boolean TypeUpArrow {get; set;}
    public boolean CreateDownArrow {get; set;}
    public boolean CreateUpArrow {get; set;}
    Public integer i {get; set;}
    Public integer j {get; set;}
    Public integer k {get; set;}
    public SortTableController(){
        acc = new List<Account>();
        acc = [select id , name , createddate, type from account];
        uparr = '&darr;';
        NameUpArrow = false;
        NameDownArrow = false;
        TypeUpArrow = false;
        TypeDownArrow = false;
        CreateUpArrow = false;
        CreateDownArrow = false;
        i = 0;
        j = 0;
        k = 0;
    }
    //sort by name....
    public pagereference NameSort(){
        TypeUpArrow = false;
        TypeDownArrow = false;
        CreateUpArrow = false;
        CreateDownArrow = false;
        if(i == 0){
            NameDownArrow = true;
            NameUpArrow = false;
        }else if(i == 1){
            NameUpArrow = true;
            NameDownArrow = false;
        }
        if(NameDownArrow == true){
            acc = [select id , name , createddate, type from account Order By Name ASC];
            i = 1;
            NameUPArrow = false;
        }else if(NameUpArrow == true){
            acc = [select id , name , createddate, type from account Order By Name DESC];
            i = 0;
            NameDownArrow = false;
        } 
        return null;
    }
    //sort by type....
    public pagereference TypeSort(){
        NameUpArrow = false;
        NameDownArrow = false;
        CreateUpArrow = false;
        CreateDownArrow = false;
        if(j == 0){
            TypeDownArrow = true;
            TypeUpArrow = false;
        }else if(j == 1){
            TypeUpArrow = true;
            TypeDownArrow = false;
        }
        if(TypeDownArrow == true){
            acc = [select id , name , createddate, type from account Order By type ASC];
            j = 1;
            TypeUPArrow = false;
        }else if(TypeUpArrow == true){
            acc = [select id , name , createddate, type from account Order By Type DESC];
            j = 0;
            TypeDownArrow = false;
        } 
        return null;
    }
    //sort by created date....
    public pagereference CreateSort(){
        NameUpArrow = false;
        NameDownArrow = false;
        TypeUpArrow = false;
        TypeDownArrow = false;
        if(k == 0){
            CreateDownArrow = true;
            CreateUpArrow = false;
        }else if(k == 1){
            CreateUpArrow = true;
            CreateDownArrow = false;
        }
        if(CreateDownArrow == true){
            acc = [select id , name , createddate, type from account Order By CreatedDate ASC];
            k = 1;
            CreateUPArrow = false;
        }else if(CreateUpArrow == true){
            acc = [select id , name , createddate, type from account Order By CreatedDate DESC];
            k = 0;
            CreateDownArrow = false;
        } 
        return null;
    }
    
}
*****************************Page*****************************

<apex:page controller="SortTableController">
  <apex:form >
      <apex:pageBlock >
          <table width="60%" border="0">
              <tr>
                  <th>
                      <apex:commandLink value="Name" action="{!NameSort}"/>
                      <apex:image value="{!$Resource.UpArrow}" width="10px" height="10px" rendered="{!NameUpArrow}"></apex:image>
                      <apex:image value="{!$Resource.DownArrow}" width="10px" height="10px" rendered="{!NameDownArrow}"></apex:image>
                  </th>
                  <th>
                      <apex:commandLink value="Type" action="{!TypeSort}"/>
                      <apex:image value="{!$Resource.UpArrow}" width="10px" height="10px" rendered="{!TypeUpArrow}"></apex:image>
                      <apex:image value="{!$Resource.DownArrow}" width="10px" height="10px" rendered="{!TypeDownArrow}"></apex:image>
                  </th>
                  <th>
                      <apex:commandLink value="Created Date" action="{!CreateSort}"/>
                      <apex:image value="{!$Resource.UpArrow}" width="10px" height="10px" rendered="{!CreateUpArrow}"></apex:image>
                      <apex:image value="{!$Resource.DownArrow}" width="10px" height="10px" rendered="{!CreateDownArrow}"></apex:image>
                  </th>
              </tr>
              <apex:repeat value="{!acc}" var="ac">
                  <tr>
                      <td>
                          <apex:outputfield value="{!ac.name}"/>
                      </td>
                      <td>
                          <apex:outputfield value="{!ac.type}"/>
                      </td>
                      <td>
                          <apex:outputfield value="{!ac.createddate}"/>
                      </td>
                  </tr>
             </apex:repeat>
         </table>
     </apex:pageBlock>
  </apex:form>
</apex:page>


For live demo please visit http://vickygaur-developer-edition.ap1.force.com/SortTable

Thursday, February 6, 2014

Email services

Welcome guys to this blog.
This time we are going to discuss on the Email services in the salesforce. Salesforce provides the facility to create the new record using the Email service.  We will see the example of creating case and case comment by using the Email service. To implement this functionality we need three thing as Apex Controller, Enabled Email Service, Apex Trigger on CaseComment object in any salesforce org. So let's start.
To create the email service we need a apex controller same as the the following.

**********************Controller************************************

global class emails implements Messaging.InboundEmailHandler{
      global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email,     Messaging.InboundEnvelope envelope) {
          Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();
          string subject1 = email.subject;
          string body = email.plainTextBody;
          Attachment attachment = new Attachment();
          string sender = email.fromAddress;
          string st = body;
          string cname = email.fromName;
          string sub;
          List<contact> contacts;
          contacts = new List<contact>();
          List<case> cases;
          cases = new List<case>();
          contacts =[select id, Email,Account.ID, Name from contact where Email =: sender limit 1];
          if(subject1.contains('Re:')){
              integer i = subject1.length();
              sub = subject1.substring(4,i);
          }else{
              sub = subject1;
          }
         if(contacts.size()>0){       
                for(contact con : contacts){
                      if(con.id != null)
                      {
                         cases = [select id, CaseNumber from case];
                         for(case c : cases)
                         {
                             if(c.CaseNumber.contains(sub))
                             {
                                 c.subject=subject1;
                                 c.caseIdentifier__c = false;
                                 c.Description=body;
                                 c.Status='Working';
                                 c.Origin='Email';
                                 c.Severity__c='<-----None--->';
                                 c.Reported_at__c=c.CreatedDate;
                                 update c;
                               
                                    CaseComment cc = new CaseComment(ParentId=c.Id,CommentBody=st,IsPublished=true);
                                    insert cc;
                          
                                    if(email.TextAttachments !=null){
                                       for (Messaging.Inboundemail.TextAttachment tAttachment : email.textAttachments) {  
                                            attachment.Name = tAttachment.fileName;  
                                            attachment.Body = Blob.valueOf(tAttachment.body);  
                                            attachment.ParentId = c.Id;  
                                            insert attachment;  
                                       }
                                    }  
                                   if(email.BinaryAttachments !=null){
                                        for (Messaging.Inboundemail.BinaryAttachment ttAttachment : email.BinaryAttachments) {  
                                            attachment.Name = ttAttachment.fileName;  
                                            attachment.Body = ttAttachment.body;  
                                            attachment.ParentId = c.Id;  
                                            insert attachment;  
                                        }  
                                   }
                                   return result;
                           }
                          }
                    if(con.Email == sender)
                    {
                        case cs = new case(contactID=con.ID,description=body,origin='email',Severity__c='None',status='new');
                        insert cs;
                        CaseComment cc1 = new CaseComment(ParentId=cs.Id,CommentBody=st.abbreviate(4000),IsPublished=true);
                        insert cc1;
                         
                    }
          }
        
        }
        }
        else
        {
              contact c;
              c = new contact();
              c.LastName =cname;
              c.subjects__C = 'java';
              c.Email=sender;
              insert c;
              
              case cs1 = new case(contactID=c.ID,description=body,origin='email',status='new');
              insert cs1;
               
        }
          return result;
      }
      
  }

********************************Controller************************************

After saving that controller we need to make the Email Service in the salesforce. To create the email service in the salesforce you have to move as setup -> App setUp -> develop -> Email service . Just click on the New Service . When you are going to create the email service  you will see that there is an option to add the
Apex class. In that option we will add our above class. When you finished the process of creating the Email Service , you will get an address. Thar address should be added in gmail account as Forward Message which gmail account is being in the Salesforce org.

When you send email to this address a new Case and a new Contact will be created in the salesforce org. That contact will be associated that case.
This is the first step. In next step we will see that when we add a comment in Case comment of the salesforce, then an email will be sent to the contact who is associated with this case. That contact will receive an email . If that contact send any reply to that email , then new comment will be created in same case in the salesforce and the process is so on.
To implement the second step we need to write a trigger on the CaseComment object in salesforce.

***************************trigger*********************************************

 trigger casetest on CaseComment (after insert) {
    set<Id> caseId = new set<Id>();
    set<Id> conId = new set<Id>();
    set<Id> conId1 = new set<Id>();
    list<CaseComment> lst = new list <CaseComment>();
    Id contId;
    string caseNo;
    boolean flag;
    string comment;
    for(CaseComment cs : trigger.new){
        caseId.add(cs.Id);
       
    }
     if(CaseId.size() > 0){
    
    lst = [select id,commentbody,parentid from CaseComment where id in :caseId];
    }
    
    if(lst.size()>0){
    
    for(CaseComment css: lst){
    
    conId1.add(css.parentid);
    
     comment = css.commentBody;
    
    }
    }
    List<case> cse = new List<case>();
    if(conId1.size() > 0){
        List<case> cases = new List<case>();
        cases = [select id, casenumber, contactId, caseIdentifier__c,description         from case where id in : conId1];
        if(cases.size() > 0){
            for(case cs : cases){
            system.debug('ajit'+ comment +'ajit1'+cs.description);
            if(cs.description==null){
            
            caseNo = cs.caseNumber;
                contId = cs.contactId;
               flag = true;
            
            
            }
            else{
              if(comment.equals(cs.description)==false ){
                caseNo = cs.caseNumber;
                contId = cs.contactId;
               flag = true;

               }  
               }
            }
            
        }
       
    } 
    if(flag == true){
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setSubject(caseNo);  
        mail.setTargetObjectId(contId);
        mail.setreplyTo('my_email_services@2hpulp0pv93g3rbe2ng8dzw0ocs0wzyupuemgncw5cnhjoiffg.9-gjk7eaa.9.apex.salesforce.com');
        mail.setSaveAsActivity(false);
        mail.setHtmlBody(comment);
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail }); 
     }   
}
So in above blog we saw that how to create a new case and casecomment in salesforce using Email service.
If you any doubt or issue then let me know.

Monday, February 3, 2014

Email Services via Apex code

Today i am going to introduce the the email services via Apex code in salesforce. Some time we need to send an email via vf page . That time we need of Cc , Bcc. Here i will post the code what will be used to create  the email service using Apex code.
Here  i am adding on more thing to send the in email that List of Account. Account is just for an example. In the same process we can send also the another object's records.


*************************VF page****************************************

<apex:page showHeader="false" sidebar="false" standardStylesheets="false" controller="EmailSendController">
   <apex:form id="frm">
          <apex:actionFunction name="addmeAccount" action="{!sendAccount}" status="status">
            <apex:param name="index" value="" assignTo="{!Index}"/>
          </apex:actionFunction>
          <apex:actionStatus id="status">
                <apex:facet name="start">
                <div style="width: 500px;">
                <img src="/img/loading24.gif" style="vertical-align:middle;margin-left:50px;"/>
                <span style="margin-left:10px; font-size: 12px; font-weight: bold; color: #000000;">Please wait...</span>
                </div>
                </apex:facet>
          </apex:actionStatus>
          <table border="0"  width="40%" align="center" cellspacing="0" cellpadding="0">
             <tr bgcolor="#222222">
                 <td  width="90%" colspan="4">
                     <b><font size="3" color="White">New Message</font></b>
                 </td>
                 <td align="right" colspan="4">
                     <apex:image value="{!$Resource.Minusimage}" width="15px" height="15px" title="Minimize"/>
                 </td>
                 <td align="right" colspan="4">
                     <apex:image value="{!$Resource.MultiplyImage}" width="15px" height="15px" title="Close"/>
                 </td>
             </tr>
          </table><br/>
          <table border="0"  width="40%" align="center" cellspacing="0" cellpadding="2">
             <tr>
                 <td width="14%">
                     <b><font size="3" color="#2F4F4F">To</font></b>
                 </td>
                 <td width="90%">
                     <apex:inputText size="80" value="{!to}"/>
                 </td>  
                 <td width="14%">
                     <apex:commandLink value="Cc" action="{!mailcc}"/>
                 </td>
                 <td width="5%">
                     <apex:commandLink value="Bcc" action="{!mailbcc}"/>
                 </td>
             </tr>
             <apex:pageBlock rendered="{!cc}" id="mecc">
                 <tr>
                     <td width="5%" rowspan="4">
                         <b><font size="3" color="#2F4F4F">Cc</font></b>
                     </td>
                     <td width="90%" rowspan="4">
                         <apex:inputText size="80" value="{!addcc}"/>
                     </td>
                 </tr>
             </apex:pageBlock>
           </table>
           <table border="0"  width="40%" align="center" cellspacing="0" cellpadding="2">
              <apex:pageBlock rendered="{!bcc}">
                 <tr>
                     <td width="9%" rowspan="4">
                         <b><font size="3" color="#2F4F4F">Bcc</font></b>
                     </td>
                     <td width="90%" rowspan="4">
                         <apex:inputText size="80" value="{!addBcc}"/>
                     </td>
                 </tr>
             </apex:pageBlock>  
         </table>
         <table border="0"  width="40%" align="center" cellspacing="0" cellpadding="2">
             <tr>
                 <td width="9%">
                         <b><font size="3" color="#2F4F4F">Subject</font></b>
                 </td>
                 <td width="90%" >
                         <apex:inputText size="80" value="{!sub}"/>
                 </td>
             </tr>
             <tr>
                 <td colspan="2">
                     <apex:inputTextarea richText="true" value="{!body}"/>
                 </td>
             </tr>
         </table>
         <table border="0"  width="40%" align="center" cellspacing="0" cellpadding="2">
             <tr>
                 <td>
                     <apex:commandButton image="{!$Resource.SendButton}" action="{!mail}"/>
                 </td>
                  <td>
                      <b><apex:commandlink value="+" style="text-decoration: none;" action="{!hello}"/></b>
                 </td>
                 <apex:pageBlock id="acol" rendered="{!acol}">
                     <td>
                          <b><apex:commandlink value="Account" style="text-decoration: none;" action="{!addAccount}"/></b>
                     </td>
                     <td>
                          <b><apex:commandlink value="Contact" style="text-decoration: none;"/></b>
                     </td>
                     <td>
                          <b><apex:commandlink value="Opportunity" style="text-decoration: none;"/></b>
                     </td>
                     <td>
                          <b><apex:commandlink value="Lead" style="text-decoration: none;"/></b>
                     </td>
                 </apex:pageBlock>
             </tr>
         </table><br/>
         <table border="0"  width="40%" align="center" cellspacing="0" cellpadding="2">
             <tr>
                 <td align = "center">
                     <apex:commandButton value="Add to mail" rendered="{!accbtn}" action="{!sendAccount}"/>
                 </td>
             </tr>
             <tr>
                 <td width="100%">
                     <apex:pageBlock >
                         <apex:pageblockTable value="{!nc}" var="nsc" width="100%">
                             <apex:column >
                                 <apex:inputCheckbox  value="{!nsc.acctrue}"/>
                             </apex:column>
                             <apex:column >
                                 {!nsc.sr}
                             </apex:column>  
                             <apex:column value="{!nsc.acct.name}"/>
                             <apex:column value="{!nsc.acct.accountnumber}"/>
                             <apex:column value="{!nsc.acct.phone}"/>
                         </apex:pageblockTable>
                     </apex:pageBlock>
                 </td>
             </tr>
         </table>
     </apex:form>
</apex:page>



*****************************Controller***********************************

Public Class EmailSendController{
    public boolean cc {get; set;}
    public boolean bcc {get; set;}
    public boolean acol {get; set;}
    public string to {get; set;}
    public string sub {get; set;}
    public string body {get; set;}
    public string addBcc {get; set;}
    public string addcc {get; set;}
    public List<Account> acc {get; set;}
    public List<NestedClass> nc {get; set;}
    public integer index {get; set;}
    public boolean accbtn {get; set;}
    public List<Account> selectedAcc {get; set;}
    public String s {get; set;}
    public List<String> s1 {get; set;}
    public EmailSendController(){
        cc = false;
        bcc = false;
        acol = false;
        accbtn = false;
        s1 = new List<String>();
     
    }
    public pagereference mailcc(){
        if(cc == false){
            cc = true;
        }else{
            cc = false;
        }
        return null;
    }
    public void mailbcc(){
        if(bcc == false){
            bcc = true;
        }else{
            bcc = false;
        }
    }
    public pagereference hello(){
        if(acol == false){
            acol = true;
        }else{
            acol = false;
        }
        return null;
    }
    public pagereference addAccount(){
       acc = new list<Account>();
       nc = new List<NestedClass>();
       accbtn = true;
       acc = [select id, name , AccountNumber, phone from account];
       integer i = 1;
       for(Account ac : acc){
           nestedClass nsc = new NestedClass();
           nsc.sr = i++;
           nsc.acct = ac;
           nc.add(nsc);
       }
       return null;
    }
    public pageReference sendAccount(){
        selectedAcc = new List<Account>();
        if(nc.size() > 0){
            account selectedAccount = new account();
            for(NestedClass ac : nc){
               if(ac.acctrue == true){
                  selectedAcc.add(ac.acct);
               }
            }
        }
       for(Account acc : selectedAcc){
     
            s = '<Html>' ;
                      s += '<head>' ;
                      s += '</head>' ;
                      s += '<body>' ;
                          s += '<table border="0" bgcolor="#E6E6FA">';
                              s += '<tr>';
                                  s += '<th style="color : red;">';
                                      s += 'Account Name';
                                  s += '</th>';
                                  s += '<th style="color : red;">';
                                      s += 'Account Number';
                                  s += '</th>';
                                  s += '<th style="color : red;">';
                                      s += 'Phone';
                                  s += '</th>';
                              s += '</tr>';
                              s += '<tr>';
                                  s += '<td style="color : blue;">';
                                      s += string.valueOf(acc.Name);
                                  s += '</td>';
                                  s += '<td style="color : blue;">';
                                      s += string.valueOf(acc.AccountNumber);
                                  s += '</td>';
                                  s += '<td style="color : blue;">';
                                      s += string.valueOf(acc.phone);
                                  s += '</td>';
                              s += '</tr>';
                          s += '</table>';
                      s += '<body>' ;
                  s += '</html>' ;
                  s1.add(s);
       }
        return null;
    }
    public pagereference mail(){
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        String addresses;
        addresses = to;
        String[] toAddresses = addresses.split(',', 0);
        email.setSubject(sub);
        if(addBcc != null){
            String[] toBccAddresses = addBcc.split(',', 0);
            if(toBccAddresses.size() > 0 && toBccAddresses != null){
                email.setBccAddresses(toBccAddresses);
            }
        }
        if(addcc != null){    
            String[] toccAddresses = addcc.split(',', 0);
            if(toccAddresses.size() > 0 && toccAddresses != null ){
                email.setccAddresses(toccAddresses);
            }
        }  
        email.setReplyTo('excellencegaur@gmail.com');
        email.setHTMLBody(body+ '' +s1);
        email.setToAddresses(toAddresses);
        List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>{email};
        Messaging.SendEmailResult [] r = Messaging.sendEmail(emails);
        return null;
    }
    public class NestedClass{
        public account acct {get; set;}
        public integer sr {get; set;}
        public boolean acctrue {get; set;}
    }
}

If you have any confusion related to this post , then let me know. 

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;
    }

}