• Derrick Abbey
  • NEWBIE
  • 175 Points
  • Member since 2016

  • Chatter
    Feed
  • 6
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 3
    Questions
  • 15
    Replies
Hello guys
First post
I'm a newbie in Salesforce trying to understand how i can write test classes
I need to write a test class of the following class:
public class RelatedListEditController {
    @AuraEnabled( cacheable=true )  
    public static List < sObject > fetchRecords( String listValues ) {  
        List < String > strList = listValues.split( ',' );  
        if ( strList.size() >= 3 ) {  
            String recordId = strList.get( 0 );  
            String objectName = strList.get( 1 );  
            String parentFieldAPIName = strList.get( 2 );              
            String strSOQL = 'SELECT Id FROM ' + objectName + ' WHERE ' + parentFieldAPIName + ' = \'' + recordId + '\'' + ' WITH ' + 'SECURITY_ENFORCED';  
            strSOQL += ' LIMIT 20';
            return Database.query( strSOQL );  
        } else   
            return null;  
    }   
}
Any help would be appreciated
I just want to learn how i can do it
Hi Friends,
Is it possible or easy way to do System.Debug dynamic SOQL statements, want to know what will be the internal parameters build in the query before executing
For eg:
 
trigger AccountDeletion on Account (before delete) {
   
    // Prevent the deletion of accounts if they have related opportunities.
    for (Account a : [SELECT Id FROM Account
                     WHERE Id IN (SELECT AccountId FROM Opportunity) AND
                     Id IN :Trigger.old]) {
        Trigger.oldMap.get(a.Id).addError(
            'Cannot delete account with related opportunities.');
    }
    
}


Can somebody provide a sample code to have a debug log in the For loop, so I can know what are the parameters get passed.
or is there any way the SOQL query to be passed to a string so I can see what's going on.

Thanks,
James George

Our org in new to case managment and we are using email-to-case
We receive emails from a third party system that has a formatted body.
We would like to view the formatted body instead of the cse description that is plain text
I added a RichText field to save the body into and have tried a trigger, workflow and process builder.

Here is the section of the trigger ( before insert )
// bulkify by only doing this if Trigger.New.Size == 1
if ( true ) {
// Insert Email Body into custom field
EmailMessage emailMsg = [SELECT id, ParentId, FromName, FromAddress, HtmlBody, TextBody
FROM EmailMessage
WHERE Id = :cs.SourceId
AND Incoming = true
Limit 1];
if ( emailMsg != null && emailMsg.HtmlBody != null) {
cs.lutd_Description_Rich__c = 'Not Null htmlBody';
//cs.lutd_Description_Rich__c = emailMsg.HtmlBody;
} else if ( emailMsg != null && emailMsg.TextBody != null){
cs.lutd_Description_Rich__c = 'Checking textBody'; //emailMsg.textBody;
} else {
cs.lutd_Description_Rich__c = 'Null email message';
}
//cs.lutd_Description_Rich__c = cs.description ; works as expected
}
I dont get the htmlBody.
In the developer console I see the htmlBody using the same SOQL subtitutng the SourceId of the case. 


 
Hello All, 

   Newbie to Salesforce and i need help writing a test class - schedule apex + consuming csv file. Below is the code - 
=======================
global class FilePOC_ScheduleClass implements Schedulable {
 
     global Blob csvFileBody;
     global string csvAsString;
    
   global void execute(SchedulableContext sc)
   
    {   
        
        try{
            
            ContentVersion cv=[SELECT id,ContentDocumentId,versiondata
                                    FROM Contentversion
                                   WHERE Id='0990o00000B9TYOA3' ];
        
            csvFileBody =cv.VersionData;
            csvAsString= csvFileBody.toString();
        
            // Logic to split the file contents 
            List<String> csvFileLines= csvAsString.split('\n');
            List<String> newList = new List<String>();
    
            // Logic to remove the fist line - the column name
            for(Integer i=1;i<csvFileLines.size();i++){
                newList.add(csvFileLines[i]);
            }
    
            List<Account> accList = new List<Account>();
            
            for(integer i=0;i<newList.size();i++){
                
                List<String> values = newList[i].split(',');
                
                // Prepare the Account fields for insert
                Account accObj = new Account();
                accObj.Name = values[0];
                accObj.accountnumber = values[1];
                accObj.Type = values[2];
                accObj.AccountSource = values[3];
                accObj.Industry = values[4];
                
                acclist.add(accObj);
            }
            
            // Insert the account collection
            insert acclist;
        }
        catch (Exception e)
        {
            
        }
    }
}
Please help !! 
Thanks 
Rey....
 
Hello I'm trying to write a test class for Rest API post Method which i wrote, need help in writing test method. This gives me System.DmlException: Update failed. First exception on row 0; first error: MISSING_ARGUMENT, Id not specified in an update call:". Please help
trigger RadarFirst on Patient_Satisfaction__c (after update) {
for (Patient_Satisfaction__c cc : Trigger.new){
if(cc.Patient_Relation__c!= Trigger.oldMap.get(cc.id).Patient_Relation__c && cc.Patient_Relation__c != null) {
      if(cc.Patient_Relation__c.contains('Referred to Privacy Office')){
      RadarUpdate.postcallout(cc.id);
      }
  }
}
}
 
public class RadarUpdate {
    @future (callout=true)
	public static void postcallout(string Id) { 
	Patient_Satisfaction__c c = [select id, Name, Reporter_Phone__c,Reporter_First_Name__c,Reporter_Last_Name__c, Reporter_Email__c,
    Description_of_Feedback__c from Patient_Satisfaction__c where Patient_Relation__c ='Referred to Privacy Office' order by lastmodifiedDate desc limit 1];
    JSONGenerator gen = JSON.createGenerator(true);
	gen.writeStartObject();
	gen.writeObjectField('name', c.Name);
	gen.writeObjectField('incident_group_id', 7387);
    gen.writeObjectField('description',c.Description_of_Feedback__c);
	gen.writeFieldName('submitted_by');
	gen.writeStartObject();
	gen.writeStringField('given_name',c.Reporter_First_Name__c);
	gen.writeStringField('surname', c.Reporter_Last_Name__c);
	gen.writeStringField('phone',c.Reporter_Phone__c);
    gen.writeStringField('email',c.Reporter_Email__c);
	gen.writeEndObject();
	String jsonS = gen.getAsString(); 
	System.debug('jsonMaterials'+jsonS);
    Http http = new Http();
	HttpRequest request = new HttpRequest();
	request.setEndpoint('https://api.radarfirst.com/incidents');
	request.setMethod('POST');
	request.setHeader('Content-Type','application/json;charset=UTF-8');
	request.setHeader('User-agent', 'Salesforce-integration-client');
	request.setHeader('Authorization','Bearer 123');
    request.setBody(jsonS);
	// Set the body as a JSON object
	HttpResponse response = http.send(request);
	if (response.getStatusCode() != 201) {
    System.debug('The status code returned was not expected: ' +
        response.getStatusCode() + ' ' + response.getStatus());
	} else {
    System.debug(response.getBody());
	}
    }
}
@isTest
public class RadarUpdateTest{

    static testMethod void  postcalloutTest(){
        Account ac = new Account();
        ac.Name= 'Test';
        insert ac;
        
        Contact con= new Contact();
        con.AccountId= ac.Id;
        con.FirstName ='First Name';
        con.LastName = 'Test Contact';
        con.Phone= '7896541233';
        con.Email= 'Test@123.com';
        con.RUSH_Email__c= 'Test@123.com';
        insert con;
         		
        Patient_Satisfaction__c Pr = new Patient_Satisfaction__c();
        Pr.Primary_Campus__c = 'a1pP0000001lfaKIAQ';
        Pr.Primary_Facility__c= 'a1pP00000022FLRIA2';
        Pr.Primary_Location__c= 'a1pP00000022FLcIAM';
        Pr.Reporter__c=con.Id;
        Pr.Reporter_Phone__c=con.Id;
        Pr.Reporter_Email__c= 'Test@123.com';
        Pr.Description_of_Feedback__c= 'Testing Privacy office';
        Pr.Patient_Relation__c = 'Referred to Privacy Office';
        
     update Pr;
  	 RadarUpdate reqst=new RadarUpdate();
   	 String JsonMsg=JSON.serialize(reqst);
     Test.startTest();

    RestRequest req = new RestRequest(); 
    RestResponse res = new RestResponse();

    req.requestURI = '/services/apexrest/DemoUrl';  //Request URL
    req.httpMethod = 'POST';//HTTP Request Type
    req.requestBody = Blob.valueof(JsonMsg);
    RestContext.request = req;
    RestContext.response= res;
    RadarUpdate.postcallout(Pr.Id);
  
    update Pr;
    Test.stopTest();

   }
}

 
As part of the Lead conversion process I have disabled the ability to create an Opportunity and replaced the Opportunity creation via a Process builder flow.  However, I am experiencing an issue where a Task with an empty subject field is automatically created. Any thoughts/ideas how I can prevent the Task creation?

Thanks!
Our community was created by an outside vendor.  They used a custom font in the community, but I can't find the file that they used for the font.  I've checked our static resources as well as our file libraries, but I don't see any files that match the name in the CSS.  Here is the markup from the CSS that references where the custom file is.  Any ideas where I should be looking?
@font-face {
    font-family: 'GothamBold';
    src: url('/s/gothambold1.eot');
    src: url('/s/gothambold1.eot?#iefix') format('embedded-opentype'), url('/s/gothambold1.woff') format('woff'), url('/s/gothambold1.ttf') format('truetype'), url('/s/gothambold1.svg#svgFontName') format('svg');
}
Hi Community,

I'm hoping I can get some help with an issue I'm having with running the Date Loader via the command line.  My csv and mapping files work fine.  If I run an update using the Data Loader UI, then the update goes through just fine.  However, if I try to do an update with the same csv and same mapping file via the command line, I get an error stating "Id not specified in an update call."  When I look at the error file, it appears that Data Loader is having trouble parsing the CSV because the two fields I have specified are returned in the same value.  Here's and example:

"ID,OWNERID","ERROR"
"0060c00001QtX8EAAV,005a0000007tQb9AAE","Id not specified in an update call"

I've double checked that the csv is encoded in UTF-8 and I have it set to read UTF-8 in my config file.  Any thoughts?  Thank you.
Hello SF community,

I've created a visualforce page that I would like to display as a homepage component.  I've also created two custom fields on the user object that I would like that to be able to update based on the current user.  I'm using the "User" standard controller, here is a bit of my code for the input fields.  Do I need a custom controller or am I missing something simple?  I'm fairly new to Visualforce, so I'm still learning.  Thank you for any assistance!

<apex:page standardController="User" doctype="html-5.0">
                <apex:inputField value="{!User.Time_off_start_date__c }"
                    label="" style="width:125px" showDatePicker="false" type="date">
                </apex:inputField>
                <apex:inputField value="{! User.Time_off_end_date__c }"
                    label="" style="width:125px" showDatePicker="false" type="date">
                </apex:inputField>
                <apex:commandButton action="{! save }" value="Submit"/>
Hello guys
First post
I'm a newbie in Salesforce trying to understand how i can write test classes
I need to write a test class of the following class:
public class RelatedListEditController {
    @AuraEnabled( cacheable=true )  
    public static List < sObject > fetchRecords( String listValues ) {  
        List < String > strList = listValues.split( ',' );  
        if ( strList.size() >= 3 ) {  
            String recordId = strList.get( 0 );  
            String objectName = strList.get( 1 );  
            String parentFieldAPIName = strList.get( 2 );              
            String strSOQL = 'SELECT Id FROM ' + objectName + ' WHERE ' + parentFieldAPIName + ' = \'' + recordId + '\'' + ' WITH ' + 'SECURITY_ENFORCED';  
            strSOQL += ' LIMIT 20';
            return Database.query( strSOQL );  
        } else   
            return null;  
    }   
}
Any help would be appreciated
I just want to learn how i can do it
Hi Friends,
Is it possible or easy way to do System.Debug dynamic SOQL statements, want to know what will be the internal parameters build in the query before executing
For eg:
 
trigger AccountDeletion on Account (before delete) {
   
    // Prevent the deletion of accounts if they have related opportunities.
    for (Account a : [SELECT Id FROM Account
                     WHERE Id IN (SELECT AccountId FROM Opportunity) AND
                     Id IN :Trigger.old]) {
        Trigger.oldMap.get(a.Id).addError(
            'Cannot delete account with related opportunities.');
    }
    
}


Can somebody provide a sample code to have a debug log in the For loop, so I can know what are the parameters get passed.
or is there any way the SOQL query to be passed to a string so I can see what's going on.

Thanks,
James George

The below code works fine when I insert a new Contact with email. But when I update the Exchange Contact field on Opportunity it still keeps the email of the previous Contact. Please help me to resolve the issue.
 
public with sharing class PrimaryEmailOnExchange {
    public static void populatePrimaryEmailOnExchange(List<Opportunity> oppList) {

        Set<Id> conIds = new Set<Id>();

        for (Opportunity oppt : oppList) {
            if(oppt.Exchange_Contact__c != null){
                conIds.add(oppt.Exchange_Contact__c);
            }

        }

        Map<Id, Contact> mapCont = new Map<Id, Contact>([
                SELECT Id, Email FROM Contact WHERE Id IN : conIds
        ]);

        for (Opportunity oppt : oppList) {
            if (oppt.Exchange_Contact__c != null && oppt.Primary_Email__c == null) {
                    if (mapCont.containsKey(oppt.Exchange_Contact__c)) {
                        Contact c = mapCont.get(oppt.Exchange_Contact__c);
                        oppt.Primary_Email__c = c.Email;
                        oppt.ContactId = c.Id;

                    }
                }
            }
        }
    }
Here is the Trigger:
trigger populatePrimaryEmailOnExchange on Opportunity (before insert, before update, after update) {

    if (Trigger.isBefore || Trigger.isInsert || Trigger.isUpdate) {
        PrimaryEmailOnExchange.populatePrimaryEmailOnExchange(Trigger.new);
    }
}

 
I need to create a custom mass upload tool that allows a user to upload a csv file and create contacts and leads based on some logic. The file can have up to 100,000 rows. This tool needs to be a real time, meaning once the user uploads the file, the records need to be created and the user cannot wait. What would be the best way to do this with Apex code? Can databse.insert handle inserting upto 100k records?
Our org in new to case managment and we are using email-to-case
We receive emails from a third party system that has a formatted body.
We would like to view the formatted body instead of the cse description that is plain text
I added a RichText field to save the body into and have tried a trigger, workflow and process builder.

Here is the section of the trigger ( before insert )
// bulkify by only doing this if Trigger.New.Size == 1
if ( true ) {
// Insert Email Body into custom field
EmailMessage emailMsg = [SELECT id, ParentId, FromName, FromAddress, HtmlBody, TextBody
FROM EmailMessage
WHERE Id = :cs.SourceId
AND Incoming = true
Limit 1];
if ( emailMsg != null && emailMsg.HtmlBody != null) {
cs.lutd_Description_Rich__c = 'Not Null htmlBody';
//cs.lutd_Description_Rich__c = emailMsg.HtmlBody;
} else if ( emailMsg != null && emailMsg.TextBody != null){
cs.lutd_Description_Rich__c = 'Checking textBody'; //emailMsg.textBody;
} else {
cs.lutd_Description_Rich__c = 'Null email message';
}
//cs.lutd_Description_Rich__c = cs.description ; works as expected
}
I dont get the htmlBody.
In the developer console I see the htmlBody using the same SOQL subtitutng the SourceId of the case. 


 
Hello,

We have two objects in our org Custom1__c and Approver__c which are linked via junction object Approval__c. I have a vf page where I show approvers by stages by comparing Sales Price and Margin coming from Custom1 object against the approver records stored in Appover object and then I store the records in Approval object on click of Save button which is linked with Approver and Custom1. So I am basically inserting records in Approval object which are linked to respective Custom1 and Approver record.

There can be multiple stages of Approvers and each stage can have 1 or 2 Approvers depending on the country which I am managing on VF page through controller class. 

When the records are inserted in Approval object, I have a trigger written on Approval (After Insert) which calls a future callout class and sends detail of Approval records of stage 1 and related Custom1 and Approver info to webservice.

Now I want to build a logic in trigger on Approval Object(after update), which checks the the status(field on Approval) of previous stage approval record(s) and if they are Approved then call the future callout class with details of Approval records of next stage and if the last stage is approved then update the Custom1 record's Status field to Active . I am really struggling to build a dynamic logic which will do this no matter how many Approvers are there in a particular stage and how many no of stages are there.

I know this might sound confusing to many readers and I can answer any questions or doubts. Any help will be really appreciated.

Thanks in Advance!
 
trigger ClosedOpportunityTrigger on Opportunity (after insert) {

    List<Task> taskListToInsert = new List<Task>();
    
    for(Opportunity opp:Trigger.new)
    {
       if(opp.StageName == 'CloseWon') 
       {
           Task t = new Task();
           t.Subject = 'Follow Up Test task';
           t.WhatId = opp.Id;
           taskListToInsert.add(t);
       }      
    }
    
    if(taskListToInsert.size() > 0)
       {
          insert taskListToInsert; 
       } 
}
When I'm trying ti invoke this trigger I have this error

There was an unexpected error in your org which is preventing this assessment check from completing: System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [Discount_Percent__c]: [Discount_Percent__c]
Can anyone help me with this?
Hello All, 

   Newbie to Salesforce and i need help writing a test class - schedule apex + consuming csv file. Below is the code - 
=======================
global class FilePOC_ScheduleClass implements Schedulable {
 
     global Blob csvFileBody;
     global string csvAsString;
    
   global void execute(SchedulableContext sc)
   
    {   
        
        try{
            
            ContentVersion cv=[SELECT id,ContentDocumentId,versiondata
                                    FROM Contentversion
                                   WHERE Id='0990o00000B9TYOA3' ];
        
            csvFileBody =cv.VersionData;
            csvAsString= csvFileBody.toString();
        
            // Logic to split the file contents 
            List<String> csvFileLines= csvAsString.split('\n');
            List<String> newList = new List<String>();
    
            // Logic to remove the fist line - the column name
            for(Integer i=1;i<csvFileLines.size();i++){
                newList.add(csvFileLines[i]);
            }
    
            List<Account> accList = new List<Account>();
            
            for(integer i=0;i<newList.size();i++){
                
                List<String> values = newList[i].split(',');
                
                // Prepare the Account fields for insert
                Account accObj = new Account();
                accObj.Name = values[0];
                accObj.accountnumber = values[1];
                accObj.Type = values[2];
                accObj.AccountSource = values[3];
                accObj.Industry = values[4];
                
                acclist.add(accObj);
            }
            
            // Insert the account collection
            insert acclist;
        }
        catch (Exception e)
        {
            
        }
    }
}
Please help !! 
Thanks 
Rey....
 
Hello I'm trying to write a test class for Rest API post Method which i wrote, need help in writing test method. This gives me System.DmlException: Update failed. First exception on row 0; first error: MISSING_ARGUMENT, Id not specified in an update call:". Please help
trigger RadarFirst on Patient_Satisfaction__c (after update) {
for (Patient_Satisfaction__c cc : Trigger.new){
if(cc.Patient_Relation__c!= Trigger.oldMap.get(cc.id).Patient_Relation__c && cc.Patient_Relation__c != null) {
      if(cc.Patient_Relation__c.contains('Referred to Privacy Office')){
      RadarUpdate.postcallout(cc.id);
      }
  }
}
}
 
