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

Saturday 30 August 2014

status=Moved Temporarily, StatusCode=302

Hi Guys,


So this time it was quite a long time. Anyways lets start with integration part this time . Let me just walk you through scenario.

Scenario:

I have a requirement that I want to integrate some website with salesforce. thougfh it was a just one way integration. I just have to bring some data into the salesforce. Obviously what comes into your mind is Http callout!! Right :)


Lets get started ...

As I have explained above that we want to fetch data from one website into salesforce. So i tried the hhtp callout to their exposed API. As expected I should get the response as status code = ok and 200 . But I got status=Moved Temporarily, StatusCode=302. Then I started looking for solution. I got many but one which I found was very easy. So , i attempted the one and luckily it worked for me.

Why does this happen?

We get this response because we are hitting the wrong api. It gets changes with location . So we need to find the same . The location of server gets changed.


Solution:

We have to find the location which comes with header. So we need to get location from header and we need to write handler for it.


here is the code for you .


if(res.getStatusCode() >=300 && res.getStatusCode() <= 307 && res.getStatusCode() != 306) {
            do {
                redirect = false; // reset the value each time
                String loc = res.getHeader('Location'); // get location of the redirect
                system.debug('loc===='+loc);
                if(loc == null) {
                    redirect = false;
                    continue;
                }
                req = new HttpRequest();
                req.setEndpoint(loc);
                req.setMethod('GET');
                res = http.send(req);
                system.debug('========='+res.getbody());
                                            // Parse entire JSON response.
                JSONParser parser = JSON.createParser(res.getbody());
                    while(parser.nextToken() != null) {
                        if (parser.getCurrentToken() == JSONToken.START_OBJECT) { 
                            root= (RootObject)parser.readValueAs(RootObject.class);
                            system.debug('data =====4'+root.items);
                        }
                        if(root==null){
                        ApexPages.Message msg = new Apexpages.Message(ApexPages.Severity.INFO,'No Records Found');
                        ApexPages.addmessage(msg);
                    }
                }

Now, just try to get through this code. It will work for you too.

happy coding !!


Thanks






















Sunday 20 July 2014

How to add Dynamic Picklist values in Salesforce!!!!

Hi guys!

Its been a long time since I have Written anything. As, I am a also a kind of beginner in salesforce . am also practicing these days with you guys. So , I was just surfing the internet and I found that what if we have to add Dynamic picklist values.
Although there are number of blogs which are available to above scenario. I have also tried the same . So , I thought it would be great to share with you people.

So , Lets start it ...

I have a requirement that an object i.e is called as DynamicObject which has records . I also have a page named as dynamic page, where I have a text  field . Now, Whenever I type any valuer in that text box , then it should get added to the picklist that is shown on visualforce page  . And behind the salesforce it should get added as an record in DynamicObjects .

Use case of this scenario:

There are many websites where it is asked to add your school name and  and in this whole universe unfortunately your school name doesn't exist in the picklist value. So in that case visitor needs to type it  manually. Done! .  But what if another person who is from same school needs to write again . To avoid this situation lets include this functionality of adding value to the picklist. So if the next person comes and tries to find his school name should get in the picklist .


Here is the code ,

Public class dynamicPicklist{
    public string value{get;set;}
    public List<SelectOption> getoptionss(){
          List<SelectOption> options = new List<SelectOption>();
          List<AnkushTest__DynamicObjects__c> citylist = new List<AnkushTest__DynamicObjects__c>();
           valuelist = [Select Id, AnkushTest__PicklistValue__c FROM AnkushTest__DynamicObjects__c];
          options.add(new SelectOption('--None--','--None--'));
          for (Integer j=0;j<citylist.size();j++)
              {
                  options.add(new SelectOption(valuelist[j].AnkushTest__PicklistValue__c,valuelist[j].AnkushTest__PicklistValue__c));
              }
          return options;
    }

    public pageReference Saves()
        {
          AnkushTest__DynamicObjects__c newrec = new AnkushTest__DynamicObjects__c (AnkushTest__PicklistValue__c = newpicklistvalue);
          insert newrec;
         // newpicklistvalue=NULL;
          return null;
        
    }
        public String newpicklistvalue{get; set;}
            Public string getvaluess(){
        
        return  newpicklistvalue;
        
    }

}




<apex:page controller="dynamicPicklist" sidebar="false">
    <apex:pageBlock >
        <apex:form >
            <apex:pageBlockSection title="Dynamic picklist" columns="1">
              <apex:pageblocksectionItem >
                  <apex:outputlabel value="value" for="values" />
                  <apex:selectList value="{!value}" size="1" id="values">
                   <!--  <apex:actionSupport event="onchange" reRender="newpicklistvalue1" />-->
                      <apex:selectOptions value="{!optionss}"/>
                  </apex:selectList>
              </apex:pageblocksectionItem>
             <apex:commandButton action="{!Saves}" value="Add" id="theButton"/>
             <apex:inputText value="{!newpicklistvalue}" label="New value " id="newvalue"/>
             <apex:outputtext value="The name entered is {!valuess}"  id="newpicklistvalue1"/>
         </apex:pageBlockSection>
        </apex:form>
  </apex:pageBlock>
</apex:page>

Just try .. And if u r stuck atny point Just leave me a message at ankushsalesforce@gmail.com


Happy Coding!!!
Cheers
































Saturday 21 June 2014

Trigger on Contact Object!!

Hi Guys!!

How are you doing ? Its been very long I haven't written anything, well I just got time today . Its very hot out here at my place, What!! not because of weather but because of something else . Oh! Sorry , its a Technical blog . I should mind my language. let me stop all this Crap. Focus on Salesforce. Its growing at a rapid rate. need to catch up. :)


So , Guys again am here with a new scenario for trigger . This time we We will Write a trigger on Contact Object . I got this requirement on internet.

Scenario:-

I need a trigger with before events for the below scenario:
We have a Case object having a lookup relationship with opportunity as LX_Opportunity__c.
I wanted the below fields to get populated when case object is saved
LX_Sales_ORG__c on case object should be poulated with LX_Sales_Organization__c from opportunity
LX_Payment_Terms_Lead__c on case object should be poulated with Payment_Terms__c from opportunity.

So I guess it is looks very simple . Let me make it more simple. Lets plan the strategy n nail it.

1. We need to get the id of look up field on contact of opportunity.
2. Then we will querry the opprtunity field from that id.
3. We will then Iterate through that records. And will save those values in contact.


Dont Worry Here is the code

trigger FieldpopulatedFromOpportunity  on Case (Before insert, Before Update) {
    
    set<id> caseIds = new set<id>();
    list<case> opp= new List <case>();
    for(Case c: trigger.new){
        
//        c.AnkushTest__LX_Sales_ORG__c=
          caseIds.add(c.AnkushTest__LX_Opportunity__c);
          system.debug('===case'+c);
          system.debug('==='+caseIds);
    }
    Map<id,Opportunity>  mapopp = new Map<id,opportunity>([Select id, AnkushTest__LX_Sales_Organization__c from opportunity where Id in : caseIds]);
    //mapopp  =  [];
   // system.debug('===op'+op);
    //case c =[Select id from case where id in : caseIds];
    
    for(case cs : trigger.new){
    cs.AnkushTest__LX_Sales_ORG__c = mapopp.get(cs.AnkushTest__LX_Opportunity__c).AnkushTest__LX_Sales_Organization__c ;
    //insert cs;
    opp.add(cs);
    system.debug('===case2'+trigger.new);
    }
    
    
  
  
}



Just try it once . To be honest it took me around five hours to sove this. I hope you can do it too.

Happy coding!!
Cheers
ankushsalesforce@gmail.com




















Sunday 1 June 2014

Trigger On Custom Object!!!

Hi Guys!!

I was just going through some of the requirement on internet last night. So, thought that I should share it with you too. Note: It s for beginners like me , for those who have just made debut in salesforce. :p

Lets Say the scenario is I have a custom object name Friend and it has a field named as Company which is look up to on another object named as company. So if the Company field is empty i.e any of the friend is not associated with any company then it should be associated with company of its own name.
Like If my friend Ravi is not associated with any company then it should automatically get associated with company of his own namw i.e ravi.


trigger populateCompany on Friend__c (before insert,Before update) {
    list<Friend__c> lst = [Select id, name ,AnkushTest__Company__c ,AnkushTest__Pare__c from Friend__c ];
    system.debug('====='+lst);
    For(Friend__c  fi: trigger.new){
        if(fi.AnkushTest__Company__c == null){
            fi.AnkushTest__Pare__c = fi.Name;     
            system.debug('====='+lst);
        }
    }
    
}

So, here have a custom field named AnkushTest__Company__c  which is lookup to Company object.
So if this field is empty or Null then another field named  AnkushTest__Pare__c should be populated as same as Name field .  Important point here is I have used Before trigger because this whole transaction should occur before saving account.

























Sunday 4 May 2014

Java Script remoting Salesforce!!!

Hi Guys,'

Last week I was playing with Java script remoting.

What is java script remoting?

In very simple words , use java script remoting  in Visualforce to call methods in Apex controllers from javaScript.

So , lemme straight away take you to scenario on which I was working last week.

Say, You want to display a picklist value that you have just selected from a custom field of account object. it is one of the scenario where java script remoting comes handy and useful.
Here , is the code for you:-


Apex Controller:-

global with sharing class CopyFieldUsingRemoteActions{

    public CopyFieldUsingRemoteActions() {

    }
      
    Account acct = [SELECT Id, AnkushTest__SLA__c from Account WHERE Id = :ApexPages.currentPage().getParameters().get('id')];
    public static Account account { get; set; }
    
   @RemoteAction
    global static account getAccountSLA(string Fname) {
        account= [Select id , name,TestMap__c,AnkushTest__samplePrefix__c, AnkushTest__SLA__c from account where AnkushTest__SLA__c =: Fname limit 1];
        return account;
    }
    
}
lemme first explain What I have done. So I have tried to querry Account id which is current page ID using :ApexPages.currentPage().getParameters().get('id')] which acytually returns the ID of 
It actually returns the Id of the current  page .  You have to tell controller that a method is going top ber remoting action so you can use in Visualforce. Also , I have passed a parameter in of string type . 


Now , lets go to visualforce section :-


<apex:page Controller="CopyFieldUsingRemoteActions">
     <script>
    function getRemoteAccount(){
          alert(document.getElementById("j_id0:formid:pb:disc:myText").value);
     var test1=document.getElementById("j_id0:formid:pb:disc:myText").value
        Visualforce.remoting.Manager.invokeAction(
            '{!$RemoteAction.CopyFieldUsingRemoteActions.getAccountSLA}',
            test1,
            function(result, event){
                if (event.status) {
                    alert(document.getElementById("j_id0:formid:pb:acctSearch"));
                    // Get DOM IDs for HTML and Visualforce elements like this
                    document.getElementById("j_id0:formid:pb:acctSearch").innerHTML = result.AnkushTest__SLA__c ;       
                } else if (event.type === 'exception') {
                    document.getElementById("j_id0:formid:pb:acctSearch").innerHTML = 
                        event.message + "<br/>\n<pre>" + event.where + "</pre>";
                        alert(event.message);
                } else {
                    document.getElementById("j_id0:formid:pb:acctSearch").innerHTML = event.message;
                     alert('FAil');
                    
                }
            }, 
            {escape: true}
        );
    }
    </script>
    <apex:form id="formid">
        <apex:pageBlock mode="edit" id="pb">
            <apex:pageBlockButtons >
               
                <button onclick="getRemoteAccount()">show </button>
            </apex:pageBlockButtons>
             <apex:outputText id="acctSearch" label="Output"/>
            <apex:pageBlockSection title="My Content Section" columns="2" id="disc" >
                <apex:inputField value="{!account.AnkushTest__SLA__c }" id="myText" onblur="alert('hii');getRemoteAccount();"/>
                
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>


All the java script functionality should be defined under script tag. Now , I have defined a function name getRemoteAccount(). Interesting thing to know that in alert and in that i have used id from inspect element where i want it to be get print. 




Happy Coding!!

Cheers
ankushsalesforce@gmail.com





































Saturday 3 May 2014

Trigger On ContentDocument object Salesforce

Trigger On ContentDocument object Salesforce!


Hi guys!

These days am practicing out Triggers . In-fact I must say it is one of the  best exercise to  build your logic and get familiar with how coding is done in salesforce. 

So, Lemme First explain you the scenario.:-

 Say You want to write a trigger to insert a feed in chatter which could be a link to the library when I create a content  or edit it anything in a  library..

it says If when ever you add or edit any file in library then its link should be posted as link on chatter. 
Its very simple one should be familiar with contentDocument object as this object is not available in salesforce UI. But it is available on background of salesforce.

So you must be thinking then how do I got to know about this one . Well,  Keep exploring. Anyways . I got to know about this one through Developer console. Also from there you can create the trigger. 

Here , is the simple code For you ...


trigger PublishlinkOnChatter on ContentDocument (After insert,After Update) {
    list<FeedItem> lst=new List<feedItem>();
    for(ContentDocument cd:trigger.new){
            FeedItem fi= new FeedItem();
            fi.LinkUrl='https://na15.salesforce.com/'+cd.LatestPublishedVersionId;
            fi.parentid=userinfo.getUserID();
            fi.body='Modified the Content';
            lst.add(fi);
    }
        insert lst;
}


happy Coding!!!


Cheers!!!
ankushsalesforce@gmail.com


















Sunday 13 April 2014

How to write a trigger on Account ?

Hi Guys!!!  I just a new scenario in which we have to write a trigger. it will be a good exercise for us to write a trigger. As trigger is also one of the important parameter. So lets get started.

Here, is the scenario:-


My task is 
in custom settings i have created 2 fields 1) prefix data type is text like abcd. 2)sample is number data type like 0001 ok. now in account object i have created a 1 check box and 1 text field. The task is when ever click on save button the text box needs to be generate a id this id comes from custom settings fields combination of prefix and number like(abcd00001) after this number should be increased by 1 ex:0002 and need to be stored on custom setting field sample because  it needs to be incremented by 1. when next time I am going to create a new record.

