Thursday 13 October 2016

Apex - Trigger.old and trigger.new comparison

trigger contacttrigger on contact (before delete) {
    for (customobject__C coj : [SELECT Contactlookup__c
                                      FROM contactrelatedobject__c
                                      WHERE Contactlookup__c
                                      IN :Trigger.oldMap.keySet()]) {
        Trigger.oldMap.get(coj.contactlookup__c).addError(
                   'Cannot delete contact with a contactrelatedobject record');
    }
}

Apex - create master-detail records

master(parent) - account

detail(child) - contact


 Creating a Child Record When a Parent Record is Created

You want to automatically create a new child record when you create a parent record. The child record should be populated with default values from contact.


trigger AutoCreatecontact on account (after insert) {
    List<contact> cons = new List<contact>();

  
    for (account newacc: Trigger.New) {
        if (newacc.customfield__c != null) {
            cons.add(new contact(
                        Name = 'Iain',
                        account = newacc.Id,
                        contactcustomfield__c = newacc.customfield__c,
                        another_contactcustomfield__c = 'Yes'));
        }
    }
    insert cons;
}


Wednesday 12 October 2016

Apex - loops

Loops are used when a particular piece of code should be repeated with desired number of iteration.

FOREACH loops let you repeatedly execute code on every element of a list:

List<Contact> allContacts = [SELECT Id FROM Contact];

for (Contact currentContact : allContacts) {
    

    currentContact.customfield__c = 'customvalue';



FOR loops  lets you repeatedly execute code a specific number of times:


for (Integer i = 0; i < 5; i++) {

    
    Contact newcontact = new Contact();
    newcontact.FirstName = 'Iain';
    newcontact.LastName  = 'Banks #' + i;
    newcontact.customfield__c = 'customvalue';
    insert newcontact;
}

FOR LOOP:
syntax - 
for (variable : list_or_set) { code_block }

List<apex_invoice__c> PaidInvoiceNumberList = new List<apex_invoice__c>();
//initialising list of object records 


PaidInvoiceNumberList = [SELECT Id,Name, APEX_Status__c FROM APEX_Invoice__c  WHERE CreatedDate = today]; 
//SOQL query to find filter records


List<string> InvoiceNumberList = new List<string>();
//list to store paid invoice


for (APEX_Invoice__c objInvoice: PaidInvoiceNumberList) { 

//loop iterates (executes repeatedly) on the PaidInvoiceNumberList and will process the each record (objInvoice)

if (objInvoice.APEX_Status__c == 'Paid') { 
//this if condition will check each record for the boolean condition



InvoiceNumberList.add(objInvoice.Name);
//if Status value is paid then it will add the invoice number into List of String
}
}

SOQL FOR LOOP:
This type of for loop is used when we don't want to create the List and directly iterate over the returned set of records of SOQL query.


Syntax - 
for (variable : [soql_query]) { code_block }
OR
for (variable_list : [soql_query]) { code_block }

the variable_list or variable should always be of same type as the records returned by the Query

List<apex_invoice__c> PaidInvoiceNumberList = new List<apex_invoice__c>();
//initialising list of object records 

List<string> InvoiceNumberList = new List<string>();
//list to store paid invoice

for (APEX_Invoice__c objInvoice: [SELECT Id,Name, APEX_Status__c FROM APEX_Invoice__c  WHERE CreatedDate = today]) { 

//this loop will iterate and will process the each record returned by the Query

if (objInvoice.APEX_Status__c == 'Paid') { 
//this if condition will check each record for the boolean condition



InvoiceNumberList.add(objInvoice.Name);
//if Status value is paid then it will add the invoice number into List of String
}
}

JAVA FOR LOOP:
Syntax - 
for (init_stmt; exit_condition; increment_stmt) { code_block }

List<apex_invoice__c> PaidInvoiceNumberList = new List<apex_invoice__c>();
//initialising list of object records 

List<string> InvoiceNumberList = new List<string>();
//list to store paid invoice

for (Integer i = 0; i < paidinvoicenumberlist.size(); i++) { 

//this loop will iterate on the List PaidInvoiceNumberList and will process the each record. It will get the List Size and will iterate the loop for number of times that size. For example, list size is 10.

if (PaidInvoiceNumberList[i].APEX_Status__c == 'Paid') { 
//this if condition will check each record for the boolean condition



InvoiceNumberList.add(PaidInvoiceNumberList[i].Name);
//if Status value is paid then it will add the invoice number into List of String
}

}

WHILE LOOP:
Syntax - 
while (Boolean_condition) { execute_code_block }

//Fetch 20 records from database
List<apex_invoice_c> InvoiceList = [SELECT Id, APEX_Description_c, APEX_Status_c FROM APEX_Invoice_c LIMIT 20];
Integer i =1;
//Update ONLY 10 records
while (i< 10) {
InvoiceList[i].APEX_Description__c = 'This is the '+i+'Invoice';

i++;

}

DO WHILE LOOP:
syntax - 
do { code_to_execute } while (Boolean_condition);


//Code for do while loop
List<apex_invoice__c> InvoiceList = [SELECT Id, APEX_Description__c, APEX_Status__c FROM APEX_Invoice__c LIMIT 20];//it will fetch only 20 records
Integer i =0;
do {
InvoiceList[i].APEX_Description__c = 'This is the '+i+' Invoice';

i++;//Increment the counter
}while (i< 1); 

//iterate till 1st record only

Sunday 11 September 2016

Apex - Usefull trigger to maintain the relationship between custom objects related to Lead to Account/Contact/Opp after Lead Conversion


trigger LeadConvertCustomObjects on Lead (before update) {
//This trigger will associate Custom Object records with the Account, Contact, and/or      opportunity associated to the
//lead after it has been converted.
//The Custom Object is associated to an opportunity only if an opportunity record exist on the Lead.
for (Integer i = 0; i < Trigger.new.size(); i++){
    if (Trigger.new[i].IsConverted == true && Trigger.old[i].isConverted == false){
        Set<Id> leadIds = new Set<Id>();
        for (Lead lead : Trigger.new)
            leadIds.add(lead.Id);

        Map<Id, DocuSign_Account__c> entries_DSA = new Map<Id, DocuSign_Account__c>([select Account__c, Lead__c from DocuSign_Account__c where lead__c in :leadIds]);      
        if(!Trigger.new.isEmpty()) {
            for (Lead lead : Trigger.new)  {
                for (DocuSign_Account__c DSA : entries_DSA.values()) {
                    if (DSA.Lead__c == lead.Id) {
                        // DSA.contact__c = lead.ConvertedContactId;
                        // DSA.opportunity__c = lead.ConvertedOpportunityId;
                        DSA.account__c = lead.ConvertedAccountId;
                        update DSA;
                        // break;
                    }
                }
            }
        }

        Map<Id, DocuSign_Account_Member__c> entries_DSAM = new Map<Id, DocuSign_Account_Member__c>([select Contact__c, Lead__c from DocuSign_Account_Member__c where lead__c in :leadIds]);      
        if(!Trigger.new.isEmpty()) {
            for (Lead lead : Trigger.new)  {
                for (DocuSign_Account_Member__c DSAM : entries_DSAM.values()) {
                    if (DSAM.Lead__c == lead.Id) {
                        DSAM.Contact__c = lead.ConvertedContactId;
                        // DSAM.opportunity__c = lead.ConvertedOpportunityId;
                        // DSAM.account__c = lead.ConvertedAccountId;
                        update DSAM;
                        // break;
                    }
                }
            }
        }

        Map<Id, Use_Case__c> entries_UC = new Map<Id, Use_Case__c>([select Account__c, Lead__c from Use_Case__c where lead__c in :leadIds]);      
        if(!Trigger.new.isEmpty()) {
            for (Lead lead : Trigger.new)  {
                for (Use_Case__c UC : entries_UC.values()) {
                    if (UC.Lead__c == lead.Id) {
                        // UC.contact__c = lead.ConvertedContactId;
                        // UC.opportunity__c = lead.ConvertedOpportunityId;
                        UC.account__c = lead.ConvertedAccountId;
                        update UC;
                        // break;
                    }
                }
            }
        }

        Map<Id, Ecosystem__c> entries_ECO = new Map<Id, Ecosystem__c>([select Account__c, Lead__c from Ecosystem__c where lead__c in :leadIds]);      
        if(!Trigger.new.isEmpty()) {
            for (Lead lead : Trigger.new)  {
                for (Ecosystem__c ECO : entries_ECO.values()) {
                    if (ECO.Lead__c == lead.Id) {
                        // ECO.contact__c = lead.ConvertedContactId;
                        // ECO.opportunity__c = lead.ConvertedOpportunityId;
                        ECO.account__c = lead.ConvertedAccountId;
                        update ECO;
                        // break;
                    }
                }
            }
        }

        Map<Id, Partner_Influence__c> entries_PI = new Map<Id, Partner_Influence__c>([select Account__c, Lead__c from Partner_Influence__c where lead__c in :leadIds]);      
        if(!Trigger.new.isEmpty()) {
            for (Lead lead : Trigger.new)  {
                for (Partner_Influence__c PI : entries_PI.values()) {
                    if (PI.Lead__c == lead.Id) {
                        // PI.contact__c = lead.ConvertedContactId;
                        PI.opportunity__c = lead.ConvertedOpportunityId;
                        PI.account__c = lead.ConvertedAccountId;
                        update PI;
                        // break;
                    }
                }
            }
        }

        Map<Id, Qualification_Credit__c> entries_QC = new Map<Id, Qualification_Credit__c>([select Account__c, Lead__c from Qualification_Credit__c where lead__c in :leadIds]);      
        if(!Trigger.new.isEmpty()) {
            for (Lead lead : Trigger.new)  {
                for (Qualification_Credit__c QC : entries_QC.values()) {
                    if (QC.Lead__c == lead.Id) {
                        // QC.contact__c = lead.ConvertedContactId;
                        QC.opportunity__c = lead.ConvertedOpportunityId;
                        QC.account__c = lead.ConvertedAccountId;
                        update QC;
                        // break;
                    }
                }
            }
        }


    }
}

}


//---------------
@isTest
//This is a test case for a situation where a lead will be converted.  The developer must explicitly call the convert lead
//method to simulate the user action.

private class TestLeadConvertCustomObjects {
    static testMethod void TestReferralUpdate() {
    // Insert the Lead
    List<Lead> leads = new List<Lead>();
    Lead leadt = new Lead (FirstName ='fname', LastName ='test', Company ='myCompany');
    insert leadt;
    // Insert the DocuSign_Account__c Record
    DocuSign_Account__c DSA = new DocuSign_Account__c (Lead__c = leadt.Id);
    insert DSA;
    // Insert the DocuSign_Account_Member__c Record
    DocuSign_Account_Member__c DSAM = new DocuSign_Account_Member__c (Lead__c = leadt.Id, DocuSign_Account__c = DSA.Id);
    insert DSAM;
    // Insert the Use_Case__c Record
    Use_Case__c UC = new Use_Case__c (Lead__c = leadt.Id, Department__c='Legal', Use_Case__c='NDAs', Status__c='Interest');
    insert UC;
    // Insert a Partner Account Record with a Partner Go To Market to relate Ecosystem & Partner Influence to
    Account PartnerAccount = new Account (Name='PartnerAccount', Partner_Go_To_Market_Count_Active__c=1);
    insert PartnerAccount;
    Partner_Go_To_Market__c PGTM = new Partner_Go_To_Market__c (Name='PartnerGoToMarket', Account__c = PartnerAccount.Id, GTM_Status__c='Agreement Signed');
    insert PGTM;
    // Insert the Ecosystem__c Record
    Ecosystem__c ECO = new Ecosystem__c (Lead__c = leadt.Id, Partner__c = PartnerAccount.Id, Ecosystem_Type__c='CRM', Integration__c='Not Integrated');
    insert ECO;
    // Insert the Partner_Influence__c Record
    Partner_Influence__c PI = new Partner_Influence__c (Lead__c = leadt.Id, Partner__c = PartnerAccount.Id, Role__c='Influencer', Influence_Type__c='Neutral');
    insert PI;
    // Insert the Qualification_Credit__c Record
    Qualification_Credit__c QC = new Qualification_Credit__c (Lead__c = leadt.Id, Status__c='Qualified');
    insert QC;

//test.startTest();

//Convert the Lead
Database.LeadConvert lc = new database.LeadConvert();
lc.setLeadId(leadt.Id);
LeadStatus convertStatus = [Select Id, MasterLabel from LeadStatus where MasterLabel='Contact Created Only' AND IsConverted=true limit 1];
lc.setConvertedStatus(convertStatus.MasterLabel);
Database.LeadConvertResult lcr = Database.convertLead(lc);  

//Requery for the referral record to see if it is updated
DocuSign_Account__c ref_upd_DSA = [select Account__c from DocuSign_Account__c where Lead__c = :leadt.Id];
DocuSign_Account_Member__c ref_upd_DSAM = [select Contact__c from DocuSign_Account_Member__c where Lead__c = :leadt.Id];
Use_Case__c ref_upd_UC = [select Account__c from Use_Case__c where Lead__c = :leadt.Id];
Ecosystem__c ref_upd_ECO = [select Account__c from Ecosystem__c where Lead__c = :leadt.Id];
Partner_Influence__c ref_upd_PI = [select Account__c, Opportunity__c from Partner_Influence__c where Lead__c = :leadt.Id];
Qualification_Credit__c ref_upd_QC = [select Account__c, Opportunity__c, Contact__c from Qualification_Credit__c where Lead__c = :leadt.Id];

//Check that the test passed
    System.assertEquals(ref_upd_DSA.Account__c,[Select ConvertedAccountId From Lead Where Id = :DSA.Lead__c].ConvertedAccountId);
    System.assertEquals(ref_upd_DSAM.Contact__c,[Select ConvertedContactId From Lead Where Id = :DSAM.Lead__c].ConvertedContactId);
    System.assertEquals(ref_upd_UC.Account__c,[Select ConvertedAccountId From Lead Where Id = :UC.Lead__c].ConvertedAccountId);
    System.assertEquals(ref_upd_ECO.Account__c,[Select ConvertedAccountId From Lead Where Id = :ECO.Lead__c].ConvertedAccountId);
    System.assertEquals(ref_upd_PI.Account__c,[Select ConvertedAccountId From Lead Where Id = :PI.Lead__c].ConvertedAccountId);
    System.assertEquals(ref_upd_QC.Account__c,[Select ConvertedAccountId From Lead Where Id = :QC.Lead__c].ConvertedAccountId);
    System.assertEquals(ref_upd_QC.Contact__c,[Select ConvertedContactId From Lead Where Id = :QC.Lead__c].ConvertedContactId);
    System.assertEquals(ref_upd_PI.Opportunity__c,[Select ConvertedOpportunityId From Lead Where Id = :PI.Lead__c].ConvertedOpportunityId);
    System.assertEquals(ref_upd_QC.Opportunity__c,[Select ConvertedOpportunityId From Lead Where Id = :QC.Lead__c].ConvertedOpportunityId);    

//Test if no opty is created
string NoOpty = 'Y';  
if (NoOpty =='Y'){
  Lead leadto = new Lead (FirstName ='fnameo', LastName ='testo', Company ='myCompanyo');
      insert leadto;
      // Insert the custom object record
      // CustomObject__c customobjecto = new CustomObject__c (Lead__c = leadto.Id);
      // insert customobjecto;
      // Insert the DocuSign_Account__c Record
      DocuSign_Account__c DSAo = new DocuSign_Account__c (Lead__c = leadto.Id);
      insert DSAo;
      // Insert the DocuSign_Account_Member__c Record
      DocuSign_Account_Member__c DSAMo = new DocuSign_Account_Member__c (Lead__c = leadto.Id, DocuSign_Account__c = DSAo.Id);
      insert DSAMo;  
      // Insert the Use_Case__c Record
      Use_Case__c UCo = new Use_Case__c (Lead__c = leadto.Id, Department__c='Legal', Use_Case__c='NDAs', Status__c='Interest');
      insert UCo;
      // Insert a Partner Account Record with a Partner Go To Market to relate Ecosystem & Partner Influence to
      Account PartnerAccounto = new Account (Name='PartnerAccounto', Partner_Go_To_Market_Count_Active__c=1);
      insert PartnerAccounto;
      Partner_Go_To_Market__c PGTMo = new Partner_Go_To_Market__c (Name='PartnerGoToMarketo', Account__c = PartnerAccounto.Id, GTM_Status__c='Agreement Signed');
      insert PGTMo;
      // Insert the Ecosystem__c Record
      Ecosystem__c ECOo = new Ecosystem__c (Lead__c = leadto.Id, Partner__c = PartnerAccounto.Id, Ecosystem_Type__c='CRM', Integration__c='Not Integrated');
      insert ECOo;
      // Insert the Partner_Influence__c Record
      Partner_Influence__c PIo = new Partner_Influence__c (Lead__c = leadto.Id, Partner__c = PartnerAccounto.Id, Role__c='Influencer', Influence_Type__c='Neutral');
      insert PIo;
      // Insert the Qualification_Credit__c Record
      Qualification_Credit__c QCo = new Qualification_Credit__c (Lead__c = leadto.Id, Status__c='Qualified');
      insert QCo;




  Database.LeadConvert lco = new database.LeadConvert();
  lco.setLeadId(leadto.Id);
  lco.isDoNotCreateOpportunity();
  lco.setDoNotCreateOpportunity(true);
  LeadStatus convertStatuso = [Select Id, MasterLabel from LeadStatus where MasterLabel='Contact Created Only' AND IsConverted=true limit 1];
  lco.setConvertedStatus(convertStatuso.MasterLabel);
  Database.LeadConvertResult lcro = Database.convertLead(lco);

  DocuSign_Account__c ref_updo_DSA = [select Account__c from DocuSign_Account__c where Lead__c = :leadto.Id];
  DocuSign_Account_Member__c ref_updo_DSAM = [select Contact__c from DocuSign_Account_Member__c where Lead__c = :leadto.Id];
  Use_Case__c ref_updo_UC = [select Account__c from Use_Case__c where Lead__c = :leadto.Id];
  Ecosystem__c ref_updo_ECO = [select Account__c from Ecosystem__c where Lead__c = :leadto.Id];
  Partner_Influence__c ref_updo_PI = [select Account__c, Opportunity__c from Partner_Influence__c where Lead__c = :leadto.Id];
  Qualification_Credit__c ref_updo_QC = [select Account__c, Opportunity__c, Contact__c from Qualification_Credit__c where Lead__c = :leadto.Id];


  //Check that the test passed
      System.assertEquals(ref_updo_DSA.Account__c,[Select ConvertedAccountId From Lead Where Id = :DSAo.Lead__c].ConvertedAccountId);
      System.assertEquals(ref_updo_DSAM.Contact__c,[Select ConvertedContactId From Lead Where Id = :DSAMo.Lead__c].ConvertedContactId);
      System.assertEquals(ref_updo_UC.Account__c,[Select ConvertedAccountId From Lead Where Id = :UCo.Lead__c].ConvertedAccountId);
      System.assertEquals(ref_updo_ECO.Account__c,[Select ConvertedAccountId From Lead Where Id = :ECOo.Lead__c].ConvertedAccountId);
      System.assertEquals(ref_updo_PI.Account__c,[Select ConvertedAccountId From Lead Where Id = :PIo.Lead__c].ConvertedAccountId);
      System.assertEquals(ref_updo_QC.Account__c,[Select ConvertedAccountId From Lead Where Id = :QCo.Lead__c].ConvertedAccountId);
      System.assertEquals(ref_updo_QC.Contact__c,[Select ConvertedContactId From Lead Where Id = :QCo.Lead__c].ConvertedContactId);
      System.assertEquals(ref_updo_PI.Opportunity__c,[Select ConvertedOpportunityId From Lead Where Id = :PIo.Lead__c].ConvertedOpportunityId);
      System.assertEquals(ref_updo_QC.Opportunity__c,[Select ConvertedOpportunityId From Lead Where Id = :QCo.Lead__c].ConvertedOpportunityId);    
      // System.assert(ref_updo__DSA.Opportunity__c == null);

//test.stopTest();
}
}

  static testMethod void testBulkUpdate() {
    List<Lead> leads = new List<Lead>();    
    for (Integer i=0;i<5;i++) {
        Lead l = new Lead (FirstName ='bulk', LastName ='Test', Company ='myCompanyo');
    insert l;
    // Insert the Custom Record
     DocuSign_Account__c DSAr = new DocuSign_Account__c (Lead__c = l.Id);
     insert DSAr;
     DocuSign_Account_Member__c DSAMr = new DocuSign_Account_Member__c (Lead__c = l.Id, DocuSign_Account__c = DSAr.Id);
     insert DSAMr;
     // Insert the Use_Case__c Record
     Use_Case__c UCr = new Use_Case__c (Lead__c = l.Id, Department__c='Legal', Use_Case__c='NDAs', Status__c='Interest');
     insert UCr;
     // Insert a Partner Account Record with a Partner Go To Market to relate Ecosystem & Partner Influence to
     Account PartnerAccountr = new Account (Name='PartnerAccountBulk', Partner_Go_To_Market_Count_Active__c=1);
     insert PartnerAccountr;
     Partner_Go_To_Market__c PGTMr = new Partner_Go_To_Market__c (Name='PartnerGoToMarketBulk', Account__c = PartnerAccountr.Id, GTM_Status__c='Agreement Signed');
     insert PGTMr;
     // Insert the Ecosystem__c Record
     Ecosystem__c ECOr = new Ecosystem__c (Lead__c = l.Id, Partner__c = PartnerAccountr.Id, Ecosystem_Type__c='CRM', Integration__c='Not Integrated');
     insert ECOr;
     // Insert the Partner_Influence__c Record
     Partner_Influence__c PIr = new Partner_Influence__c (Lead__c = l.Id, Partner__c = PartnerAccountr.Id, Role__c='Influencer', Influence_Type__c='Neutral');
     insert PIr;
     // Insert the Qualification_Credit__c Record
     Qualification_Credit__c QCr = new Qualification_Credit__c (Lead__c = l.Id, Status__c='Qualified');
     insert QCr;


      test.startTest();

      //Convert the Lead
  Database.LeadConvert lcb = new database.LeadConvert();
  lcb.setLeadId(l.Id);
  LeadStatus convertStatusb = [Select Id, MasterLabel from LeadStatus where MasterLabel='Contact Created Only' AND IsConverted=true limit 1];
  lcb.setConvertedStatus(convertStatusb.MasterLabel);
  Database.LeadConvertResult lcrb = Database.convertLead(lcb);

  DocuSign_Account__c bulkup_DSA = [select Account__c from DocuSign_Account__c where Lead__c =:l.Id];
  DocuSign_Account_Member__c bulkup_DSAM = [select Contact__c from DocuSign_Account_Member__c where Lead__c =:l.Id];
  Use_Case__c bulkup_UC = [select Account__c from Use_Case__c where Lead__c = :l.Id];
  Ecosystem__c bulkup_ECO = [select Account__c from Ecosystem__c where Lead__c = :l.Id];
  Partner_Influence__c bulkup_PI = [select Account__c, Opportunity__c from Partner_Influence__c where Lead__c = :l.Id];
  Qualification_Credit__c bulkup_QC = [select Account__c, Opportunity__c, Contact__c from Qualification_Credit__c where Lead__c = :l.Id];

  //Check that the test has passed
      System.assertEquals(bulkup_DSA.Account__c,[Select ConvertedAccountId From Lead Where Id = :DSAr.Lead__c].ConvertedAccountId);
      System.assertEquals(bulkup_DSAM.Contact__c,[Select ConvertedContactId From Lead Where Id = :DSAMr.Lead__c].ConvertedContactId);
      System.assertEquals(bulkup_UC.Account__c,[Select ConvertedAccountId From Lead Where Id = :UCr.Lead__c].ConvertedAccountId);
      System.assertEquals(bulkup_ECO.Account__c,[Select ConvertedAccountId From Lead Where Id = :ECOr.Lead__c].ConvertedAccountId);
      System.assertEquals(bulkup_PI.Account__c,[Select ConvertedAccountId From Lead Where Id = :PIr.Lead__c].ConvertedAccountId);
      System.assertEquals(bulkup_QC.Account__c,[Select ConvertedAccountId From Lead Where Id = :QCr.Lead__c].ConvertedAccountId);
      System.assertEquals(bulkup_QC.Contact__c,[Select ConvertedContactId From Lead Where Id = :QCr.Lead__c].ConvertedContactId);
      System.assertEquals(bulkup_PI.Opportunity__c,[Select ConvertedOpportunityId From Lead Where Id = :PIr.Lead__c].ConvertedOpportunityId);
      System.assertEquals(bulkup_QC.Opportunity__c,[Select ConvertedOpportunityId From Lead Where Id = :QCr.Lead__c].ConvertedOpportunityId);    
      // System.assertEquals(bulkup.Opportunity__c,[Select ConvertedOpportunityId From Lead Where Id = :r.Lead__c].ConvertedOpportunityId);


     }
  }
}

Sunday 19 June 2016

Visualforce - create an event record using a custom button and visualforce page

visual force page to create event record

requires
visualforce page
controller class
button

visualforce page

<apex:page standardController="Event" extensions="macalendarentry" showheader="false" sidebar="false">
<apex:form >
<apex:pageblock title="MArket Appraisal Calendar Entry" mode="edit">
 <apex:pageBlockButtons location="top">
 <apex:commandButton action="{!save}" value="Save"/>


 </apex:pageBlockButtons>


<apex:pageBlockSection title="Calendar Details" columns="4" >


<apex:inputfield value="{!Event.Ownerid}" >
</apex:inputfield>



<apex:inputfield value="{!Event.Subject}" >
</apex:inputfield>

<apex:inputfield value="{!Event.WhatId}" >
</apex:inputfield>

<apex:inputfield value="{!Event.Type}" >
</apex:inputfield>

<apex:inputfield value="{!Event.StartDateTime}" >
</apex:inputfield>

<apex:inputfield value="{!Event.EndDateTime}" >
</apex:inputfield>
<apex:inputfield value="{!Event.Event_Status__c}" >
</apex:inputfield>
<apex:inputfield value="{!Event.Cancellation_Reason__c}" >
</apex:inputfield>
<apex:inputfield value="{!Event.Location}" >
</apex:inputfield>
<apex:inputfield value="{!Event.ShowAs}" >
</apex:inputfield>

</apex:pageBlockSection>


<apex:pageBlockSection title="Other Information" columns="4">
<apex:inputfield value="{!Event.Location}" >
</apex:inputfield>
<apex:inputfield value="{!Event.ShowAs}" >
</apex:inputfield>
</apex:pageBlockSection>

<apex:pageBlockSection title="Description Information" columns="4">
<apex:inputfield value="{!Event.Description}" >
</apex:inputfield>
</apex:pageBlockSection>
</apex:pageblock>


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

controller
(to prepopulate values in edit screen)
public class macalendarentry {
   public event event{get;set;}
    public macalendarentry(ApexPages.StandardController stdController){

        if(event == null) event = new Event();
        event.ownerid = ApexPages.currentPage().getParameters().get('ownerID');
        event.whatid = ApexPages.currentPage().getParameters().get('whatid');
     
    }
}

button
execute javascript/onclick javascript
window.open('/apex/ADD2Calendar?whatid={!Easy_Opportunity__c.Id}&ownerid={!$User.Id}', '_blank', 'toolbar=0,location=0,menubar=0');

Thursday 16 June 2016

Visualforce - google maps

visual force - google maps visualforce page

fields required:

formula text
Coordinates__c
text( GPS_Coordinates__Latitude__s )&" "&Text(GPS_Coordinates__Longitude__s )

geolocation
GPS_Coordinates__c
decimal 7 places

visualforce page

<apex:page standardController="pba__Property__c">

<head>

<script type="text/javascript" src="https://maps.google.com/maps/api/js?&sensor=false"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">

$(document).ready(function() {

  var myOptions = {
  draggable: false,
    zoom: 18,
    mapTypeId: google.maps.MapTypeId.SATELLITE,
    mapTypeControl: false
  }

  var map;
  var marker;

  var geocoder = new google.maps.Geocoder();

 
   var address = "{!pba__Property__c.Coordinates__c}";

 var infowindow = new google.maps.InfoWindow({
    content: "<b>{!pba__Property__c.pba__Address_pb__c}</b><br>{!pba__Property__c.pba__City_pb__c}<br>{!pba__Property__c.State__c}, {!pba__Property__c.pba__PostalCode_pb__c}<br>{!pba__Property__c.Country__c}"
  });

 

   geocoder.geocode( { address: address}, function(results, status) {

    if (status == google.maps.GeocoderStatus.OK && results.length) {
      if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {

        //create map
        map = new google.maps.Map(document.getElementById("map"), myOptions);

        //center map
        map.setCenter(results[0].geometry.location);

        //create marker
        marker = new google.maps.Marker({
            position: results[0].geometry.location,
            map: map,
            title: "Property"
        });

        //add listeners
        google.maps.event.addListener(marker, 'click', function() {
          infowindow.open(map,marker);
        });
        google.maps.event.addListener(infowindow, 'closeclick', function() {
          map.setCenter(marker.getPosition());
        });

      }

    } else {
      $('#map').css({'height' : '25px'});
      $('#map').html("Oops! Property's  address could not be found, please make sure the address is correct.");
      resizeIframe();
    }
  });

  function resizeIframe() {
    var me = window.name;
    if (me) {
      var iframes = parent.document.getElementsByName(me);
      if (iframes && iframes.length == 1) {
        height = document.body.offsetHeight;
        iframes[0].style.height = height + "px";
      }
    }
  }

});
</script>

<style>
#map {
  font-family: Arial;
  font-size:12px;
  line-height:normal !important;
  height:250px;
  background:transparent;
}
</style>

</head>

<body>
<div id="map"></div>
</body>
</apex:page>
                                     



Sunday 12 June 2016

Apex - maps sets and lists - data collections

lists - orders index numbers starting with 0, 1, 2, 3,........

List<string> ListOfCities = new List<string>();

List<string> ListOfStates = new List<string> {'NY', 'LA', 'LV'}();

List<account> AccountToDelete = new List<account> ();//This will be null

List<List<Set<Integer>>> myNestedList = new List<List<Set<Integer>>>();

String [] ListOfStates = new List<string>();

Below are some most frequently used methods.

size()
add()
get()
clear()
set()

//Initialize the List
List<string> ListOfStatesMethod = new List<string>();

//This statement would give null as output in Debug logs
System.debug('Value of List'+ ListOfStatesMethod);

//Add element to the list using add method
ListOfStatesMethod.add('New York');
ListOfStatesMethod.add('Ohio');

//This statement would give New York and Ohio as output in Debug logs
System.debug('Value of List with new States'+ ListOfStatesMethod);

//Get the element at the index 0
String StateAtFirstPosition = ListOfStatesMethod.get(0);

//This statement would give New York as output in Debug log
System.debug('Value of List at First Position'+ StateAtFirstPosition);

//set the element at 1 position
ListOfStatesMethod.set(0, 'LA');

//This statement would give output in Debug log
System.debug('Value of List with element set at First Position'+ ListOfStatesMethod[0]);

//Remove all the elements in List
ListOfStatesMethod.clear();

//This statement would give output in Debug log
System.debug('Value of List'+ ListOfStatesMethod);

sets - unorderd and unique

Set<string> ProductSet = new Set<string>{'Phenol', 'Benzene', 'H2SO4'};
System.debug('Value of ProductSet'+ProductSet);

//Adds an element to the set
//Define set if not defined previously
Set<string> ProductSet = new Set<string>{'Phenol', 'Benzene', 'H2SO4'};
ProductSet.add('HCL');
System.debug('Set with New Value '+ProductSet);

//Removes an element from set
ProductSet.remove('HCL');
System.debug('Set with removed value  '+ProductSet);

//Check whether set contains the particular element or not and returns true or false
ProductSet.contains('HCL');
System.debug('Value of Set with all values '+ProductSet);

maps -unordered- case sensitive -  key value pair

//Initialize the Map
Map<string, string> ProductCodeToProductName = new Map<string, string> {'1000'=>'HCL', '1001'=>'H2SO4'};

//This statement would give as output as key value pair in Debug log
System.debug('value of ProductCodeToProductName'+ProductCodeToProductName);

// Define a new map
Map<string, string> ProductCodeToProductName = new Map<string, string>();

// Insert a new key-value pair in the map where '1002' is key and 'Acetone' is value
ProductCodeToProductName.put('1002', 'Acetone');

// Insert a new key-value pair in the map where '1003' is key and 'Ketone' is value
ProductCodeToProductName.put('1003', 'Ketone');

// Assert that the map contains a specified key and respective value
System.assert(ProductCodeToProductName.containsKey('1002'));
System.debug('If output is true then Map contains the key and output is :'+ProductCodeToProductName.containsKey('1002'));

// Retrieves a value, given a particular key
String value = ProductCodeToProductName.get('1002');
System.debug('Value at the Specified key using get function: '+value);

// Return a set that contains all of the keys in the map
Set SetOfKeys = ProductCodeToProductName.keySet();
System.debug('Value of Set with Keys '+SetOfKeys);

Apex - Variables and data types – strings, dates, numbers, booleans, and sObjects

Variables and data types – strings, dates, numbers, booleans, and sObjects

Data types are simply the different types of variables you can have
String bestteam = 'PortsmouthFC';
Integer numberofpoints = 3;

Decimal goalratio = 0.9;
Boolean winner = true;
Date next match = Date.today().addDays(30);

DateTime now = DateTime.now();
Contact me = [SELECT FirstName, LastName 
                 FROM Contact 
                 WHERE Email = 'iain.banks@email.com'

                 LIMIT 1];
