Thursday, 15 January 2015

Trigger on Parent Object to copy the fields on its child record in Salesforce!!

Hi Guys!!

Its been long time since I have been here. My obsession with salesforce has taken next level.

Still, I love writing triggers. I know all these are very small triggers. But it may help beginners who are trying to connect to salesforce.

Anyways, lets start with another trigger(Only for beginners) .

Scenario:-

I have to replicate a field of parent object to all its child records. It is very simple scenario for experience people.

Here is the code for you folks....

Trigger replicateFieldsOnChild on Parent (After update){
 Set<id> setOfParentId = new Set<Id>();
 for(Parent pt : trigger.new){
  setOfParentId.add(pt.id);
 }
 List<Child> listChild = new List<Child>([Select id, parentId from child where ParentId in: setOfParentId]);
 List<Child> updatedlistChild = new List<Child>
 for(Parent pt : trigger.new){
  for(Child ch : listChild){
   ch.field = pt.field;
   updatedlistChild.add(ch);
  }
 }
 Update updatedlistChild;
}


Remember :-  There are may ways of doing a job . You may find more simpler and efficient way. keep Exloring!


Happy coding 

Cheers
Ankush
ankushsalesforce@gmail.com

















Sunday, 30 November 2014

Accessing parent object field in trigger Salesforce!!

Hi Guys!

It is Saturday out here and am sharing a few rodablocks you may face while executing your code. Beware , if you are new to salesforce apex like me. It can take days and hours, to solve the issue which I will discuss with you.

Some good readers may be aware of it already. Ok

Issue:- I was working in my office and doing debugging of a trigger which someone wrote a year back I guess. But I got an scenario that this trigger is not working properly means it is doing 95 5 of its work. But rest 5 % was the bug.

So lemme explain you the scenario. Say, I have two two custom object A  and B . Also I have a USER object.

Lets go with the rlation ship User is the parent of 'A' object. In turn 'A' is the parent of 'B' object.
As we know that there is a field called Manager on User object which is lookup field to user. So, whenever a record of object'A' is created then the manager of parent A should be replicated to a field Manager__B on Custom Object'B'. Obviously we have trigger on Custom Object'A' . But catch here is you cannnot use the value of a parents fields directly. you need to querry that field. Lemme share you with the codesinppet.