Now , lets hit it by step by step. 

1. First we have to create a custom setting. And it shpuld have two fields named sa,ple amd prefix.
2. Create a custom field on Account name Sampleprefix.
3. The idea is to have the value from custom setting and append it to the one in Account.

We will start with after insert and after update. I have already wriiten in my personal org.

Here is the trigger:-



trigger CustomSettings on Account (before insert,before update) {
    if(trigger.isInsert){
    for(Account ac: trigger.new){
        AnkushTest__prefix__c acs =AnkushTest__prefix__c.getOrgDefaults();
        string st;
        st= String.valueOf(acs.AnkushTest__prefix__c)+Integer.valueOf(acs.AnkushTest__sample__c+1);
        system.debug(st);
        ac.AnkushTest__samplePrefix__c=st;
        
        acs.AnkushTest__sample__c=integer.valueof(st.substring(4,5));
        update acs;
        
        }
    }
    if(trigger.isUpdate){
        for(Account acc: trigger.new){
        
        AnkushTest__prefix__c acs =[select AnkushTest__sample__c,AnkushTest__prefix__c, name from AnkushTest__prefix__c limit 1];

        string st;
        st= acs.AnkushTest__prefix__c+integer.valueof(acs.AnkushTest__sample__c+1);
        system.debug('))))))))))'+st);
        acc.AnkushTest__samplePrefix__c=st;
       
        acs.AnkushTest__sample__c=integer.valueof(st.substring(4,5));
        update acs;
        }
       
    }    

}



Saturday 12 April 2014

How to get Contacts associated to a particular opportunity?

It will be a good practice for you to get aware of how apex and visualforce works. 

So lets get started .... Lemme create a very simple scenario for you . Say, I want to get all the contacts that are associated to an opportunity. 

remember:- Before writing any class and visualforce first try to understand the basic requirement and dnt feel shy while noting down on a piece of paper . 

So lets first try to understand how can I retrieve Contacts . What is the relation b/w contacts and opportunity. 
On every Opportunity there is account and account has many contacts associated with it. So, the idea is to first have the Account associated with the current opportunity. then get all the ids of contacts associated with it.
  

I am just going to copy the Apex class that i have written on my personal org. :-


public class ContactList {
    Id opid=ApexPages.currentPage().getParameters().get('id');
    list<opportunity> oplist = new list<opportunity>();
    set<id> acid= new set<id>();
    list<Contact> cont = new list<Contact>();
    public list<Contact> getContactss(){
        for(Account acc:[Select id , name,(select id,lastname from contacts) from Account 
                where AnkushTest__Opportunity__c= :opid])//ApexPages.currentPage().getParameters().get('id')
            { 
               system.debug('=========='+opid);
               system.debug(acc.id+'************************');
               acid.add(acc.id);
            }
        system.debug('========'+acid);
        for(contact con:[select id , name,Accountid,phone from contact where accountid in : acid]){
            cont.add(con);
            system.debug(acid);
        }
        return cont;
    }
    