Strings are simply text variables
Integers and decimals are used in number, currency, and percentage fields in Salesforce. Integers are for number fields without any decimal places.
Booleans are just either true or false. They’re used with checkboxes in Salesforce.

Apex - basic trigger and unit test explained

Apex - basic trigger and its unit test explained


Basic Trigger

// trigger name "addcompanyname" on "user" (sobject)
trigger addcompanyname on User (before insert) {

//for every user in trigger.new do whats in the bracket (known as loop)
    for (User thisuser : Trigger.new) {
//companyname field   is apre ltd  (is possible to add more values)           
        thisuser.companyname = 'aspre ltd';          
    }
}


notes:
trigger - starting point for all triggers

addcompanyname - name of trigger can be anything

user - sobject  for a full list of standard salesforce objects and for a full list of object refeence

before insert - trigger will fire before record inserted/created in database for list of trigger operations

thisuser - variable that represent each specific user in the loop as it iterates one by one across all users in the list trigger.new

trigger.new -returns a list of the new versions of the sObject recordsthat are captured in trigger. this list only available in insert/update triggers and record can only be changed in before triggers for list of trigger context variables

Unit Test for basic trigger
every trigger requires a unit test to push code from sandbox to production -Salesforce requires at least 75% of your code to be “tested” before deploying