for(custom__A res: [Select Id,  custom__A__User__r.ManagerId from custom__A where Id in:resIds ]){
                custom__B mem = resourceToMemberMap.get(res.Id);
                mem.OwnerId = res.OwnerId;
                mem.Line_Manager__c = res.custom__A__User__r.ManagerId;                

You cannot  use the value res.custom__A__User__r.ManagerId untill this field is being used in query.
So, you need to query this field. Otherwise you ll get mem.Linemanager = null always.

Credit for this learning goes to my colleques and to the Senior developer who passed on this piece of knowledge to me .

Cheers
happy coding!

Thanks
Ankush












Thursday, 27 November 2014

Upoading ChangeSet of Email templates and letter heads in salesforce!!

Hi Guys!!

Salesforce sometimes comes up  with very interesting scenarios . I don t know why it happens . but it should not never happen . Though it is bug or not . Sorry , You must be thinking what the hell am talking about . Ok lemme tell you.


If you are a administrator and working to create a change sets from one org to another org which are connected to each other. In that change sets you are about to send the email templates that you created that are HTML templates . then BEWARE!!!


Guys!
I ll share what all happened with me. Some of  you might not be surprised to know .

I got an issue while uploading a change set which contains two email templates . In the org in which I have created the email template i. is a HTML Email template with Letter Heads.

First, When I created a change set it just contained the Email templates without Letterheads. I uploaded it to a connected org which  does not have its associated Letter heads. I found that there is no letter heads found . Which is the obvious  case.  Also ,I didn get the letter heads field available.


Second, I uploaded another Change set to the connected org  which contains only letter heads which were associated with the Email templates which which I uploaded in last change set. Still I cant see letter heads field on email template I uploaded.  Although , Letter heads has been deployed. to this connected org. Also Letter heads was made available by checking the check box.


Third , When I uploaded the another change set with Email Templates and letter heads in one change set.  It is then Only I get Option to ad letter heads.


So, Make sure you upload theses components in same change set.

Thanks
Ankush

Sunday, 23 November 2014

Simple Script for Calculating bumber of childs in Salesforce!

Hi Guys!!

Its been long time.  This time I am with very simple scenario. Must say salesforce is expanding day by day. Its really awesome, but its becoming very difficult to keep running salesforce, so many new features are being released with every release.

Any ways lets get back to buisness.

Scenario:- Say, I have many accounts and Contacts in my Org. And I simply wants to calculate the number of Contacts that are related to one account.

Solution:-

It is very easy . Just take a copy and a pen, and lay down the idea and think before writting the code.
prerequisite :- Get familiar with Workbench. 

In workbench go to the apex execute.  section , which is under the Utilities.



Map<id,List<Contact>> mapit = new Map<id,List<Contact>>();
for(Contact con : [Select id, AccountID from Contact]){
 If(Con.AccountId != null){
    mapit.put(con.AccountId, new List<Contact>([Select id from Contact where AccountId = : Con.AccountID]));
}
}
System.debug('=='+Mapit.keySet().size());
For(Account acc : [Select id from Account where id in :Mapit.keySet()]){
     system.debug('size='+mapit.get(acc.id).size());
    acc.NumberofLocations__c = mapit.get(acc.id).size();
}


NumberofLocations__c is a number field in account. 

Happy Coding
Ankush 

ankushsalesforce@gmail.com










Thursday, 23 October 2014

Trigger On Attachment Object Salesforce!!

Hi Guys!!

Hope you doing well.

One of my blog reader asked me to share code of trigger on Attachment object . Although , I have already written a trigger on attachment object. For the same click here. but this time I have got a different scenario.

Caution Notice :P :- This blog is meant for beginners like me, who are still learning  salesforce or must say it is for those who are loving salesforce.

Scenario:-  When an attachment is inserted under an account or a contact or Lead  etc.Now, on the basis of a custom field on parent of attachment object, it should check whether any other record exist with same value of field . If there exist some record then this lead should get deleted and and the attachment should be attached to older one. 

So , lets begin with it . Lets Say , I have acustom field on Lead object name as My_name__c on lead objec. On the basis of this field I ll check whether there exist some records or not. so lets Jump to code .




trigger DeleteLeadIFNewMatchesOld on Attachment (Before insert) {
    Set<Id> setOfNewLead = new Set<Id>();
    Set<String> setOfMyname = new Set<String>();
    Set<Id> setOfDeleteLeads = new Set<Id>();
    for(attachment a : trigger.new ){
        setOfNewLead.add(a.ParentId);
    }
    Map<Id,lead> mapOfNewLead = new Map<Id,Lead>([Select id , My_name__c from Lead where id in :  setOfNewLead]);
    Map<Id,Lead> mapOfOldLead = new Map<Id,Lead>([Select id , My_name__c from Lead where  id not in :  setOfNewLead]); 
//    Map<Id,String> = new Map<Id,String>();
    System.debug(mapOfOldLead);
     //if(mapOfNewLead.get(a.ParentId).My_name__c == mapOfOldLead.get())
        for(Lead ld : mapOfNewLead.values()){
           //System.debug('myname'+myname);
            System.debug('mapOfNewLead.values()'+mapOfNewLead.get(ld.Id).My_name__c);
            String myname = mapOfNewLead.get(ld.Id).My_name__c;
            setOfMyname.add(myname);
        }
        for(attachment a : trigger.new ){
            System.debug(setOfMyname);
            System.debug('==19'+mapOfNewLead.get(a.ParentId).My_name__c);
                System.debug('===');
                //Id testId = [Select Id from Lead where My_name__c in]
                for(Id getIdMap : mapOfOldLead.keySet()){
                    if(setOfMyname.contains(mapOfOldLead.get(getIdMap).My_name__c)){
                        setOfDeleteLeads.add(a.ParentId);
                        a.ParentId = getIdMap;
                }

            }
        }
        List<Lead> deleteList = [Select id from Lead where Id in : setOfDeleteLeads];
        delete deleteList;
}




try this Code and then let me know how can I improve this code . I have made it quite complex. 
ThanksAnkush 

Cheers
ankushsalesforce@gmail.com


Please give a look at  my awesome friends Blog piyush Blog

























Saturday, 4 October 2014

Trigger On Case(EmailTo Case) using Custom Settings in Salesforce!

Hi Guys!!

Its been long time since I have written anything. Lets start this time with custom settings. Let me straight away walk you through the scenario.


Scenario:

Lets say you have activated the email to case Functionality in salesforce. For more info about it . click here . I have so many clients account and their respective contacts. 

Let me first tell you how the Email to case functionality works. Lets say I have my client named TestClient and correspondingly I have an account for it named as TestClient. Also I have a Contact associated with it. Name = TestContact and its email 'testcontact@smile.com'.  Now, if this contact comes and mail and a case is created in my org. So when You go in your org and check the case, it will be associated with a client account i.e testClient also a contact with TestContat.  Now what if the email was send by a client that was not CONTACT but is a part of clients company. Then in that case, Account and Contact will be null . I,e case will not be associated with any of the account unless incoming email is from contact . 

So we Need to associate the case with account incase if it has no contact.






So Guys, Lets start it with writing a trigger and its trigger handler 

Note: This trigger is not Bulkified although it will work properly , Because there are very less chances that we can get so many emails at one time. Still the best practices says that every thing we code should be bulkified .


So here is my architecture of the trigger. 

We need to build a custom setting named as domain. where we can add fields on basis of  our requirement of filtering it .

I have made a field named as Account which is text field. we will create records like gmail.com, Yahoo.co.in etc. if the company name is TestClient then its email must be xyz@testcleint.com. So in this Case you have to make record with name testcleint.com and Account as Test Client. 


Here is a code for you. 

Remeber: it is trigger handler.


 trigger CreateAccount on EmailMessage (After insert, After Update){
    string []  emails ;
    List<Account> acct ;
    Map<String,Domain__c> dommap = Domain__c.getAll();
    system.debug('===getall'+Domain__c.getAll());
    system.debug('===dommap'+dommap);
    set<id> sid = new set<id>();
    Domain__c ccd = new Domain__c();
    For(EmailMessage em : trigger.new){
        if(em.Incoming == True ){
            emails =  em.FromAddress.split('@');          
            system.debug('===Emails'+emails);
            system.debug('===dommap.containsKey(emails)'+dommap.containsKey(emails[1]));
            if(dommap.containsKey(emails[1])){
              sid.add(em.ParentId); 
              //dmlst.add(ccd.getvalues(emails[1]));
            }
            system.debug('\nsid'+sid);
            //Domain__c dc = new Domain__c();   
            //system.debug('=='+dc.getAll().values());
            //if(em.FromAddress = dc.getAll()){}
            //em.FromAddress =  
        }
    }
    Domain__c cd ;


//    system.debug(cd.get(emails[1]).values());
//    system.debug(cd.getinstanace(emails[1]));
    //system.debug(cd.getvalues(emails[1]));
    
    acct = new list<Account>() ;
    //acct = [Select id , name from Account where name =: dommap.get('emails[1]').AnkushTest__Account__c];
    system.debug('\nacct'+acct); 
    List<Case> lst = new List<Case>();
    lst = [Select id , Accountid from case where id in : sid];
    system.debug('==lst'+lst);
    for(case cs : lst){
        lst = new List<Case>();
        if(cs.Accountid == Null){
            system.debug(string.valueof(dommap.get(emails[1])));
            system.debug(dommap.get(emails[1]).AnkushTest__Account__c);
            string st =string.valueof(dommap.get(emails[1]).AnkushTest__Account__c);
            system.debug(st);
            Account acctt = [Select id , name from Account where name = :st];
                system.debug(acctt);
            cs.Accountid = acctt.id ;
            lst.add(cs);
                }
                else{ lst.add(cs);}
        
        
        /*for(Domain__c dm : Domain__c.getall(emails[1])){
            system.debug(dommap.get(emails[1]));
            //if(dm.Incoming == True ){
                system.debug('\n==='+dommap.get('emails[1]'));
                if(cs.Accountid == Null){
                    //cs.Accountid = dommap.get('emails[1]');
                }
            //}
        }*/
    }
    update lst;
    system.debug('==lst'+lst);
}


For Any Querries 
Contact 
ankushsalesforce@gmail.com


Tuesday, 2 September 2014

WrapperClass to delete Selected Account in Salesforce

Hi Guys..

This time lets start with wrapper class in salesforce. Like java, we also have wrapper class in salesforce. to know more about wrapper class Clickhere . So I got some requirements on social networking groups. Let me walk you throgh the scenario.


Scenario:

Lets say you have some list of accounts and you have to delete some of the selected accounts using check box. 

Solution: 

I ll provide you with the whole code but first lets understand the way how we ll be going to proceed . Basically  a roadmap.

1. we need to first display the listy of acccounts.
2. We need to have a column of check boxes to select the accounts that we need to display.
3. Once a check box is checked then we need to delete them by clicking on delete  the button .

Here is the code for you guys


public class DeleteWrapper{
    public List<wrapperDelete> wrp;
    public  List<wrapperDelete> getAccnt(){
        //List<wrapperDelete> wrp = new List<wrapperDelete>();
        if(wrp == null){
        wrp = new List<wrapperDelete>();
        for(account acct:[Select id, name from Account ]){
        wrp.add(new wrapperDelete(Acct));
        }
      }
        system.debug(wrp);
        return wrp;
    }
    public class wrapperDelete{
        public Boolean selected {get; set;}
        //public  List<Account> lst {get; set;}
        public Account lst {get; set;}
        //public wrapperDelete(List<Account> lstact){
        public wrapperDelete(Account lstact){
            selected = false;
            lst = lstact;
        }
    }
    public pageReference Deletes(){
        list<Account> SelectedAccount = new List<Account>();
        system.debug('=='+getAccnt());
        for(wrapperDelete wd : getAccnt()){
            if(wd.selected == true){
                SelectedAccount.add(wd.lst);
            }
        }
        system.debug('=='+SelectedAccount);
        delete SelectedAccount;
        wrp = null;
        system.debug('===='+SelectedAccount);
        return null;
    } 
}


Let me explain you line by line .

We have wrapper class with name wrapperDelete which contains list of account  and checkboxes. In its constructor we have passed account object as parameter and made selection as false . So whenever the  page is loaded check boxes are unchecked.

Now above we have created a list of wrapper class to add accounts.

here is the visual force code :

<apex:page controller="DeleteWrapper">
    <apex:form >
        <apex:pageBlock >
            <apex:pageBlockSection >
                <apex:pageBlockTable value="{!Accnt}" var="it" >
                      <apex:column >
                         <apex:inputCheckbox value="{!it.selected}"/>
                      </apex:column>
                      <apex:column value="{!it.lst.name}"/>
                      <apex:column value="{!it.lst.id}"/>
                </apex:pageblockTable>
            </apex:pageBlockSection>
        </apex:pageBlock>
      <apex:commandButton action="{!Deletes}" value="Deletes" />
    </apex:form>    
</apex:page>

If you have any querry regarding the above post. please Feel free to contact me


happy coding!!


Cheers
Ankush
ankushsalesforce@gmail.com

My AI Channel

Hi Folks,  Its been a while posted any post on Salesforce. I feel like Salesforce can waith but new AI hype cant, need to go with the flow. ...