• SFDC Rohit
  • NEWBIE
  • 33 Points
  • Member since 2018
  • Technical Architect


  • Chatter
    Feed
  • 1
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 10
    Replies
Hi,

I am having difficulty writing a test class for an apex class that doesn't invoke any changes in Salesforce. Instead, it invokes changes to an external system. I don't even know where to begin with this test class. I figured it would help if I give you the code:
 
global class AsyncRequest {

    //@HttpPost
    @future (callout=true)
    global static void postRequest(string contactJSON, 
                                  string flAdminUser, 
                                  string flUserId,
                                  string sfUserId){
                Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint('https://dev-api-example.com/api/v2.5/integrations/salesforce/profile');
        request.setMethod('POST');
        //request.setHeader('FL-SECRET', 'Example.secret');
        request.setHeader('FL-SECRET', 'SF2018/Example');
        request.setHeader('FL-ADMIN-USER', flAdminUser);
        request.setHeader('Content-Type', 'application/json');
        request.setHeader('FL-USER-ID', flUserId);
        request.setHeader('SF-USER-ID', sfUserId);
        // Set the body as a JSON object
        request.setBody(contactJSON);
        HttpResponse response = http.send(request);
        // Parse the JSON response
        if (response.getStatusCode() != 200) {
            System.debug('The status code returned was not expected: ' +
                response.getStatusCode() + ' ' + response.getStatus());
        } else {
            System.debug('The status code returned was not expected: ' +
                response.getStatusCode() + ' ' + response.getStatus());
            System.debug(response.getBody());
        }
            
    }
}

Then here is another .apext file that I would need to test as well
 
trigger AsyncToFarmLead on Contact (after update) {
    
    String FlAdminUser;
    String contactJSON;
    String FlUserId;
    String SfUserId;
    
    for(Contact a : Trigger.New) {
        
        Map<String,Object> conMap = (Map<String,Object>)JSON.deserializeUntyped(JSON.serialize(a));
        
        removeAttributes(conMap, 'Account');
        removeAttributes(conMap, 'FL_ADMIN_USER__c');
        removeAttributes(conMap, 'FarmLead_URL__c');
        removeAttributes(conMap, 'AccountId');
        removeAttributes(conMap, 'FarmLead_Secret_key__c');
        
        String contactJSON = (JSON.serializePretty(conMap));
        
        if(a.FL_ADMIN_USER__c != null) {
            FlAdminUser = a.FL_ADMIN_USER__c;
        } else {
            FlAdminUser = 'nullVal';
        }
        System.debug('FL_ADMIN_USER__c: ' + FlAdminUser);
        
        if(a.MK_fl_user_id__c != null) {
            FlUserId = a.MK_fl_user_id__c;
        } else {
            FlUserId = 'nullVal';
        }
        System.debug('MK_fl_user_id__c: ' + FlUserId);
        
        if(a.Id != null) {
            SfUserId = a.Id;
        } else {
            SfUserId = 'nullVal';
        }
        System.debug('Id: ' + SfUserId);

        try{
            System.debug('JSON being passed: ' + contactJSON);
            AsyncRequest.postRequest(contactJSON, FlAdminUser, FlUserId, SfUserId);
        } catch (Exception e) {
             Messaging.SingleEmailMessage mail=new Messaging.SingleEmailMessage();
             String[] toAddresses = new String[] {'EXAMPLE@Email.com'};
             mail.setToAddresses(toAddresses);
             mail.setReplyTo('EXAMPLE@Email.com');
             mail.setSenderDisplayName('Apex error message');
             mail.setSubject('Error from Org : ' + UserInfo.getOrganizationName());
             mail.setPlainTextBody(e.getMessage());
             Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
        }
    }
    
    private void removeAttributes(Map<String,Object> jsonObj, String attribute)  {
        for(String key : jsonObj.keySet()) {
            if(key == attribute) {
                jsonObj.remove(key);
            } else {
                if(jsonObj.get(key) instanceof Map<String,Object>) {
                    removeAttributes((Map<String,Object>)jsonObj.get(key), attribute);
                }
                if(jsonObj.get(key) instanceof List<Object>) {
                    for(Object listItem : (List<Object>)jsonObj.get(key)) {
                        if(listItem instanceof Map<String,Object>)  {
                            removeAttributes((Map<String,Object>)listItem, attribute);
                        }
                    }
                }
            }
        }  
    }
}

 
 I have 3 objects account, contact and cases. Account is related to contact and contact is related to cases..How to show all in one vf page?
Final output comming as Account and Opportunity ID. i want to display Account name and opportunity names

public class Map_Opportunities {
    public Map<string,List<Opportunity>> oppMap        {set;get;}
    public List<Opportunity> optyList                {set;get;}
    
    public Map_Opportunities(){
        oppMap = new Map<string,List<Opportunity>>();  
        
        for (Account acc: [SELECT name,(SELECT Name FROM Opportunities)FROM Account]){            
            oppMap.put(acc.Name,acc.Opportunities);            
        }        
    }
}
///VF
<apex:page controller="Map_Opportunities">
    <apex:form >
        <apex:pageBlock title="Account Map">
            <apex:pageBlockButtons location="Bottom" style="opportunity">                
            </apex:pageBlockButtons>
            <apex:pageBlockSection columns="1" collapsible="false" >
                <apex:pageBlockTable value="{!oppMap}" var="m">
                    <apex:column value="{!m}" headerValue="Account Name"/>
                    <apex:column value="{!oppMap[m]}" headerValue="Opportunity Name"/>
                </apex:pageBlockTable>                
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>
 
Hi, I wrote a trigger to prevent the lead duplicates based on the mobile number and Email.

Am wondering to write a test class for the same trigger. My test class was not passed .can anyone give me the suggestion to how to write a flow for the test class.

My Trigger  code

Trigger leaddup17 on lead(before insert, After Update) {


    Set<String> setEmail = new Set<String>();
    Set<String> setnumber = new Set<String>();
    Set<String> setId = new Set<String>();
    
    for (Lead ld: Trigger.new) {
        if (ld.Phone != Null ||  ld.MobilePhone!=Null || ld.Whatsapp_Mobile__c!=Null || ld.Mobile_Additional__c!=Null|| ld.Phone_Additional__c!=Null 
            ){
                    
            setnumber.add(ld.MobilePhone);
            setnumber .add(ld.Whatsapp_Mobile__c);
            setnumber .add(ld.Mobile_Additional__c);
            setnumber .add(ld.Phone);
            setnumber .add(ld.Phone_Additional__c);
           
          }
        
        if (ld.Email!=null || ld.E_Mail_Additional__c!=Null){
            setEmail.add(ld.Email);
             setEmail.add(ld.Email);
             setEmail.add(ld.E_Mail_Additional__c);
            
        }
        setId.add(ld.id);
    }
        
    List<Lead> lstExistingLead = [Select id,Phone,Email,E_Mail_Additional__c,MobilePhone,Whatsapp_Mobile__c,Phone_Additional__c,Mobile_Additional__c from Lead where  ((email in :setEmail or E_Mail_Additional__c in : setEmail ) or
     (Phone in :setnumber or Phone_Additional__c in : setnumber  or Mobile_Additional__c in : setnumber   or Whatsapp_Mobile__c in :setnumber   or
     MobilePhone in : setnumber))    and (id not in :setId)];
    
    map < string, Lead > LeadsMap = new map < String, Lead > ();
   

    for (Lead ld: lstExistingLead) {
        if (ld.Email!=null || ld.E_Mail_Additional__c!=Null || ld.Phone != Null ||  ld.MobilePhone!=Null || ld.Whatsapp_Mobile__c!=Null || ld.Mobile_Additional__c!=Null|| ld.Phone_Additional__c!=Null )
        {
        
            LeadsMap .put(ld.Phone, ld);
             LeadsMap .put(ld.MobilePhone, ld);
              LeadsMap .put(ld.Whatsapp_Mobile__c, ld);
               LeadsMap .put(ld.Phone_Additional__c, ld);
                LeadsMap .put(ld.Mobile_Additional__c, ld);
                LeadsMap .put(ld.Email, ld);
             LeadsMap .put(ld.E_Mail_Additional__c, ld);
                 
        }   
          setId.add(ld.id);
    }

    for (Lead ld: Trigger.new) 
    {
    
    
        if ( Trigger.isInsert &&  ld.Email!=null || ld.E_Mail_Additional__c!=Null &&  ld.Phone == Null ||  ld.MobilePhone==Null || ld.Whatsapp_Mobile__c==Null || ld.Mobile_Additional__c==Null|| ld.Phone_Additional__c==Null 
        
        && ld.Email != trigger.oldMap.get(ld.Id).Email  ||
         ld.E_Mail_Additional__c!= trigger.oldMap.get(ld.Id).E_Mail_Additional__c)
         
        {
            if ((ld.Email != null && LeadsMap .get(ld.Email) != null) || (ld.E_Mail_Additional__c!= null && LeadsMap .get(ld.E_Mail_Additional__c) != null) )
             {
                ld.adderror('Lead already exist with this  Email. You cannot create a duplicate leads.');
            }
        }

        if ( Trigger.isInsert || (ld.Phone != trigger.oldMap.get(ld.Id).Phone) ||
        (ld.MobilePhone!= trigger.oldMap.get(ld.Id).MobilePhone)||
        (ld.Whatsapp_Mobile__c!= trigger.oldMap.get(ld.Id).Whatsapp_Mobile__c)||
        (ld.Mobile_Additional__c!= trigger.oldMap.get(ld.Id).Mobile_Additional__c)||
        (ld.Phone_Additional__c!= trigger.oldMap.get(ld.Id).Phone_Additional__c))
        {
            if ((ld.Phone != null && LeadsMap.get(ld.Phone) != null) ||
           ( ld.MobilePhone!= null && LeadsMap.get(ld.MobilePhone) != null)||
            (ld.Whatsapp_Mobile__c!= null && LeadsMap.get(ld.Whatsapp_Mobile__c) != null)||
            (ld.Mobile_Additional__c!= null && LeadsMap.get(ld.Mobile_Additional__c) != null)||
            (ld.Phone_Additional__c!= null && LeadsMap.get(ld.Phone_Additional__c) != null)) {
                ld.adderror('Lead already exist with this Phone Number . You cannot create a duplicate leads.');
            }
            setId.add(ld.id);
        }
        
        
        
         if ( (Trigger.isupdate  && (ld.Email!=Null || ld.E_Mail_Additional__c!=Null)) && ((ld.Email != trigger.oldMap.get(ld.Id).Email ) ||
        (ld.E_Mail_Additional__c!= trigger.oldMap.get(ld.Id).E_Mail_Additional__c)))
         
        {
            if ((ld.Email != null && LeadsMap .get(ld.Email) != null) || (ld.E_Mail_Additional__c!= null && LeadsMap .get(ld.E_Mail_Additional__c) != null) )
             {
                ld.adderror('Lead already exist with this  Email. You cannot create a duplicate leads.');
            }
        }

        if ((Trigger.isupdate && (ld.Phone!=Null ||ld.MobilePhone!=Null ||ld.Whatsapp_Mobile__c!=Null || ld.Mobile_Additional__c!=Null ||
     ld.Phone_Additional__c!=Null)) &&  ((ld.Phone != trigger.oldMap.get(ld.Id).Phone) ||
        (ld.MobilePhone!= trigger.oldMap.get(ld.Id).MobilePhone)||
        (ld.Whatsapp_Mobile__c!= trigger.oldMap.get(ld.Id).Whatsapp_Mobile__c)||
        (ld.Mobile_Additional__c!= trigger.oldMap.get(ld.Id).Mobile_Additional__c)||
        (ld.Phone_Additional__c!= trigger.oldMap.get(ld.Id).Phone_Additional__c)))
        {
            if ((ld.Phone != null && LeadsMap.get(ld.Phone) != null) ||
           ( ld.MobilePhone!= null && LeadsMap.get(ld.MobilePhone) != null)||
            (ld.Whatsapp_Mobile__c!= null && LeadsMap.get(ld.Whatsapp_Mobile__c) != null)||
            (ld.Mobile_Additional__c!= null && LeadsMap.get(ld.Mobile_Additional__c) != null)||
            (ld.Phone_Additional__c!= null && LeadsMap.get(ld.Phone_Additional__c) != null)) {
                ld.adderror('Lead already exist with this Phone Number . You cannot create a duplicate leads.');
            }
            
            setId.add(ld.id);
        }
        
    }
    
}
 
Hi,
I have the following code

Opportunity oppty = new Opportunity();
oppty.Name='123';
insert oppty;

Product2 pr = new Product2();
pr.Name = '123';
pr.Description = 'my product';

myJunctionObject obj = new myJunctionObject();
obj.Product2.id  = pr.id; //
obj.Opportunity.id  = oppty.id;
insert obj;

I am getting the error - Attempt to dereference a null object.Null pointer exception at 'insert obj;'
Can anyone suggest a solution to overcome this

Thanks,
Abhilash
this is apex page:

public class DynamicSoql {
    public List<Account> accs {set;get;}
    public string accName {set;get;}
    public string accIndustry {set;get;}
    public void Search(){
        accs=[select name,industry from Account where name=:accName and industry=:accIndustry];
    }
     public void dynamicSearch(){
        string query='select id,name,industry from Account';
        if((accName!=null && accName!='') && (accIndustry!='' && accIndustry!=null)){
            query=query+'where name=\''+accName+'\' and industry=\''+accIndustry+'\''; 
        }else{
            if((accName!=null && accName!='')){
                query=query+'where name=\''+accName+'\'';
            }else{
                if((accIndustry!='' && accIndustry!=null)){
                    query=query+'where industry=\''+accIndustry+'\'';
                }
            }
        }
       accs=Database.query(query);     
    }
  
    
  }


This is VF page

<apex:page controller="DynamicSoql">
    <apex:form>
        <apex:pageBlock title="AdyInformation">
            <apex:pageBlockButtons location="top">
                <apex:commandButton value="search" action="{!Search}" />
               <apex:commandButton value="DynamicQuery" action="{!dynamicSearch}"/>
            </apex:pageBlockButtons>
            <apex:pageBlockSection>
                <apex:pageBlockSectionItem>
                    <apex:outputLabel>EnterName</apex:outputLabel>
                    <apex:inputText value="{!accName}" />
                        </apex:pageBlockSectionItem>
                <apex:pageBlockSectionItem>
                    <apex:outputLabel>EnterIndustry</apex:outputLabel>
                    <apex:inputText value="{!accIndustry}" />
                </apex:pageBlockSectionItem>
            </apex:pageBlockSection>
        </apex:pageBlock>
        <apex:pageBlock title="Success" rendered="{! !ISNULL(accs)}">
            <apex:pageBlockTable value="{!accs}" var="a">
                <apex:column value="{!a.name}" />
                <apex:column value="{!a.industry}" />
            </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:form>
</apex:page>

         My Error is 
System.QueryException: unexpected token: =
Error is in expression '{!dynamicSearch}' in component <apex:commandButton> in page dynamicsoql: Class.DynamicSoql.dynamicSearch: line 21, column 1
Class.DynamicSoql.dynamicSearch: line 21, column 1

Hi all,

I have created a VF page with a form that allow users to create a record in Salesforce, it 100% working but I've received couple of feedbacks from my users that the form is too long.

To make it short I need to divide the form into different pages but what I wanted to know is if its possible for me to use pagination on the form. 

Any ideas are welcome on how to make a form short without having to create multiple Visualforce pages as I am not sure how would that work without losing the values inputted from the previous page.

Thank you!

Hi,

I am having difficulty writing a test class for an apex class that doesn't invoke any changes in Salesforce. Instead, it invokes changes to an external system. I don't even know where to begin with this test class. I figured it would help if I give you the code:
 
global class AsyncRequest {

    //@HttpPost
    @future (callout=true)
    global static void postRequest(string contactJSON, 
                                  string flAdminUser, 
                                  string flUserId,
                                  string sfUserId){
                Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint('https://dev-api-example.com/api/v2.5/integrations/salesforce/profile');
        request.setMethod('POST');
        //request.setHeader('FL-SECRET', 'Example.secret');
        request.setHeader('FL-SECRET', 'SF2018/Example');
        request.setHeader('FL-ADMIN-USER', flAdminUser);
        request.setHeader('Content-Type', 'application/json');
        request.setHeader('FL-USER-ID', flUserId);
        request.setHeader('SF-USER-ID', sfUserId);
        // Set the body as a JSON object
        request.setBody(contactJSON);
        HttpResponse response = http.send(request);
        // Parse the JSON response
        if (response.getStatusCode() != 200) {
            System.debug('The status code returned was not expected: ' +
                response.getStatusCode() + ' ' + response.getStatus());
        } else {
            System.debug('The status code returned was not expected: ' +
                response.getStatusCode() + ' ' + response.getStatus());
            System.debug(response.getBody());
        }
            
    }
}

Then here is another .apext file that I would need to test as well
 
trigger AsyncToFarmLead on Contact (after update) {
    
    String FlAdminUser;
    String contactJSON;
    String FlUserId;
    String SfUserId;
    
    for(Contact a : Trigger.New) {
        
        Map<String,Object> conMap = (Map<String,Object>)JSON.deserializeUntyped(JSON.serialize(a));
        
        removeAttributes(conMap, 'Account');
        removeAttributes(conMap, 'FL_ADMIN_USER__c');
        removeAttributes(conMap, 'FarmLead_URL__c');
        removeAttributes(conMap, 'AccountId');
        removeAttributes(conMap, 'FarmLead_Secret_key__c');
        
        String contactJSON = (JSON.serializePretty(conMap));
        
        if(a.FL_ADMIN_USER__c != null) {
            FlAdminUser = a.FL_ADMIN_USER__c;
        } else {
            FlAdminUser = 'nullVal';
        }
        System.debug('FL_ADMIN_USER__c: ' + FlAdminUser);
        
        if(a.MK_fl_user_id__c != null) {
            FlUserId = a.MK_fl_user_id__c;
        } else {
            FlUserId = 'nullVal';
        }
        System.debug('MK_fl_user_id__c: ' + FlUserId);
        
        if(a.Id != null) {
            SfUserId = a.Id;
        } else {
            SfUserId = 'nullVal';
        }
        System.debug('Id: ' + SfUserId);

        try{
            System.debug('JSON being passed: ' + contactJSON);
            AsyncRequest.postRequest(contactJSON, FlAdminUser, FlUserId, SfUserId);
        } catch (Exception e) {
             Messaging.SingleEmailMessage mail=new Messaging.SingleEmailMessage();
             String[] toAddresses = new String[] {'EXAMPLE@Email.com'};
             mail.setToAddresses(toAddresses);
             mail.setReplyTo('EXAMPLE@Email.com');
             mail.setSenderDisplayName('Apex error message');
             mail.setSubject('Error from Org : ' + UserInfo.getOrganizationName());
             mail.setPlainTextBody(e.getMessage());
             Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
        }
    }
    
    private void removeAttributes(Map<String,Object> jsonObj, String attribute)  {
        for(String key : jsonObj.keySet()) {
            if(key == attribute) {
                jsonObj.remove(key);
            } else {
                if(jsonObj.get(key) instanceof Map<String,Object>) {
                    removeAttributes((Map<String,Object>)jsonObj.get(key), attribute);
                }
                if(jsonObj.get(key) instanceof List<Object>) {
                    for(Object listItem : (List<Object>)jsonObj.get(key)) {
                        if(listItem instanceof Map<String,Object>)  {
                            removeAttributes((Map<String,Object>)listItem, attribute);
                        }
                    }
                }
            }
        }  
    }
}

 
Hi all,

I have given App builder transition exam 6 months back which I have passed successfully but now again I am getting mail from Salesforce to regive this exam as Salesforce Developer certification is getting discontinued soon. Should I give this exam again?
P.S. My App builder transition certificate got expired later as I was not able to give its maitaince exam.
Error is :

Validation Errors While Saving Record(s)
There were custom validation error(s) encountered while saving the affected record(s). The first validation error encountered was "Apex trigger ContactBeforeInsert1 caused an unexpected exception, contact your administrator: ContactBeforeInsert1: execution of BeforeDelete caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.ContactBeforeInsert1: line 2, column 1". 

My code :
trigger ContactBeforeInsert1 on Contact (before insert, before update, before delete) {
    for(Contact objContact : Trigger.new){
        if(trigger.isBefore){
            objContact.Description = 'Contact is created by ' + UserInfo.getUserName() + '. Description is added in before insert Trigger.';
         }
        if(trigger.isUpdate)
        {  
           objContact.Description = objContact.Description + 'Contact is updated by ' +UserInfo.getUserName() + '. Description is updated in before update Trigger.';
        }
       if(trigger.isDelete)
        {  
          // Create a task to track that contact is deleted
          Task objTask = new Task();       
          objTask.Subject = 'Contact Deleted';    
          objTask.Priority = 'Normal';        
          objTask.Status = 'Completed';                  
          objTask.Description = 'Contact ' + objContact.Id + ' is deleted by ' + UserInfo.getUserName() + '. Description on contact was ' + objContact.Description;
          try{
              insert objTask;
          }
          catch(Exception ex){
              
          }
        }
    }
}