    public ContactList(ApexPages.StandardController controller) {

    }





visualforce page :-


<apex:page standardController="opportunity" extensions="ContactList">
    <apex:form >
         <apex:pageBlock title="My Content">

        <apex:pageBlockTable value="{!Contactss}" var="item">
        <apex:column >
                <apex:outputLink target="_blank" value="/{!item.id}">{!item.id}</apex:outputLink>
            </apex:column>

           <apex:column value="{!item.Accountid}"/>
           <apex:column value="{!item.phone}"/>

        </apex:pageBlockTable> 

    </apex:pageBlock>
    </apex:form>
</apex:page>
               


Remenber:- You need to append id in URL of the opportunity for which you want to get contacts.
like this   
apex/ContractList/?id=006i000000HRFOw



Happy coding !!
Cheers



Sunday 6 April 2014

How to write Approval process in trigger?

Approval Process!!!
In Salesforce, everyone is aware of approval process. What if I say you can write dynamic Approval processs in a trigger. By doing this your functionality is achieved . 

Salesforce it self illustrates this very smoothly 



Saturday 5 April 2014

How to write a trigger on Attachment object

Hey !  Lets  work on the object which is less used in salesforce i. e am talking about Attachment object !

What is Attachment object ?

Attachment is standard object provided by the salesforce. Interesting thing is you will not find this object under customise tab in salesforce UI. But if you are aware of workbench then through that you can easily come to know the objects which are available in salesforce . Any ways lets get ahead .


Attachment objects is available under the Account Object related list.

Now, Lets run towards writting a trigger on attachment object. So, let me just walk you through the scenario first.
Scenario is :- Say , we want to update an field named last attachment .Every time the attachnment is added. It is very simple to write a trigger whcih is hardly a 10 lines code .
 Here , is the trigger :-


trigger LastAttach on Attachment (After insert) {
    list<account> aclist= new  list<Account>() ;
    Account ac= new Account();
    for (attachment a : trigger.new ){
    
        aclist.add( new Account(Id=a.ParentId ,AnkushTest__last_attachment_added__c= System.now()));
    
            }
  //}
    update aclist;
    }


Dont worry lemme explain it what i did line by line :-

So , in the very first step I created the list of account , then I tried to iterate each attachment till it is created . 
Now, the intersting point here is to note that Account is the parent of attachment object . So, I just have to pick the parent ID and Assigning it to the Account Id. Then a very simple step to have the time stamp of current time used system.now() which returns the current time. 


Happy Coding !!!!
Ankush
ankushsalesforce@gmail.com











Sunday 23 February 2014

Error: invalidData Review all error messages below to correct nYour Data. The page you submitted was invalid for your session. Please Click save again to confirm your change.

Error: invalidData
Review all error messages below to correct Your Data.
The page you submitted was invalid for your session. Please Click save again to confirm your change.


Hi


If you are really worried about this "Error: invalidData
Review all error messages below to correct nYour Data.
The page you submitted was invalid for your session. Please Click save again to confirm your change." while saving a record in salesforce.
Let me attach an error for you .


Now , this is due to the face when you over ride a button with java script . So , it is recommended to avoid "Save=1" variable in javascript because its is no more compatible with salesforce.
Let me just share a Link with You


http://help.salesforce.com/apex/HTViewSolution?id=000176169&language=en_US


Thanks!!

Cheers!!





Sunday 16 February 2014

How to auto-Populate the lookup field from other object.(URL-Hacking in Salesforce).

Hi Guys ... Hows Apex and Visualforce Doing ?? :P

So Last week I was working URL hacking ..I mean to say Override the functionality of new custom button . Some people says that It is "URL hacking". Any ways, whatever it is . So lets get started. 

If you have a query to Auto populate the lookup field from  other object . Let me create an senario for you.
So  Lets say I have three objects testContact ,TestApp and TestURL.

Note : There is no master detail relation between the two. Also it never depends whether there is relation between it or not . 

Any ways lets move ahead. Now there are two fields in each object . TestApp has a look up of TestContact one . My objective is to Auto Popoulate the lookup of TestApp  from detail page of TestContact. Follow these steps :-



  1. First create a lookup of testContact on testApp.
  2. Edit, the page layout of TestContact and in its related list add testApp.
  3. Now , create the lookup relationship of TestApp and TestContact on TestURL.
  4. Edit, the page Layout of testApp and add the TestUrl on its related list.


Now , Lets move ahead. have you ever worked on buttons and Links section under an custom object . let me guide you if not .
Remember: We will try to auto populate the lookup of TestContact on TestUrl. This should be auto populated when trying to make a new testUrl record from TestApp page layout.

Now, Click on the object of TestUrl edit it. Go to the Buttons,links and action section. Click on NewButton or Link.
Am goint to attach screen shots :- 

1.  





Now, in this as you can see that I have created the new button with name Newurl. From behaviour field choose choose Display in existing window and sidebar. Content Source should be URL.


2. Now , go to the testApp object from there try to create a new record for TestUrl.
  


Now , try  to copy the part as indicated in Picture. First copy the link marked in in the URL. and save somewhere in notepad. and then the id of Field as indicted by the inspect element . It is the id of field which will be using to append in URL.

3.
Now , go to the object agaiin where we were making the new button and paste the link and id there as shown below.:-



4. Now , add the field from selectfield Type  section from where you can . now here is a twist that we have to add the TestContact name which is there in TestApp. so we will select TestApp. as object.  And from Insert Field section insert TestContact Name and testApp name and assign their respective Ids which you copied earlier from inspect element.





Now save it finally , But you mut be thinking Y this ret& URL working their. Well, I ll explain it later .


Now , go to testApp page layout and replace this New button with NewURL . and save it .
Now try to create new record You will find that all the lookup fields are auto populated .

But now again try to create the new record , but this time try to cancel it . You will find that it will take you to the home page . so to avoid this we have to append the return url .



Thanks For Reading

Gud day!

Contact : ankushsalesforce@gmail.com
Cheers!!

Saturday 4 January 2014

How to merge two campaigns data into one in Salesforce??


Hello 


You must be thinking how I got solution to this. Dont worry , am not a genius neither am a Researcher. Actually, I too faced this problem few  days back. Then I started looking on internet and i found a very good answer to this in  Developer community of salesforce .  Solutions is very simple . Lemme walk you through it with the help of screen shots : So here we Go :)


Steps :-

  1. First note down the data thats is associated with particular campaigns like :
  







2. Create a new campaign in which you want to merge a data . 


3. Now , run a report on the campagin on which you want to merge into new one . after running a report you ll find a button "Add  to a campaign " click on that button and select the new campaign from the look up . then you ll find  all the above fields ll be added  automatically 

Lemme walk you through the screen shots .


Screen shots :-
                                                                         
                                                                               






 








                                                                             






oAuth Use Case -  Headless API Explained in the Easiest way Wondering why? and When we use the Headless API flow Use case example: Imagine a...