Lookup filter

Lookup filter is used to filter the values to be shown in lookup relation.



Cheers!!!

Difference between trigger.new and trigger.old in salesforce

Trigger.new : Returns a list of the new versions of the sObject records. Note that this sObject list is only available in insert and update triggers, and the records can only be modified in before triggers.

Trigger.old : Returns a list of the old versions of the sObject records. Note that this sObject list is only available in update and delete triggers.

For more info visit the below link

http://www.salesforce.com/us/developer/docs/apexco​de/Content/apex_triggers_context_variables.htm

Cheers!!!

Setup Audit trail

Setup Audit trail is used to store the configurational changes.



Cheers!!!

How to get a subquery field value using Apex?

List<Account> acct = new List<Account>();

String sql = 'SELECT Name,Phone,External_ID__c,Type,Industry,AccountNumber,Description,FAX,SLA__c,Rating,(SELECT Name,StageName,CloseDate,Probability FROM Opportunities) FROM Account WHERE ID=:localId';

acct = Database.Query(sql);
       
        for(Account ac:acct)
        {
            List<Opportunity> opptys = new List<Opportunity>();
            opptys = ac.getSObjects('Opportunities');
            for(Opportunity opt:opptys)
            {
            }
        }


Cheers!!!

How to free list memory using apex?

MyList.clear();

Where MyList is a List variable.


Example:


List<Account> MyList = new List<Account>();
MyList.add(new Account(name = 'test');
MyList.clear(); // Removes the accounts


Cheers!!!

Getting child objects of Master object in salesforce

Sample code:
 
Schema.DescribeSObjectResult R = Account.SObjectType.getDescribe();
List<Schema.ChildRelationship> C = R.getChildRelationships();

for (Schema.ChildRelationship cr: C) 
{
relName.add(cr.getRelationshipName());
}
 
Query:
 
SELECT Name,(Select Name,AccountId From Contacts) FROM Account 


Cheers!!!

Salesforce to Salesforce using PartnerSoapSforceCom

Step 1: Generate Partner WSDL.



Save the generated Partner WSDL.

Step 2: Generate Apex code using the generated Partner WSDL.







Copy the generated code and create a new Apex Class.

Note:
In the generated code do the following changes.
  1. Change public partnerSoapSforceCom.DeleteResult[] delete(String[] ids)  to public partnerSoapSforceCom.DeleteResult[] deleteSObjects(String[] ids).
  2. Change public partnerSoapSforceCom.UpsertResult[] upsert(String externalIDFieldName,sobjectPartnerSoapSforceCom.sObject_x[] sObjects) to public partnerSoapSforceCom.UpsertResult[] upsertSObjects(String externalIDFieldName,sobjectPartnerSoapSforceCom.sObject_x[] sObjects).
  3. Change public partnerSoapSforceCom.MergeResult[] merge(partnerSoapSforceCom.MergeRequest[] request) to public partnerSoapSforceCom.MergeResult[] mergeSObjects (partnerSoapSforceCom.MergeRequest[] request).
  4. Change public partnerSoapSforceCom.SaveResult[] update(sobjectPartnerSoapSforceCom.sObject_x[] sObjects) to public partnerSoapSforceCom.SaveResult[] updateSObjects(sobjectPartnerSoapSforceCom.sObject_x[] sObjects).
  5. Change public partnerSoapSforceCom.UndeleteResult[] undelete(String[] ids) to public partnerSoapSforceCom.UndeleteResult[] undeleteSObjects(String[] ids).

Step 3: Creating a custom button ‘Share with Bangalore’.





Step 4: Add the custom button to Account page layout.



Step 5: Create shareWithBangalore apex class.

Sample Code:

global class shareWithBangalore
{
    webservice static void share(Id localId)
    {  
   
        String password = 'pocuser01xmJO32dqUnhHUwB1kFNW9kEw';
        String userName = 'chennaipoc@patni.com';
       
        List<Account> acct = new List<Account>();
        String sql = 'SELECT Name,Phone,External_ID__c,Type,Industry,AccountNumber,Description,FAX,SLA__c,Rating FROM Account WHERE ID=:localId';
        acct = Database.Query(sql);
       
        partnerSoapSforceCom.Soap con = new partnerSoapSforceCom.Soap();
             
        partnerSoapSforceCom.LoginResult loginResult = con.login(username, password);   
       
        con.SessionHeader = new partnerSoapSforceCom.SessionHeader_element();
        con.endpoint_x =loginResult.ServerUrl;
        con.Sessionheader.sessionid = loginResult.sessionid;
       
        List<sobjectPartnerSoapSforceCom.sObject_x> sObjects = new List<sobjectPartnerSoapSforceCom.sObject_x>();          
        sobjectPartnerSoapSforceCom.sObject_x tmpObj = new sobjectPartnerSoapSforceCom.sObject_x();
        for(Account ac:acct)
        {
            tmpObj.type_x = 'Account';
            tmpObj.AcctName = ac.Name;
            tmpObj.ExtID= ac.External_ID__c;
            tmpObj.Phone = ac.Phone;           
            tmpObj.AcctType = ac.Type;
            tmpObj.AcctIndustry = ac.Industry;
            tmpObj.AcctNum = ac.AccountNumber;
            tmpObj.AcctDesc= ac.Description;            
            tmpObj.AcctFAX = ac.FAX;
            tmpObj.AcctSLA = ac.SLA__c;   
            tmpObj.AcctRating = ac.Rating;       
            sObjects.add(tmpObj);
        }
        con.create(sObjects);           
    }
}


Step 6: Add the field details in sobjectPartnerSoapSforceCom apex class.

Add the below code in sobjectPartnerSoapSforceCom apex class.

        //Start      

        public String AcctName;      

        private String[] AcctName_type_info = new String[]{'Name','urn:partner.soap.sforce.com','string','1','1','true'};      

        public String ExtID;      

        private String[] ExtID_type_info = new String[]{'External_ID__c','urn:partner.soap.sforce.com','string','1','1','true'};      

        public String Phone;      

        private String[] Phone_type_info = new String[]{'Phone','urn:partner.soap.sforce.com','string','1','1','true'};      

        public String AcctType;      

        private String[] AcctType_type_info = new String[]{'Type','urn:partner.soap.sforce.com','string','1','1','true'};     

        public String AcctIndustry;      

        private String[] AcctIndustry_type_info = new String[]{'Industry','urn:partner.soap.sforce.com','string','1','1','true'};      

        public String AcctNum;      

        private String[] AcctNum_type_info = new String[]{'AccountNumber','urn:partner.soap.sforce.com','string','1','1','true'};       

        public String AcctDesc;      

        private String[] AcctDesc_type_info = new String[]{'Description','urn:partner.soap.sforce.com','string','1','1','true'};      

        public String AcctFax;      

        private String[] AcctFax_type_info = new String[]{'Fax','urn:partner.soap.sforce.com','string','1','1','true'};      

        public String AcctSLA;      

        private String[] AcctSLA_type_info = new String[]{'SLA__c','urn:partner.soap.sforce.com','string','1','1','true'};       

        public String AcctRating;      

        private String[] AcctRating_type_info = new String[]{'Rating','urn:partner.soap.sforce.com','string','1','1','true'};     

        //end


Edit the private String[] field_order_type_info = new String[]{'type_x','fieldsToNull','Id'}; to private String[] field_order_type_info = new String[]{'type_x','fieldsToNull','Id','AcctName','ExtID','Phone','AcctIndustry','AcctType','AcctNum','AcctDesc','AcctFax','AcctSLA','AcctRating'};


Step 7: Adding Remote site settings.



Output:

Javascript code to reload a page

The below Javascript code is used to reload a page

location.reload(true);

Cheers!!!

Password field in Visualforce

Syntax:


<apex:inputSecret value="{!inputValue}" id="theSecretInput"/>

Example:

<apex:inputsecret id="pwd" value="{!pwd}"/>


Cheers!!!

Approval Process using Apex

In order to use apex code to submit the record for Approval process, we have to first create Approval process in Create --> Workflow & Approvals.


Sample code:

    void submit(Id localId)
    {
        // Create an approval request for the account
   
        Approval.ProcessSubmitRequest req1 =
            new Approval.ProcessSubmitRequest();
        req1.setComments('Submitting request for approval.');
        req1.setObjectId(localId);
       
        // Submit the approval request for the account
   
        Approval.ProcessResult result = Approval.process(req1);
       
        // Verify the result
   
        System.assert(result.isSuccess());
       
        System.assertEquals(
            'Pending', result.getInstanceStatus(),
            'Instance Status'+result.getInstanceStatus());       

    }


Visit the below link to get more details

http://www.salesforce.com/us/developer/docs/apexcode/index_Left.htm#CSHID=apex_ProcessRequest.htm|StartTopic=Content%2Fapex_ProcessRequest.htm|SkinName=webhelp

Cheers!!!

Fetching data from another salesforce instance using API

Visualforce page:

<apex:page controller="SearchAcctFromSf" standardStylesheets="true">
<apex:form >

<apex:pageBlock >
    <apex:pageblockSection columns="2" >
        <apex:outputLabel value="UserName"/>
        <apex:inputText required="true" id="userName" value="{!userName}" />
        <apex:outputLabel value="Password"/>
        <apex:inputsecret id="pwd" value="{!pwd}"/>      
    </apex:pageblockSection>
    <apex:pageblockButtons >
        <apex:commandButton id="getRecords" value="Fetch" action="{!fetch}" rerender="acctDetails" status="waitStatus" />
    </apex:pageblockButtons>
</apex:pageBlock>

<apex:actionStatus startText="Fetching..." id="waitStatus"/>

<div style="display:{!displayError}"> {!errMsg} </div>

<apex:pageBlock >
    <apex:pageblockSection id="acctDetails">
        <apex:pageBlockTable value="{!acc}" var="account" id="accTable">
  
            <apex:column >
                <apex:facet name="header">Account Name</apex:facet>
                <apex:outputText value="{!account.name}"/>
            </apex:column>
  
            <apex:column >
                <apex:facet name="header">Created By</apex:facet>
                <apex:outputText value="{!account.CreatedBy.FirstName}"/>
            </apex:column>
  
            <apex:column >
                <apex:facet name="header">Phone</apex:facet>
                <apex:outputText value="{!account.Phone}"/>
            </apex:column>

        </apex:pageBlockTable>

    </apex:pageblockSection>
</apex:pageBlock>

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

Apex Controller:

public with sharing class SearchAcctFromSf {  
    public String pwd{get;set;}
    public String userName{get;set;}
    public List<Account> acc{get;set;}
    public String errMsg{get;set;}
    public String displayError{get;set;}

    public SearchAcctFromSf() 
{
        displayError = 'none';
    }

    public void fetch() 
{
        errMsg  = 'Some error occurred, please try again';
        try {
        /*-----------------------------------
         Login via SOAP/XML web service api
        -----------------------------------*/
        HttpRequest request = new HttpRequest();
        request.setEndpoint('https://www.salesforce.com/services/Soap/u/22.0');
        request.setMethod('POST');
        request.setHeader('Content-Type', 'text/xml;charset=UTF-8');
        request.setHeader('SOAPAction', '""');
        /*not escaping username and password because we're setting those variables above
        in other words, this line "trusts" the lines above
        if username and password were sourced elsewhere, they'd need to be escaped below*/
        request.setBody('<Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/"><Header/><Body><login xmlns="urn:partner.soap.sforce.com"><username>' + userName+ '</username><password>' + pwd+ '</password></login></Body></Envelope>');
        Dom.XmlNode resultElmt = (new Http()).send(request).getBodyDocument().getRootElement()
          .getChildElement('Body', 'http://schemas.xmlsoap.org/soap/envelope/')
          .getChildElement('loginResponse', 'urn:partner.soap.sforce.com')
          .getChildElement('result', 'urn:partner.soap.sforce.com');

        /*-------------------------------

         Grab session id and server url
        --------------------------------*/
        final String SERVER_URL = resultElmt.getChildElement('serverUrl', 'urn:partner.soap.sforce.com') .getText().split('/services')[0];
        final String SESSION_ID = resultElmt.getChildElement('sessionId', 'urn:partner.soap.sforce.com') .getText();

        /*----------------------------------

         Load first 20 accounts via REST API
        ---------------------------------*/
        final PageReference theUrl = new PageReference(SERVER_URL + '/services/data/v22.0/query/');
        theUrl.getParameters().put('q','Select a.Phone, a.Name, a.Industry From Account a limit 20');
        request = new HttpRequest();
        request.setEndpoint(theUrl.getUrl());
        request.setMethod('GET');
        request.setHeader('Authorization', 'OAuth ' + SESSION_ID);

        String body = (new Http()).send(request).getBody();


        JSONParser parser = JSON.createParser(body);


        do 
{
            parser.nextToken();
        }
        while(parser.hasCurrentToken() && !'records'.equals(parser.getCurrentName()));

        parser.nextToken();


        acc = (List<Account>) parser.readValueAs(List<Account>.class);

        }
        catch(Exception e) {
            displayError = 'block';
        }

    }

}

Remote Site settings:

Dont forget to add "http://www.salesforce.com" under Setup --> Administration Setup --> Security Controls --> Remote Site Settings.



Output: