• Egor Gerasimenko 9
  • NEWBIE
  • 75 Points
  • Member since 2019

  • Chatter
    Feed
  • 3
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 1
    Questions
  • 15
    Replies

I'm sure this is simple for most but I can't seem to figure out how to write a test class for a very simple custom class.  This will truly show how much I don't know how to code so I'm hoping someone will help me.

Here's my controller:

public class AccountTeamMemberController {
    
    public List<AccountTeamMember> atmList {get; set;}
    public AccountTeamMemberController(ApexPages.StandardController controller) {
        Account acc = (Account) controller.getRecord();
        
        atmList = [SELECT Id, AccountAccessLevel, AccountId, Account.Name, TeamMemberRole,UserId, User.Name FROM AccountTeamMember where AccountId =: acc.Id];
    }

}
Here's my test class that has the compile error:
@isTest
public class AccountTeamMemberControllerTest {

    @isTest
    static void testATMController() {
   
    List<AccountTeamMember> teamList=new List<AccountTeamMember>();
   
    User uUser1 = [Select Id from user where user.name = 'Jane Doe' Limit 1];
    User uUser2 = [Select Id from user where user.name = 'John Doe' Limit 1];
        
    RecordType accRT = [select id,Name from RecordType where SobjectType='Account' and Name='Customer' Limit 1];
   
    // Create the Acount
    Account aAccount = new Account();
    aAccount.Name='Test123';
    aAccount.Owner=uUser1;
    aAccount.RecordTypeID=accRT.id;
    aAccount.Account_Subtype__c='Subscription';
    aAccount.Industry='Construction';
    aAccount.Marketing_Vertical__c='Construction';
    aAccount.Website='http://www';
    aAccount.LMS_Current__c='EH&S Platform';
    aAccount.Active__c='Yes';
    aAccount.BillingCity='New York City';
    aAccount.BillingState='New York';
    
    insert aAccount;
       
    //Create the AccountTeam
    AccountTeamMember ATM1 = new AccountTeamMember();
    ATM1.AccountId = aAccount.ID;
    ATM1.TeamMemberRole = 'Owner';
    ATM1.UserId = uUser1.ID;
        
    teamList.add(ATM1);
    
    AccountTeamMember ATM2 = new AccountTeamMember();
    ATM2.AccountId = aAccount.ID;
    ATM2.TeamMemberRole = 'Co-Owner';
    ATM2.UserId = uUser2.ID;
        
    teamList.add(ATM2);
    
    if(teamList != null) { insert teamList; }
       
    Test.StartTest();
    
    PageReference pageRef = Page.Account_Team; //VF page
    Test.setCurrentPage(pageRef);
       
    AccountTeamMemberController tp = new AccountTeamMemberController();
    tp.RefreshPage();
    
    Test.StopTest();

    }
}

 
Hi!
I would like to know how to deserialize a JSON response on a list (to use it later on a for).
Im trying to deserialize the response, but the result of the deserialize is always null.

The response I receive contains a list of ServiceNow incidents, on the following format:
{"result":[{"short_description":"text","sys_id":"004fbc4cdb062300d6e781cc0b961989","contact_type":"email","incident_state":"2","impact":"4","description":"text"},{"short_description":"text","sys_id":"0188096ddb45a340d6e781cc0b961971","contact_type":"email","incident_state":"2","impact":"4","description":"text"},{"short_description":"text","sys_id":"02786099db66df40d6e781cc0b96197a","contact_type":"email","incident_state":"2","impact":"4","description":"text"}]}

At the moment my code looks like this:

ServiceNowBatch
//Authentication + request done (req and res)
// (...)
List<Case> casesToUpdate = new List<Case>;
String response = res.getBody();

//Having problems here
CaseWrapper caseWrapperDes = (CaseWrapper)JSON.deserialize(response, CaseWrapper.class);
System.debug('caseWrapper content: '+caseWrapperDes);

// (...)
for (CaseWrapper SNcase : caseWrapperDes) {
	if (response.length() > 0 && response.substring(0, 5) != 'Error') {
		Case c = new Case();
		c.description = SNcase.description;
		c.origin = SNcase.contact_type;
		
		casesToUpdate.add(c);
	}
}
return casesToUpdate;
(...)

CaseWrapper
CaseWrapper
public class CaseWrapper {

    public List<resultSN> results {get; set;}

    public class resultSN {
        public String short_description {get; set;}
        public String sys_id {get; set;}
        public String contact_type {get; set;}
        public String incident_state {get; set;}
        public String impact {get; set;}
        public String description {get; set;}
    }
}

CaseWrapperList
CaseWrapperList
public class CaseWrapperList {
    public List<CaseWrapper> results;
}

I don't know what I'm missing.
Would like to create a class to POST some data on an endpoint provided by an outside vendor.  Am modeling it on the "Mighty Moose" Trailhead example (https://trailhead.salesforce.com/en/content/learn/modules/apex_integration_services/apex_integration_rest_callouts) and the only difference seems to be the endpoint, the existence of an "api_key" (which the vendor says should be part of the url), and am passing more than one field.  Looks simple, but I have never done this type of thing before.  

Am testing in the "Open Execute Anonymous Window" of the developer console.  The trailhead example works fine but I am always getting a 400 Bad Request error for the real call out.  I do have a Remote Site setting.

Anything in the code below you can see (some data changed for security reasons)?
Any code you think might work better?
Any questions or details I should ask the vendor?
The vendor says I should be getting an explanatory message, but in the debug log I only see '400 Bad Request' and some other seemingly unrelated stuff.
 
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://my.domain.com/icon/send_eligible_offers?api_key=abcd-1234');
request.setMethod('POST');
request.setHeader('Content-Type', 'application/json;charset=UTF-8');

// Set the body as a JSON object
request.setBody('{"product_sku":"NTL07007", "serial_number":"1234343434", "user_email":"user.name@gmail.com", "sales_person_email":"agent@mail.com"}');

HttpResponse response = http.send(request);

// Parse the JSON response
if (response.getStatusCode() != 201) {
    System.debug('The status code returned was not expected: ' +
        response.getStatusCode() + ' ' + response.getStatus());
} else {
    System.debug(response.getBody());
}

 

Hello. While reading the docs today at https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_email_outbound_messaging.htm I noticed that the latest version (v45.0) for the Messaging.sendEmail() method states

"Sends the list of up to 10 emails"

Previous versions (v44.0 and earlier) do not state any such limitation. Is this an intended documentation change? Is this method actually limited to accepting batches of just 10 emails in v45.0? What happens if you try to send more than 10?

 

I have a trigger on Account that will update all related Contacts when updated.  I'm receiving the following error:  maximum trigger depth exceeded Account trigger event AfterUpdate Contact trigger event AfterUpdate  Any guidance would be appreciated.  Here is my trigger:
trigger UpdateRelatedContacts on Account (after update){
   List<Contact> contactList = new List<Contact>();
   List<Contact> contactList1 = new List<Contact>();
for(Account acc: [SELECT Id,RecordTypeID,(SELECT Id,RecordTypeID FROM Contacts) FROM Account WHERE Id in: Trigger.new]){
   If(acc.Contacts.size()>0 && (acc.RecordTypeID =='012E0000000PR3u' || acc.RecordTypeID =='012440000002T4h')){
     contactList.addALL(acc.Contacts);
    }
}
for(contact c:contactList){
    If(c.RecordTypeID !='012440000002T6J'){
       c.checkbox__c=true;
       contactList1.add(c);
}

update contactList1;
I am trying to create new testcase record for some case recordtype which is matching particular condition.i configured everything whch is need in the code like recordtype name status ,recordtype id ispriavte in   in my custom setting , now i m trying tocreate a record using trigger .but while creating a record i am geting "Apex trigger NewtestCaseRecord caused an unexpected exception, contact your administrator: NewtestCaseRecord: execution of AfterInsert caused by: System.NullPointerException:  NewCaseRecord: execution of AfterInsert caused by: System.NullPointerException: Attempt to de-reference a null object: ()" can someone please help me to find wht i am missing in my triger
trigger NewTestCaseRecord on Case (after insert,before update, after update) {
    
    if(!UserValidation.ValidationAccess()) {
                system.debug('Chatter_helper.getIstestCaseCreated()' + Chatter_helper.getIstestCaseCreated());
        if (!Chatter_helper.getIstestCaseCreated() ) {
            Map<string,string> caseRecordTypeMap = new Map<string,string>();
            set<string> caseRecordTypeSet = new set<string>();
            string rec_type;
            CaseRecordTypeClass RecordtypeCS = new CaseRecordTypeClass();
            RecordtypeCS.CaseFetchRecordtypes();
            Map<string, test_Settings__c> allRecordTypeMap = CaseRecordTypeClass.CaseRecordtypeMap;
            system.debug('allRecordTypeMap :NewServicenetrecord:' + allRecordTypeMap);
            for(test_Settings__c RT : allRecordTypeMap.values()){
                if(RT.SobjectType__c == 'case'){ 
                    if(RT.Name == 'Request1' || RT.Name == 'req2' || RT.Name == 'req3' || RT.Name == 'req4') {               
                    caseRecordTypeMap.put(RT.Name, RT.RecordtypeId__c.substring(0,15));
                        caseRecordTypeSet.add(RT.RecordtypeId__c.substring(0,15));
                } 
              }
            }
             system.debug('caseRecordTypeMap : ' + caseRecordTypeMap);
            system.debug('caseRecordTypeSet : ' + caseRecordTypeSet);
            
             List<test_Case__c > testCaseList = new List<test_Case__c >();
                        List<Case> caselist = new List<Case>();
            for(Case c: trigger.new){
             rec_type=c.RecordTypeId;
                if( caseRecordTypeSet.contains(rec_type.substring(0,15)) && C.Status == 'CaseRecordType__c.Status__c' && c.AD_Private__c == true)    {              
                   caselist.add(c);
                }
            }
            
           /* for(Case c: trigger.new){
                IF(Case.RecordtypeId = test_Settings__c.RecordtypeId__c){
                 rec_type=c.RecordTypeId;
                //if( caseRecordTypeSet.contains(rec_type.substring(0,15)))    {
                If(C.Status == 'test_Settings__c.Status__c' && c.AD_Private__c == false){
                     test_Case__c testCase = new test_Case__c(); 
                    testCase.Case = Case.ID;
                    testCase.SendEmail = true;
                    testCase.NotificationType = test_Settings__c.NotificationType;
                    testCaseLISt.add(testCase);

                   caselist.add(c);
                }
}
            }*/
        // 
            
                  system.debug('***caselist'+caselist.size());
                if(caselist.size()>0) {
                    for(case c : caselist){
                        rec_type=c.RecordTypeId;
                         test_Settings__c CRT = new test_Settings__c();
                        test_Case__c testCase = new test_Case__c();                       
                      if(CRT.Send_Email_to_OSJ__c == true){
                  rec_type=c.RecordTypeId;               
                testCase.Case__c = c.ID;
                testCase.Send_Email__c = true;
                testCase.Notification_Type__c = CRT.Notification_Type__c;
                testCaseLISt.add(testCase);
                    }
                    else{
                 rec_type=c.RecordTypeId;
                testCase.Case__c = C.ID;
                testCase.Send_Email__c = false;
                testCase.Notification_Type__c = CRT.Notification_Type__c;
                         testCaseLISt.add(testCase);
                    }                       
             
                }
            }

 
Hi all, 
I am trying to have my Candidate Lookup field on my UI to default to the current user
public LightningActivity(Contact candidateRecord){
        this();
        system.debug(candidateRecord);
        string userid = UserInfo.getUserID(); // getting current user info
        List<MTX_Matrix_Candidate__c> user= [SELECT Id, Name, Candidate__c FROM MTX_Matrix_Candidate__c 
        WHERE Id =: userid]; //storing the query into list for user

        if(candidateRecord.Candidate__c == null) //checking to see if  the lookup is populated
        {
            candidateRecord.Candidate__c = user.candidateName; //default to the current user
        }
    }
User-added imageRight now the Candidate Look up is blank, can someone help me with my code?
The salesforce org i am currently working on, instead of setting up many to many relationship between Account and Contact, they have multiple instances of the same contact, and each instance is related to unique account. 
E.g. In our org we have 200 Accounts for each of the 200 franchicess that do business with us. The person in charge (may be the area manager) for each of these stores is Sam Watkins. So in the org we have created Sam Watkins 200 times and related her to each of the Franchise. 
Sam Watkins  sam@email.com SW12  related to Account Acc001
Sam Watkins  sam@email.com SW12  related to Account Acc002
Where SW12 is the contacts unique identifier

In search if i type SW12, the list shows  all the 200 Accounst this person is related to.  

I have proposed to set up many to many relation between Account and Contacts so that we don't duplicate the same contact several hundered times, and also be able to build meaniful reports.  

My question is I want to fetch all instances of same Contacts that are associated with multiple accounts. 

This is how I can get one email at a time, but how can i get all contacts based on email addresses of all the Contacts who have multiple instances in the org.   
 
//retrieve related accounts for a contact
List<Contact> contactList = [Select id, name, AccountID
                       from contact where Email = 'sam@email.com'];

for(Contact con : contactList) {
    System.debug('Account id : ' + con.AccountID);
}

Thanks!
Hello, I am new to Apex (although been a salesforce admin for 5+ years) and hope someone can provide some guidance.

I have two use cases that have similarities:

1. When date field < today () and another field is > 0, update a third field.

2. When date field = today + one year and another field = specific value, create a record with specific values.

I can't do this with flow or process builder because the record will not necessary change to trigger a process builder update. 

I suspect I am doing an "after insert" and "after update". 

I suppose I will need to establish a set of records and a loop.to look for them.

I will use an "if" statement to specify my conditions. 

How do I tell the trigger when to run? It is possible to set them up on a schedule. For example, the first use case should run every night. The other use case should run daily. Do either of these requirements put unusual burden on SF limits?

Thanks for your help.
 
I'm trying to write a 'before update' apex trigger that uses values from the oldmap of an object, but have been having issues. I have been using a text field on the object to test the LastModified values, but found that the new value, the oldmap value, and the newmap value are identical. 
The code below shows what I'm talking about:
trigger Example on Contact (before update) {
    for (Object o: trigger.new) {
        try {
            o.Description = 'Current LastModifiedBy: ' + o.LastModifiedById + ' \noldMap: ' + Trigger.OldMap.get(o.Id).LastModifiedById + ' \nnewMap: ' + trigger.newMap.get(o.Id).LastModifiedById;
        } catch (Exception e) {}
    }
}
Again: o.LastModifiedById, Trigger.OldMap.get(o.Id).LastModifiedById, and Trigger.NewMap.get(o.Id).LastModifiedById, all return the same value.

Any help would be appreciated, thanks.
 

I'm sure this is simple for most but I can't seem to figure out how to write a test class for a very simple custom class.  This will truly show how much I don't know how to code so I'm hoping someone will help me.

Here's my controller:

public class AccountTeamMemberController {
    
    public List<AccountTeamMember> atmList {get; set;}
    public AccountTeamMemberController(ApexPages.StandardController controller) {
        Account acc = (Account) controller.getRecord();
        
        atmList = [SELECT Id, AccountAccessLevel, AccountId, Account.Name, TeamMemberRole,UserId, User.Name FROM AccountTeamMember where AccountId =: acc.Id];
    }

}
Here's my test class that has the compile error:
@isTest
public class AccountTeamMemberControllerTest {

    @isTest
    static void testATMController() {
   
    List<AccountTeamMember> teamList=new List<AccountTeamMember>();
   
    User uUser1 = [Select Id from user where user.name = 'Jane Doe' Limit 1];
    User uUser2 = [Select Id from user where user.name = 'John Doe' Limit 1];
        
    RecordType accRT = [select id,Name from RecordType where SobjectType='Account' and Name='Customer' Limit 1];
   
    // Create the Acount
    Account aAccount = new Account();
    aAccount.Name='Test123';
    aAccount.Owner=uUser1;
    aAccount.RecordTypeID=accRT.id;
    aAccount.Account_Subtype__c='Subscription';
    aAccount.Industry='Construction';
    aAccount.Marketing_Vertical__c='Construction';
    aAccount.Website='http://www';
    aAccount.LMS_Current__c='EH&S Platform';
    aAccount.Active__c='Yes';
    aAccount.BillingCity='New York City';
    aAccount.BillingState='New York';
    
    insert aAccount;
       
    //Create the AccountTeam
    AccountTeamMember ATM1 = new AccountTeamMember();
    ATM1.AccountId = aAccount.ID;
    ATM1.TeamMemberRole = 'Owner';
    ATM1.UserId = uUser1.ID;
        
    teamList.add(ATM1);
    
    AccountTeamMember ATM2 = new AccountTeamMember();
    ATM2.AccountId = aAccount.ID;
    ATM2.TeamMemberRole = 'Co-Owner';
    ATM2.UserId = uUser2.ID;
        
    teamList.add(ATM2);
    
    if(teamList != null) { insert teamList; }
       
    Test.StartTest();
    
    PageReference pageRef = Page.Account_Team; //VF page
    Test.setCurrentPage(pageRef);
       
    AccountTeamMemberController tp = new AccountTeamMemberController();
    tp.RefreshPage();
    
    Test.StopTest();

    }
}

 
I am trying to write an Apex trigger that copies the contents of the Comments field that is used for emails into the Notes field used for Tasks. 
Hi!
I would like to know how to deserialize a JSON response on a list (to use it later on a for).
Im trying to deserialize the response, but the result of the deserialize is always null.

The response I receive contains a list of ServiceNow incidents, on the following format:
{"result":[{"short_description":"text","sys_id":"004fbc4cdb062300d6e781cc0b961989","contact_type":"email","incident_state":"2","impact":"4","description":"text"},{"short_description":"text","sys_id":"0188096ddb45a340d6e781cc0b961971","contact_type":"email","incident_state":"2","impact":"4","description":"text"},{"short_description":"text","sys_id":"02786099db66df40d6e781cc0b96197a","contact_type":"email","incident_state":"2","impact":"4","description":"text"}]}

At the moment my code looks like this:

ServiceNowBatch
//Authentication + request done (req and res)
// (...)
List<Case> casesToUpdate = new List<Case>;
String response = res.getBody();

//Having problems here
CaseWrapper caseWrapperDes = (CaseWrapper)JSON.deserialize(response, CaseWrapper.class);
System.debug('caseWrapper content: '+caseWrapperDes);

// (...)
for (CaseWrapper SNcase : caseWrapperDes) {
	if (response.length() > 0 && response.substring(0, 5) != 'Error') {
		Case c = new Case();
		c.description = SNcase.description;
		c.origin = SNcase.contact_type;
		
		casesToUpdate.add(c);
	}
}
return casesToUpdate;
(...)

CaseWrapper
CaseWrapper
public class CaseWrapper {

    public List<resultSN> results {get; set;}

    public class resultSN {
        public String short_description {get; set;}
        public String sys_id {get; set;}
        public String contact_type {get; set;}
        public String incident_state {get; set;}
        public String impact {get; set;}
        public String description {get; set;}
    }
}

CaseWrapperList
CaseWrapperList
public class CaseWrapperList {
    public List<CaseWrapper> results;
}

I don't know what I'm missing.
Would like to create a class to POST some data on an endpoint provided by an outside vendor.  Am modeling it on the "Mighty Moose" Trailhead example (https://trailhead.salesforce.com/en/content/learn/modules/apex_integration_services/apex_integration_rest_callouts) and the only difference seems to be the endpoint, the existence of an "api_key" (which the vendor says should be part of the url), and am passing more than one field.  Looks simple, but I have never done this type of thing before.  

Am testing in the "Open Execute Anonymous Window" of the developer console.  The trailhead example works fine but I am always getting a 400 Bad Request error for the real call out.  I do have a Remote Site setting.

Anything in the code below you can see (some data changed for security reasons)?
Any code you think might work better?
Any questions or details I should ask the vendor?
The vendor says I should be getting an explanatory message, but in the debug log I only see '400 Bad Request' and some other seemingly unrelated stuff.
 
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://my.domain.com/icon/send_eligible_offers?api_key=abcd-1234');
request.setMethod('POST');
request.setHeader('Content-Type', 'application/json;charset=UTF-8');

// Set the body as a JSON object
request.setBody('{"product_sku":"NTL07007", "serial_number":"1234343434", "user_email":"user.name@gmail.com", "sales_person_email":"agent@mail.com"}');

HttpResponse response = http.send(request);

// Parse the JSON response
if (response.getStatusCode() != 201) {
    System.debug('The status code returned was not expected: ' +
        response.getStatusCode() + ' ' + response.getStatus());
} else {
    System.debug(response.getBody());
}