public class RadarUpdate {
    @future (callout=true)
	public static void postcallout(string Id) { 
	Patient_Satisfaction__c c = [select id, Name, Reporter_Phone__c,Reporter_First_Name__c,Reporter_Last_Name__c, Reporter_Email__c,
    Description_of_Feedback__c from Patient_Satisfaction__c where Patient_Relation__c ='Referred to Privacy Office' order by lastmodifiedDate desc limit 1];
    JSONGenerator gen = JSON.createGenerator(true);
	gen.writeStartObject();
	gen.writeObjectField('name', c.Name);
	gen.writeObjectField('incident_group_id', 7387);
    gen.writeObjectField('description',c.Description_of_Feedback__c);
	gen.writeFieldName('submitted_by');
	gen.writeStartObject();
	gen.writeStringField('given_name',c.Reporter_First_Name__c);
	gen.writeStringField('surname', c.Reporter_Last_Name__c);
	gen.writeStringField('phone',c.Reporter_Phone__c);
    gen.writeStringField('email',c.Reporter_Email__c);
	gen.writeEndObject();
	String jsonS = gen.getAsString(); 
	System.debug('jsonMaterials'+jsonS);
    Http http = new Http();
	HttpRequest request = new HttpRequest();
	request.setEndpoint('https://api.radarfirst.com/incidents');
	request.setMethod('POST');
	request.setHeader('Content-Type','application/json;charset=UTF-8');
	request.setHeader('User-agent', 'Salesforce-integration-client');
	request.setHeader('Authorization','Bearer 123');
    request.setBody(jsonS);
	// Set the body as a JSON object
	HttpResponse response = http.send(request);
	if (response.getStatusCode() != 201) {
    System.debug('The status code returned was not expected: ' +
        response.getStatusCode() + ' ' + response.getStatus());
	} else {
    System.debug(response.getBody());
	}
    }
}
@isTest
public class RadarUpdateTest{

    static testMethod void  postcalloutTest(){
        Account ac = new Account();
        ac.Name= 'Test';
        insert ac;
        
        Contact con= new Contact();
        con.AccountId= ac.Id;
        con.FirstName ='First Name';
        con.LastName = 'Test Contact';
        con.Phone= '7896541233';
        con.Email= 'Test@123.com';
        con.RUSH_Email__c= 'Test@123.com';
        insert con;
         		
        Patient_Satisfaction__c Pr = new Patient_Satisfaction__c();
        Pr.Primary_Campus__c = 'a1pP0000001lfaKIAQ';
        Pr.Primary_Facility__c= 'a1pP00000022FLRIA2';
        Pr.Primary_Location__c= 'a1pP00000022FLcIAM';
        Pr.Reporter__c=con.Id;
        Pr.Reporter_Phone__c=con.Id;
        Pr.Reporter_Email__c= 'Test@123.com';
        Pr.Description_of_Feedback__c= 'Testing Privacy office';
        Pr.Patient_Relation__c = 'Referred to Privacy Office';
        
     update Pr;
  	 RadarUpdate reqst=new RadarUpdate();
   	 String JsonMsg=JSON.serialize(reqst);
     Test.startTest();

    RestRequest req = new RestRequest(); 
    RestResponse res = new RestResponse();

    req.requestURI = '/services/apexrest/DemoUrl';  //Request URL
    req.httpMethod = 'POST';//HTTP Request Type
    req.requestBody = Blob.valueof(JsonMsg);
    RestContext.request = req;
    RestContext.response= res;
    RadarUpdate.postcallout(Pr.Id);
  
    update Pr;
    Test.stopTest();

   }
}

 
As part of the Lead conversion process I have disabled the ability to create an Opportunity and replaced the Opportunity creation via a Process builder flow.  However, I am experiencing an issue where a Task with an empty subject field is automatically created. Any thoughts/ideas how I can prevent the Task creation?

Thanks!
Hello SF community,

I've created a visualforce page that I would like to display as a homepage component.  I've also created two custom fields on the user object that I would like that to be able to update based on the current user.  I'm using the "User" standard controller, here is a bit of my code for the input fields.  Do I need a custom controller or am I missing something simple?  I'm fairly new to Visualforce, so I'm still learning.  Thank you for any assistance!

<apex:page standardController="User" doctype="html-5.0">
                <apex:inputField value="{!User.Time_off_start_date__c }"
                    label="" style="width:125px" showDatePicker="false" type="date">
                </apex:inputField>
                <apex:inputField value="{! User.Time_off_end_date__c }"
                    label="" style="width:125px" showDatePicker="false" type="date">
                </apex:inputField>
                <apex:commandButton action="{! save }" value="Submit"/>