tests what the code should do

//all tests start with @isTest 
@isTest
//this line defines the class method access and name (for tests below will never chnge)
public class test_addcompanyname
    static testMethod void insertNewUser() {
     
// how to instantiate new user
       User userToCreate = new User();
     
       // create all mandatory fields
       userToCreate.FirstName = 'Iain';
       userToCreate.LastName  = 'Banks';
       userToCreate.Email     = 'iain.banks@email.com';
       userToCreate.Username  = 'iain.banks@email.com.sandbox';
       userToCreate.Alias     = 'ilearnapex';
       userToCreate.ProfileId = '00ei0000000rTfp';
       userToCreate.TimeZoneSidKey    = 'America/Denver';
       userToCreate.LocaleSidKey      = 'en_US';
       userToCreate.EmailEncodingKey  = 'UTF-8';
       userToCreate.LanguageLocaleKey = 'en_US';

       // we explicitly insert our user into our Salesforce database using this DML code otherwise it will not eneter the dsatabase
       insert userToCreate;
    }
}

notes

@isTest – this tells Salesforce we’re writing test code

test_addcompanyname - name of test class

testMethod – this tells Salesforce once again that we’re doing a test

insertNewUser – the name we gave our test method.

User – the API name of any Salesforce sObject, in this case, the standard User object.

userToCreate – the variable we named to store our user record.

’00ei0000000rTfp’ – this is the ID of the profile we’ll give to our user. Note that your org will have different IDs. 15-digit record IDs can be found in the URL of any record. Like text, IDs need to be wrapped in single quotes.

insert – the DML statement to “create” a record in an org. The record only exists in our code until we save it using DML.