anusha(salesforce developer)

Monday, 12 December 2016

Create a dynamic soql query using ajax to fetch all the account records whose industry is matching with input value and display the account names

Create a dynamic soql query using ajax to fetch all the account records  whose industry is matching with input value and display the account names 

<apex:page id="page">
    <script src="/soap/ajax/36.0/connection.js" type="text/javascript">
    </script>
    <script>
    function callme(){
    sforce.connection.sessionId='{!$API.session_Id}';
            var myIndustry=document.getElementById('page:fm:myIndustry').value;
        var query='select name ,industry from Account where industry=\''+myIndustry+'\'';
    var queryResult=sforce.connection.query(query);
    var records=queryResult.getArray('records');
    var result='';
    for(var i=0;i<records.length;i++){
            result=result+'<br/>'+records[i].Name;
        }
           document.getElementById('page:fm:res').innerHTML=result;
        }         
    </script>
    <apex:form id="fm">
        <apex:inputText id="myIndustry" />
    <apex:commandButton  value="Ajax Call" oncomplete="callme()"/>
        <apex:outputLabel id="res" />
    </apex:form>
</apex:page>

BatchApexExam

Global class BatchApexExam implements database.batchable<Sobject>
{


    global database.querylocator start(database.batchablecontext bc){
            
         string query='select id, description from account';
         
        return database.getquerylocator(query);
    }
    
    global void execute(database.batchablecontext bc, list<account> acclist){
    
            for(account a: acclist){
                
                a.description='Batchapex';
            }
            
            update acclist;
    }
    global void finish(database.batchablecontext bc){
    
    }
    
}

Tuesday, 8 November 2016

Outbound email example:

How to write a code for outbound emailing?

public class OutboundExample {
    public Messaging.SingleEmailMessage email1 ;
    String[] toadd ;
    String[] tocc;
    string subject;
    public OutboundExample(){
        email1=new Messaging.SingleEmailMessage();
        toadd=new String[]{'creativetraining@gmail.com'};
        tocc=new String[]{'onlinebatch135@gmail.com'};
    }
    public void plaintTextBody(){
        email1.setToAddresses(toadd);
        email1.setCcAddresses(tocc);
        email1.setSubject('PlainText Body');
        email1.setPlainTextBody('This is a text body');
        Messaging.Email[] emails=new Messaging.Email[]{email1};
        Messaging.sendEMail(emails);
    }
    public void htmlBody(){
        email1.setToAddresses(toadd);
        email1.setCcAddresses(tocc);
        email1.setSubject('PlainText Body');
        email1.setHtmlBody('<h3> Hai Satish</h3><font style="color:blue">This is test mail</font>');
        Messaging.Email[] emails=new Messaging.Email[]{email1};
        Messaging.sendEMail(emails);
    }
    public void sendAttachments(){
        Contact c=[select id,Email from Contact where phone='9988'];
        String[] toAdd=new String[]{c.email};
        email1.setToAddresses(toAdd);
        email1.setCcAddresses(tocc);
        email1.setSubject('PlainText Body');
        email1.setHtmlBody('<h3> Hai Satish</h3><font style="color:blue">This is test mail</font>');
        PageReference p=Page.page1;
        Blob body=P.getContentAsPDF(); 
        Messaging.EmailFileAttachment attach=new Messaging.EmailFileAttachment();
        attach.setBody(body);
        attach.setFileName('Jan-Feb-Bill.pdf');      
        Messaging.EmailFileAttachment[] attachments=new Messaging.EmailFileAttachment[]{attach};
    email1.setFileAttachments(attachments);   
        Messaging.Email[] emails=new Messaging.Email[]{email1};
        Messaging.sendEMail(emails);
    /* Creating  Attachment with with email attachment    
        Attachment at=new Attachment();
        at.ParentId=c.id;
        at.body=body;
        at.Name='Jan-feb-Bill';
        insert at;
    */
     }
     public void sendTemplate(){        
        EmailTemplate et=[select id from EmailTemplate where name='Test'];
        email1.setTemplateId(et.id);    
        Contact c=[select id from Contact where phone='9988'];
        email1.setTargetObjectId(c.id);    
        Payment__c p=[select id from Payment__c limit 1];
        email1.setWhatId(p.id);      
        Messaging.Email[] emails=new Messaging.Email[]{email1};
        Messaging.sendEMail(emails);
     }
    public void massEmail(){
        Messaging.MassEmailMessage email1=new Messaging.MassEmailMessage();
      EmailTemplate et=[select id from EmailTemplate where name='Test'];
        email1.setTemplateId(et.id);
        Contact c=[select id,Email from Contact where phone='9988'];
        email1.setTargetObjectIds(new Id[]{c.id});
        Messaging.Email[] emails=new Messaging.Email[]{email1};
        Messaging.sendEMail(emails);
    }
   
}

Tuesday, 18 October 2016

what is External Lookup Relationship in salesforce

Use an external lookup relationship when the parent is an external object.

An external lookup relationship links a child standard, custom, or external object to a parent external object.

When you create an external lookup relationship field, the values of the standard External ID field on the parent external object are matched against the values of the external lookup relationship field. For a child external object, the values of the external lookup relationship field come from the specified External Column Name.

Steps to create external lookup relationship:

1. Go to Setup --> Develop --> External Data Sources and create External Data Source.


2. Go to Setup --> Develop --> External Objects and create External Object.


3. Go to Setup --> Create --> Objects and select the object under which you want to create external lookup relationship.



Thursday, 29 September 2016

Difference between Public Group and Queue

Difference between Public Group and Queue


QueuePublic Group
Queues are used primary as Owners of records.Public Groups are used primary for security.
Queue is a feature available to salesforce.com users that allows you to integrate prospect assignments with your current salesforce.com workflow. Rather than assigning to a specific user, you can choose to assign leads to a salesforce.com queue and then use your CRM workflow or manual method of distributing leads to sales representatives.Public Group is kind of team or group of related users; this will help to share the data.
Queue can be created for Custom objects and for Case, Lead and Knowledge Article Version.Public group created can be used across any objects.

Tuesday, 27 September 2016


ISCHANGED can only be used when the WFR is triggered "Every time the record is created or edited"

ISCHANGED

Description:Compares the value of a field to the previous value and returns TRUE if the values are different. If the values are the same, this function returns FALSE.
Use:ISCHANGED(field)and replace field with the name of the field you want to compare.
Validation Rule Example:The following validation rule prevents users from changing an opportunity name after it has been created:NOT(ISCHANGED(Name)).
NOT(AND(ISCHANGED(Priority), ISPICKVAL(Priority, “Low”)))is a validation rule that ensures if a user changes the Priority of a case, the new priority cannot be “Low.”
NOT(AND(ISCHANGED(CloseDate), ​OR(MONTH(CloseDate) <> MONTH(TODAY()), ​YEAR(CloseDate) <> YEAR(TODAY())),$Profile.Name <> "Sales Manager"))is a validation rule that prevents a user from changing the Close Date of an opportunity to a date outside of the current month and year unless that user has the “Sales Manager” profile.Note
$Profile merge fields are only available in Enterprise, Unlimited, and Developer Editions.
Tips:
  • This function is available only in:
    • Assignment rules
    • Validation rules
    • Field updates
    • Workflow rules if the trigger type is set to Every time a record is created or edited.
  • Use the NOT function to reverse the return values of TRUE and FALSE.
  • This function returns FALSE when evaluating any field on a newly created record.
  • If a text field was previously blank, this function returns TRUE when it contains any value.
  • For number, percent, or currency fields, this function returns TRUE when:
    • The field was blank and now contains any value
    • The field was zero and now is blank
    • The field was zero and now contains any other value

Thursday, 22 September 2016

If one object in Salesforce have 2 triggers which runs “before insert”. which one will be executed first? Is there any way to control the sequence of execution of these triggers?


If you write two triggers, there is no particular order of execution and one might run first and sometimes second. In order to control the triggers order of execution, many experts have built Trigger Templates,that basically allow developers to control the order of execution and also control when the trigger needs to be fired.

why we use bulkfy trigger in salesforce


Bulkified trigger is the one which operates on bulk of records at a time. You need to bulkyfy trigger because sometimes you may use data loader or other tools to insert/update/delete lot of records at a time.

Batch size is the number of records that will be processed in a single transaction - in the data loader when running in non-bulk mode you can set this between 1 and 200 records.

Batch jobs are apex that is run in batch mode, allowing up to 50 million records to be processed by a single job. They are a way of breaking up the processing of huge amounts of data into discrete transactions.

Data loader is just another mechanism for getting data into the system - it allows you to create multiple records in one go, unlike the standard UI which allows you to create one record at a time.

Tuesday, 20 September 2016

Visualforce Email Template with custom controller

Visualforce Email Template with custom controller

Apex Controller:

public  class acctTemplt
{
    public Id accountId {get;set;}
    public List<Opportunity> getopptys()
    {
        List<Opportunity> oppty;
        oppty = [SELECT Name, StageName FROM Opportunity WHERE Accountid =: accountId];
        return oppty;
    }
}

Component:

Name:OpptyList

<apex:component controller="acctTemplt" access="global">
    <apex:attribute name="AcctId" type="Id" description="Id of the account" assignTo="{!accountId}"/>
    <table border = "2" cellspacing = "5">
        <tr>
            <td>Opportunity Name</td>
            <td>Opportunity Stage</td>             
        </tr>
        <apex:repeat value="{!opptys}" var="o">
        <tr>
            <td>{!o.Name}</td>
            <td>{!o.StageName}</td>           
        </tr>
        </apex:repeat>     
    </table>
</apex:component>

Visualforce Email template:

<messaging:emailTemplate subject="List of opportunity" recipientType="User" relatedToType="Account">
    <messaging:htmlEmailBody >
    Hi,<br/>
    Below is the list of opportunities for your account {!relatedTo.Name}.<br/><br/>
    <c:OpptyList AcctId="{!relatedTo.Id}" /><br/><br/>
    <b>Regards,</b><br/>
    {!recipient.FirstName}
    </messaging:htmlEmailBody>
</messaging:emailTemplate>

Output:


Visualforce Email Template with custom controller

Visualforce Email Template with custom controller

Apex Controller:

public  class acctTemplt
{
    public Id accountId {get;set;}
    public List<Opportunity> getopptys()
    {
        List<Opportunity> oppty;
        oppty = [SELECT Name, StageName FROM Opportunity WHERE Accountid =: accountId];
        return oppty;
    }
}

Component:

Name:OpptyList

<apex:component controller="acctTemplt" access="global">
    <apex:attribute name="AcctId" type="Id" description="Id of the account" assignTo="{!accountId}"/>
    <table border = "2" cellspacing = "5">
        <tr>
            <td>Opportunity Name</td>
            <td>Opportunity Stage</td>              
        </tr>
        <apex:repeat value="{!opptys}" var="o">
        <tr>
            <td>{!o.Name}</td>
            <td>{!o.StageName}</td>            
        </tr>
        </apex:repeat>      
    </table>
</apex:component>

Visualforce Email template:

<messaging:emailTemplate subject="List of opportunity" recipientType="User" relatedToType="Account">
    <messaging:htmlEmailBody >
    Hi,<br/>
    Below is the list of opportunities for your account {!relatedTo.Name}.<br/><br/>
    <c:OpptyList AcctId="{!relatedTo.Id}" /><br/><br/>
    <b>Regards,</b><br/>
    {!recipient.FirstName}
    </messaging:htmlEmailBody>
</messaging:emailTemplate>

Output:


Where did MVC come from? and What is MVC?

Where did MVC come from?
MVC was one of the seminal insights in the early development of graphical user interfaces, and one of the first approaches to describe and implement software constructs in terms of their responsibilities.

Trygve Reenskaug introduced MVC into Smalltalk-76 while visiting Xerox Parc in the 1970s. In the 1980s, Jim Althoff and others implemented a version of MVC for the Smalltalk-80 class library. It was only later, in a 1988 article in The Journal of Object Technology, that MVC was expressed as a general concept.

Salesforce MVC
Below is a diagram that outlines the Salesforce model-view-controller pattern along with where each element fits into it. We'll dive into each of them.

MODEL

The model is your database objects in Salesforce. The include the standard Salesforce objects like Leads, Contacts, Accounts, Opportunities etc but it also includes any custom objects you've created. Think of it like this -the "model" represents your data model in terms of MVC.

VIEW

The view represents the presentation of the data (i.e. the user interface).
  • Pages - While often just called "pages", what we are talking about is Visualforce pages. They are the building blocks of the user interface. Visualforce uses HTML to lay out the appearance of the application interface. Each page is referenced by a unique URL just like a regular webpage. The pages themselves also contain Visualforce Components which can be invoked by simple tags inside the page. 
  • Components - these are both standard and custom Visualforce Components. Think of them like widgets that you can add to your pages. Once you write the code once, you can reuse it on multiple pages. Components are important because they allow for this reuse. Components can be styled with CSS.

CONTROLLER

Controllers are the building blocks of the actual application logic. The controllers are written in Apex code and they end up controlling and enforcing all the business logic. Remember that one of the key design elements of MVC is to separate the logic from the UI. The presentation layer (the view) shouldn't be mixed with a bunch of business logic. Pages interact with the controller through components which shuttle the data and specifies what happens when the user actually interacts with the UI. Salesforce has pre-built controllers for many of the standard actions like View, Edit, Save. If you want to add new behavior though you can extend or build new controllers (custom controllers) in Apex.

Saturday, 17 September 2016

in Visualforce page Alert button in Salesforce

Alert button in Visualforce page 

Sample Code:

Visualforce page:

<apex:page controller="SampleController">
    <script>
        function callSave(){
            var r = confirm("Are you sure want to save?");
            if(r == true) {                
                callSav();
            }
        }
    </script>
    <apex:form >
        <apex:actionFunction name="callSav" action="{!sav}"/>
        <apex:pageBlock >
            <apex:pageBlockSection >
                <apex:inputField value="{!member.Name}"/>
                <apex:inputField value="{!member.E_Mail_Id__c}"/>
                <apex:inputField value="{!member.State__c}"/>
                <apex:inputField value="{!member.City__c}"/>
                <apex:inputField value="{!member.Age__c}"/>
            </apex:pageBlockSection>
            <apex:pageBlockButtons >
                <apex:commandButton value="Save" onclick="callSave();"/>
            </apex:pageBlockButtons>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Apex controller:

public class SampleController {
    public Member__c member {get;set;}
    
    public SampleController() {
        member = new Member__c();
    }
    
    public void sav(){
        insert member;
        member = new Member__c();
    }
}

Output:


page OnLoad function in visualforce

OnLoad function in visualforce

Method 1:

<script type = "text/javascript">
    window.onload=function()       
    {        
        alert("Hi");
    };
</script>

Method 2:

Visuaforce page:

<apex:page action="{!onLoad}">

</apex:page>


Controller:

public class sample {
        public sample(){
        }

        public void onLoad(){

            .
        }
}

Thursday, 15 September 2016

action status in Salesforce

Simple action status in Salesforce

Sample Code:

<apex:page controller="Sample">
<apex:actionstatus id="counterStatus">
    <apex:facet name="start">
        <div class="waitingSearchDiv" id="el_loading" style="background-color: #fbfbfb; height:100%;opacity:0.65;width:100%;">
            <div class="waitingHolder" style="top: 100px; width: 91px;">
            <img class="waitingImage" src="/img/loading.gif" title="Please Wait..." />
            <span class="waitingDescription">Loading...</span>
            </div>
        </div>
    </apex:facet>
</apex:actionstatus>
<apex:form id="frm">
    <apex:commandButton value="Test" status="counterStatus" reRender="frm"/>
</apex:form>
</apex:page>

Output:


Creating table in Visualfore page

Creating table in Visualfore page

Sample Code:

Visualforce page:

<apex:page sidebar="false" >
<apex:form >
<apex:panelGrid columns="2" width="100%" cellpadding="5" cellspacing="5" >
    <apex:outputtext value="Name"/>
    <apex:inputtext />
    <apex:outputtext value="Age"/>
    <apex:inputtext />
    <apex:outputtext value="Total Experience"/>
    <apex:inputtext />
    <apex:outputtext value="Skill"/>
    <apex:inputtext />
    <apex:commandbutton value="Validate"/>
</apex:panelGrid>
</apex:form>
</apex:page>


Output:

How to make apex:pageblock background white in salesforce?

How to make apex:pageblock background white?

Syntax:

<apex:pageblock mode="maindetail">

Example:

Visualforce page:

<apex:page controller="Sample" sidebar="false" >
<style type="text/css">
    .hideButton{display:none;}
</style>
<chatter:feedWithFollowers entityId="{!contactDetail.Id}"/><apex:form >   
    <apex:pageblock title="Contact Detail" mode="maindetail">
        <apex:pageblockSection columns="4" >
            <apex:pageblockSectionItem >
                Contact First Name:
            </apex:pageblockSectionItem> 
            <apex:pageblockSectionItem >
                <apex:outputField value="{!contactDetail.FirstName}">
                    <apex:inlineEditSupport event="ondblclick" showOnEdit="Save,Cancel" hideOnEdit="Edit"/>
                </apex:outputField>
            </apex:pageblockSectionItem>   
            <apex:pageblockSectionItem >
                Contact Email:
            </apex:pageblockSectionItem> 
            <apex:pageblockSectionItem >
                <apex:outputField value="{!contactDetail.Email}">
                    <apex:inlineEditSupport event="ondblclick" showOnEdit="Save,Cancel" hideOnEdit="Edit"/>
                </apex:outputField>               
            </apex:pageblockSectionItem>  
            <apex:pageblockSectionItem >
                Contact Last Name:
            </apex:pageblockSectionItem> 
            <apex:pageblockSectionItem >
                <apex:outputField value="{!contactDetail.LastName}">
                    <apex:inlineEditSupport event="ondblclick" showOnEdit="Save,Cancel" hideOnEdit="Edit"/>
                </apex:outputField>               
            </apex:pageblockSectionItem>             
            <apex:pageblockSectionItem >
                Contact Mobile Number:
            </apex:pageblockSectionItem> 
            <apex:pageblockSectionItem >
                <apex:outputField value="{!contactDetail.MobilePhone}">
                    <apex:inlineEditSupport event="ondblclick" showOnEdit="Save,Cancel" hideOnEdit="Edit"/>
                </apex:outputField>               
            </apex:pageblockSectionItem>  
            <apex:pageblockSectionItem >
                Account:
            </apex:pageblockSectionItem> 
            <apex:pageblockSectionItem >
                <apex:outputField value="{!contactDetail.AccountId}">
                    <apex:inlineEditSupport event="ondblclick" showOnEdit="Save,Cancel" hideOnEdit="Edit"/>
                </apex:outputField>               
            </apex:pageblockSectionItem>                        
            <apex:pageblockSectionItem >
                Contact Phone Number:
            </apex:pageblockSectionItem> 
            <apex:pageblockSectionItem >
                <apex:outputField value="{!contactDetail.Phone}">
                    <apex:inlineEditSupport event="ondblclick" showOnEdit="Save,Cancel" hideOnEdit="Edit"/>
                </apex:outputField>               
            </apex:pageblockSectionItem>
            <apex:pageblockSectionItem >
                Department:
            </apex:pageblockSectionItem> 
            <apex:pageblockSectionItem >
                <apex:outputField value="{!contactDetail.Department}">
                    <apex:inlineEditSupport event="ondblclick" showOnEdit="Save,Cancel" hideOnEdit="Edit"/>
                </apex:outputField>               
            </apex:pageblockSectionItem>            
            <apex:pageblockSectionItem >
                Other Phone:
            </apex:pageblockSectionItem> 
            <apex:pageblockSectionItem >
                <apex:outputField value="{!contactDetail.OtherPhone}">
                    <apex:inlineEditSupport event="ondblclick" showOnEdit="Save,Cancel" hideOnEdit="Edit"/>
                </apex:outputField>               
            </apex:pageblockSectionItem>   
            <apex:pageblockSectionItem >
                Description:
            </apex:pageblockSectionItem> 
            <apex:pageblockSectionItem >
                <apex:outputField value="{!contactDetail.Description}">
                    <apex:inlineEditSupport event="ondblclick" showOnEdit="Save,Cancel" hideOnEdit="Edit"/>
                </apex:outputField>               
            </apex:pageblockSectionItem>                                 
            <apex:pageblockSectionItem >
                Fax:
            </apex:pageblockSectionItem> 
            <apex:pageblockSectionItem >
                <apex:outputField value="{!contactDetail.Fax}">
                    <apex:inlineEditSupport event="ondblclick" showOnEdit="Save,Cancel" hideOnEdit="Edit"/>
                </apex:outputField>                            </apex:pageblockSectionItem>                                                                                                                                      
        </apex:pageblockSection> 
        <apex:pageBlockSection title="System Information" columns="4" >
            <apex:pageblockSectionItem >
                Created By
            </apex:pageblockSectionItem>
            <apex:pageblockSectionItem >
                <apex:outputField value="{!contactDetail.CreatedById}"/>
            </apex:pageblockSectionItem>
            <apex:pageblockSectionItem >
                Last Modified By
            </apex:pageblockSectionItem>
            <apex:pageblockSectionItem >
                <apex:outputField value="{!contactDetail.LastModifiedById}"/>
            </apex:pageblockSectionItem>           
        </apex:pageBlockSection>     
        <apex:pageblockButtons >
            <apex:commandButton value="Edit" id="Edit" action="{!Editcontact}"/>
            <apex:commandButton value="Save" id="Save" styleClass="hideButton" action="{!updateContact}" />
            <apex:commandButton value="Cancel" id="Cancel" styleClass="hideButton"/>
        </apex:pageblockButtons>       
    </apex:pageblock>
</apex:form>
</apex:page>
 


Apex Controller:

public class Sample
{  
    public Contact contactDetail {get;set;}
    public Id contactId = '0039000000PsPW6';
    public sample()
    {
        contactDetail = [SELECT Id, LastName, FirstName, AccountId, Email, MobilePhone, Phone, Department, Fax, ReportsTo.Name, OtherPhone, Description, CreatedById, LastModifiedById FROM Contact WHERE Id =: contactId ];
    } 
    public void editContact()
    {
    }
    public void updateContact()
    {
        update contactDetail;
    }
}
 


Output:

How to increment apex:variable?

How to increment apex:variable?

In order to increment apex:variable inside the apex:pageBlockTable, we have to include it inside apex:column in apex:pageBlockTable.

 <apex:page controller="sample">
    <apex:pageBlock >
    <apex:variable var="i" value="{!0}"/>
        <apex:pageBlockTable value="{!acnt}" var="acc">
            <apex:column >

                {!i}
                <apex:variable var="i" value="{!i+1}"/>
            </apex:column>
            <apex:column value="{!acc.Name}" rendered="{! IF((mod(i,2)) == 0, true, false)}" style="background:pink;"/>
            <apex:column rendered="{! IF((mod(i,2)) == 0, true, false)}" style="background:pink;" value="{!acc.Rating}"/>                                
            <apex:column value="{!acc.Name}" rendered="{! IF((mod(i,2)) == 1, true, false)}" style="background:yellow;"/>
            <apex:column rendered="{! IF((mod(i,2)) == 1, true, false)}" style="background:yellow;" value="{!acc.Rating}"/>
        </apex:pageBlockTable>
    </apex:pageBlock>
</apex:page>


In case of apex:repeat, we can just write as below

<apex:variable var="i" value="{!0}"/> 
<apex:repeat>
      <apex:variable var="i" value="{!i+1}"/>
</apex:repeat>

Code for alternate background color for rows in a pageBlockTable

Code for alternate background color for rows in a pageBlockTable

Visualforce code:

<apex:page controller="sample">
    <apex:pageBlock >
    <apex:variable var="i" value="{!0}"/>
        <apex:pageBlockTable value="{!acnt}" var="acc">
            <apex:column >
                <apex:variable var="i" value="{!i+1}"/>
            </apex:column>
            <apex:column value="{!acc.Name}" rendered="{! IF((mod(i,2)) == 0, true, false)}" style="background:pink;"/>
            <apex:column rendered="{! IF((mod(i,2)) == 0, true, false)}" style="background:pink;" value="{!acc.Rating}"/>                     
           
            <apex:column value="{!acc.Name}" rendered="{! IF((mod(i,2)) == 1, true, false)}" style="background:yellow;"/>
            <apex:column rendered="{! IF((mod(i,2)) == 1, true, false)}" style="background:yellow;" value="{!acc.Rating}"/>
        </apex:pageBlockTable>
    </apex:pageBlock>
</apex:page>


Output: