• TechingCrewMatt
  • NEWBIE
  • 320 Points
  • Member since 2020
  • Senior Salesforce Developer
  • TechingCrew LLC

  • Chatter
    Feed
  • 11
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 1
    Questions
  • 50
    Replies
Hi, I am trying to return on formula text type field, the outcome if 3 fields are empty to return text inactive if they are not empty and filled in return text active.

Can this be achieved? below is what I have so far :
IF(ISBLANK(Account_Name__c)&& ISBLANK(Name) && ISBLANK( CtM_Close_Date__c ) ,"Inactive","Active")
I have written this trigger which adds and opportunity to any new account insertions and account updates (where the account does not have an existing related opportunity).  My current test class provides 76% coverage.  Any advice would be appreciated!

APEX TRIGGER:
trigger AddRelatedRecord on Account(after insert, after update) {

    if (Trigger.isInsert) {
        for (Account a : Trigger.new) {
            Opportunity opp = new Opportunity();
            opp.Name = a.Name + ' Opportunity';
            opp.StageName = 'Prospecting';
            opp.CloseDate = System.today().addMonths(1);
            opp.AccountId = a.Id;
            insert opp;

        }
    }

    if (Trigger.isUpdate) {
        List<Opportunity> oppList = new List<Opportunity>();

        List<Account> accountsWithoutOppsAndGotUpdated = [
                SELECT Id, Name
                FROM Account
                WHERE Id NOT IN (SELECT AccountId FROM Opportunity) AND Id IN :Trigger.new];

 
        for (Account a : accountsWithoutOppsAndGotUpdated) {
            oppList.add(new Opportunity(Name = a.Name + ' Opportunity',
                    StageName = 'Prospecting',
                    CloseDate = System.today().addMonths(1),
                    AccountId = a.Id));
        }
        insert oppList;
    }
}

HERE IS MY CURRENT TEST CLASS:
@IsTest
private class AddRelatedRecordTest {

    @IsTest public static void addRelatedRecordTestonInsert() {

        Account testAcc = new Account(Name = 'My Account Test');
        insert testAcc;
        update testAcc;
        
        System.assert(true, 'Account Updated');

    }

}
Hello All, 

I am currently working on Apex Specialist Superbadge and Im not sure where Im going wrong. Here is the error message I am getting; 

Challenge Not yet complete... here's what's wrong:
There was an unexpected error in your org which is preventing this assessment check from completing: System.DmlException: Update failed. First exception on row 0 with id 5003h000002ZNFwAAO; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, MaintenanceRequest: execution of BeforeUpdate caused by: System.NullPointerException: Argument cannot be null. Class.MaintenanceRequestHelper.updateWorkOrders: line 19, column 1 Trigger.MaintenanceRequest: line 3, column 1: []

My Apex Helper Code is as follows; 

public class MaintenanceRequestHelper {
public static void updateWorkOrders() {
        // TODO: Complete the method to update workorders
      List<Case> caseList =[
            SELECT id, Equipment__c, status, type, subject, vehicle__c, Equipment__r.Maintenance_Cycle__c
            FROM Case    
            Where Status = 'Closed' AND Type IN ('Repair','Routine Maintenance')];
   
   
    
    List<Case> newCases = new List<Case>();
          for (Case c: caseList){ 
              Case nc = new Case();
              nc.Type = 'Routine Maintenance'; 
              nc.subject = 'New Routine Maintenance';
              nc.Vehicle__c = c.Vehicle__c; 
              nc.Equipment__c = c.Equipment__c; 
              nc.Date_Reported__c = date.today(); 
              nc.Date_Due__c = date.today().addDays(Integer.valueOf(c.Equipment__r.Maintenance_Cycle__c)); 
            
              newCases.add(nc); 
          }
        
    insert newCases;
           
    }        
    
}

Please help with an explanation as I'd really like to understand what I need to do to fix this. 
Thank you all!
 
While running the batch Apex I got this error "Apex heap size too large: 12239748"
I have created a field on the Contact object Active_Community_User__c, to be checked when we set up a Community user, and unchecked when we deactivate the Community user.

I need to update this field on existing Community users. Logically that would be best done through the Execute Anonymous window, but the code I have written isn't producing results.

The code appears to execute without error, but nothing changes.

Help?
 
List<User> userList = [ select user.Id, user.Contact.Active_Community_User__c from user where user.IsActive = True and (user.Profile.Name ='zConnect Community User' or user.Profile.Name = 'zConnect Community User Login')]; 

for(User us : userList) { 
    us.Contact.Active_Community_User__c = True; 
} 

update userList;

 
Hi there, I have written a Test Class for a Switch condition but When I'm executing Tests, I still have a 68% Coverage, nothing more. 

Here is my main class wich is tested until case : 33 
public with sharing class UpdateDepartmentField_CLASS {
    public static void UpdateDepartmentFieldCommune(List<Commune__c> communeList) {

        for (Integer i=0;  i < communeList.size(); i++) {
                switch on communeList[i].CodeDepartement__c {
                    when '01' {
                        communeList[i].Departement__c = '01 AIN';
                    }
                    when '02' {
                        communeList[i].Departement__c = '02 AISNE';
                    }
                    when '03' {
                        communeList[i].Departement__c = '03 ALLIER';
                    }
                    when '04' {
                        communeList[i].Departement__c = '04 ALPES-DE-HAUTE-PROVENCE';
                    }
                    when '05' {
                        communeList[i].Departement__c = '05 HAUTES-ALPES';
                    }
                    when '06' {
                        communeList[i].Departement__c = '06 ALPES-MARITIMES';
                    }
                    when '07' {
                        communeList[i].Departement__c = '07 ARDECHE';
                    }
                    when '08' {
                        communeList[i].Departement__c = '08 ARDENNES';
                    }
                    when '09' {
                        communeList[i].Departement__c = '09 ARIEGE';
                    }
                    when '10' {
                        communeList[i].Departement__c = '10 AUBE';
                    }
                    when '11' {
                        communeList[i].Departement__c = '11 AUDE';
                    }
                    when '12' {
                        communeList[i].Departement__c = '12 AVEYRON';
                    }
                    when '13' {
                        communeList[i].Departement__c = '13 BOUCHES-DU-RHONE';
                    }
                    when '14' {
                        communeList[i].Departement__c = '14 CALVADOS';
                    }
                    when '15' {
                        communeList[i].Departement__c = '15 CANTAL';
                    }
                    when '16' {
                        communeList[i].Departement__c = '16 CHARENTE';
                    }
                    when '17' {
                        communeList[i].Departement__c = '17 CHARENTE-MARITIME';
                    }
                    when '18' {
                        communeList[i].Departement__c = '18 CHER';
                    }
                    when '19' {
                        communeList[i].Departement__c = '19 CORREZE';
                    }
                    when '21' {
                        communeList[i].Departement__c = '21 COTE-D\'OR';
                    }
                    when '22' {
                        communeList[i].Departement__c = '22 COTES-D\'ARMOR';
                    }
                    when '23' {
                        communeList[i].Departement__c = '23 CREUSE';
                    }
                    when '24' {
                        communeList[i].Departement__c = '24 DORDOGNE';
                    }
                    when '25' {
                        communeList[i].Departement__c = '25 DOUBS';
                    }
                    when '26' {
                        communeList[i].Departement__c = '26 DROME';
                    }
                    when '27' {
                        communeList[i].Departement__c = '27 EURE';
                    }
                    when '28' {
                        communeList[i].Departement__c = '28 EURE-ET-LOIR';
                    }
                    when '29' {
                        communeList[i].Departement__c = '29 FINISTERE';
                    }
                    when '30' {
                        communeList[i].Departement__c = '30 GARD';
                    }
                    when '31' {
                        communeList[i].Departement__c = '31 HAUTE-GARONNE';
                    }
                    when '32' {
                        communeList[i].Departement__c = '32 GERS';
                    }
                    when '33' {
                        communeList[i].Departement__c = '33 GIRONDE';
                    }
                    when '34' {
                        communeList[i].Departement__c = '34 HERAULT';
                    }
                    when '35' {
                        communeList[i].Departement__c = '35 ILLE-ET-VILAINE';
                    }
                    when '36' {
                        communeList[i].Departement__c = '36 INDRE';
                    }
                    when '37' {
                        communeList[i].Departement__c = '37 INDRE-ET-LOIRE';
                    }
                    when '38' {
                        communeList[i].Departement__c = '38 ISERE';
                    }
                    when '39' {
                        communeList[i].Departement__c = '39 JURA';
                    }
                    when '40' {
                        communeList[i].Departement__c = '40 LANDES';
                    }
                    when '41' {
                        communeList[i].Departement__c = '41 LOIR-ET-CHER';
                    }
                    when '42' {
                        communeList[i].Departement__c = '42 LOIRE';
                    }
                    when '43' {
                        communeList[i].Departement__c = '43 HAUTE-LOIRE';
                    }
                    when '44' {
                        communeList[i].Departement__c = '44 LOIRE-ATLANTIQUE';
                    }
                    when '45' {
                        communeList[i].Departement__c = '45 LOIRET';
                    }
                    when '46' {
                        communeList[i].Departement__c = '46 LOT';
                    }
                    when '47' {
                        communeList[i].Departement__c = '47 LOT-ET-GARONNE';
                    }
                    when '48' {
                        communeList[i].Departement__c = '48 LOZERE';
                    }
                    when '49' {
                        communeList[i].Departement__c = '49 MAINE-ET-LOIRE';
                    }
                    when '50' {
                        communeList[i].Departement__c = '50 MANCHE';
                    }
                    when '51' {
                        communeList[i].Departement__c = '51 MARNE';
                    }
                    when '52' {
                        communeList[i].Departement__c = '52 HAUTE-MARNE';
                    }
                    when '53' {
                        communeList[i].Departement__c = '53 MAYENNE';
                    }
                    when '54' {
                        communeList[i].Departement__c = '54 MEURTHE-ET-MOSELLE';
                    }
                    when '55' {
                        communeList[i].Departement__c = '55 MEUSE';
                    }
                    when '56' {
                        communeList[i].Departement__c = '56 MORBIHAN';
                    }
                    when '57' {
                        communeList[i].Departement__c = '57 MOSELLE';
                    }
                    when '58' {
                        communeList[i].Departement__c = '58 NIEVRE';
                    }
                    when '59' {
                        communeList[i].Departement__c = '59 NORD';
                    }
                    when '60' {
                        communeList[i].Departement__c = '60 OISE';
                    }
                    when '61' {
                        communeList[i].Departement__c = '61 ORNE';
                    }
                    when '62' {
                        communeList[i].Departement__c = '62 PAS-DE-CALAIS';
                    }
                    when '63' {
                        communeList[i].Departement__c = '63 PUY-DE-DOME';
                    }
                    when '64' {
                        communeList[i].Departement__c = '64 PYRENEES-ATLANTIQUES';
                    }
                    when '65' {
                        communeList[i].Departement__c = '65 HAUTES-PYRENEES';
                    }
                    when '66' {
                        communeList[i].Departement__c = '66 PYRENEES-ORIENTALES';
                    }
                    when '67' {
                        communeList[i].Departement__c = '67 BAS-RHIN';
                    }
                    when '68' {
                        communeList[i].Departement__c = '68 HAUT-RHIN';
                    }
                        when '69' {
                            communeList[i].Departement__c = '69 RHONE';
                        }
                        when '70' {
                            communeList[i].Departement__c = '70 HAUTE-SAONE';
                        }
                        when '71' {
                            communeList[i].Departement__c = '71 SAONE-ET-LOIRE';
                        }
                        when '72' {
                            communeList[i].Departement__c = '72 SARTHE';
                        }
                        when '73' {
                            communeList[i].Departement__c = '73 SAVOIE';
                        }
                        when '74' {
                            communeList[i].Departement__c = '74 HAUTE-SAVOIE';
                        }
                        when '75' {
                            communeList[i].Departement__c = '75 PARIS';
                        }
                        when '76' {
                            communeList[i].Departement__c = '76 SEINE-MARITIME';
                        }
                        when '77' {
                            communeList[i].Departement__c = '77 SEINE-ET-MARNE';
                        }
                        when '78' {
                            communeList[i].Departement__c = '78 YVELINES';
                        }
                        when '79' {
                            communeList[i].Departement__c = '79 DEUX-SEVRES';
                        }
                        when '80' {
                            communeList[i].Departement__c = '80 SOMME';
                        }
                        when '81' {
                            communeList[i].Departement__c = '81 TARN';
                        }
                        when '82' {
                            communeList[i].Departement__c = '82 TARN-ET-GARONNE';
                        }
                        when '83' {
                            communeList[i].Departement__c = '83 VAR';
                        }
                        when '84' {
                            communeList[i].Departement__c = '84 VAUCLUSE';
                        }
                        when '85' {
                            communeList[i].Departement__c = '85 VENDEE';
                        }
                        when '86' {
                            communeList[i].Departement__c = '86 VIENNE';
                        }
                        when '87' {
                            communeList[i].Departement__c = '87 HAUTE-VIENNE';
                        }
                        when '88' {
                            communeList[i].Departement__c = '88 VOSGES';
                        }
                        when '89' {
                            communeList[i].Departement__c = '89 YONNE';
                        }
                        when '90' {
                            communeList[i].Departement__c = '90 TERRITOIRE DE BELFORT';
                        }
                        when '91' {
                            communeList[i].Departement__c = '91 ESSONNE';
                        }
                        when '92' {
                            communeList[i].Departement__c = '92 HAUTS-DE-SEINE';
                        }
                        when '93' {
                            communeList[i].Departement__c = '93 SEINE-SAINT-DENIS';
                        }
                        when '94' {
                            communeList[i].Departement__c = '94 VAL-DE-MARNE';
                        }
                        when '95' {
                            communeList[i].Departement__c = '95 VAL-D\'OISE';
                        }
                        when '2B', '2b' {
                            communeList[i].Departement__c = '2B Haute-Corse ';
                        }
                        when '2A', '2a' {
                            communeList[i].Departement__c = '2A Corse-du-Sud ';
                        }
                        when else {
                            communeList[i].Departement__c = null;
                        }
                    }
                }
            }
 }
I know it's a huge condition so maybe there are some limitations ?

Here is my test class
@isTest
public with sharing class UpdateDepartmentField_TEST {
    @isTest static void TestUpdateDepartmentField() {
        //First I create a commune that should be automatically updated with Department__c
        Commune__c newCommune = new Commune__c();
        newCommune.Name='Commune 1';
        newCommune.CodeInseeCommune__c='12265';
        newCommune.CodeDepartement__c='01';
        newCommune.CodeCanton__c='02';
        newCommune.CodeRegion__c='73';
        insert newCommune;

        //Then i'll update this commune with all dept
        for (Integer i=2; i < 96; i++) {
            if (i<10) {
                newCommune.CodeDepartement__c= '0'+String.valueOf(i);
                update newCommune;
            } else if (i>9 && i<96) {
                newCommune.CodeDepartement__c= String.valueOf(i);
                update newCommune;
            }
        }

        newCommune.CodeDepartement__c='2B';
        update newCommune;

        newCommune.CodeDepartement__c='2A';
        update newCommune;         
    }
}
I don't know what i'm missing here.
When I test manually everithing seems fine, so i think it's only related to the test class. 
Do you see anything that could help reach 100% for this test class ? 

 
The standard web to case logic to match to a contact is email; I'm not confident in the quality of the email addresses we'll get on our cases, and accounts are matched via the contact. We would like to use a custom field to associate a case with an account: NPI number. We can force that into the web to case HTML and we know it's a one-to-one match. I've never written a trigger and would like some guidance on the best way to appraoch this.

My APEX trigger was timing out, so I thought I would  to use a MAP, but I cannot get past the above error.

Anyone willing to take a look?

Map<Id,List<Opportunity>> accountOppMap = new Map<Id,List<Opportunity>>();
for(Opportunity opp : [Select id,accountId from opportunity Where Almac_Division__c='SI']){
    List<Opportunity> opplst = AccountOppMap.get(opp.accountId);
    if(opplst == null)
        opplst = new List<Opportunity>();
    opplst.add(opp);
    accountOppMap.add(opp.accountId,opplst); <- error line
}

We have two custom objects, Trade and Program Trade, that we are using in an apprenticeship development app.

Trade is a lookup table containing various codes, descriptions, and training details.
Program Trade is an instance of a trade within an apprenticeship program, and (in theory) sets some of its fields to default values using the corresponding fields in Trade. Those values may be modified by the end user after the fact, but by giving them default values based on the Trade, we hope to limit the number of mising and invalid values entered on the record.
Program Trade contains a lookup on the Name field in Trade to establish the reference between the two objects.
If I execute the following query in the Developr console:
SELECT Name,Sponsor__r.Name, Sponsored_Program__r.Name,Training_Type__c,Trades__r.Name, Trades__r.Training_Type__c
FROM Program_Trade__c
WHERE Sponsored_Program__r.Name != Null AND Sponsor__r.Name != Null
LIMIT 10

Name	Sponsor__r.Name	Sponsored_Program__r.Name	Training_Type__c	Trades__r.Name	Trades__r.Training_Type__c
Why?	Really Kool Gizmos	Really Kool Gizmos-Apprenticeship	Time Based	Computer Programmer	Time Based
Painter	Really Kool Gizmos	Really Kool Gizmos-Apprenticeship	Time Based	Painter (Professional and Kindred)	Time Based
Combination Welder	Really Kool Gizmos	Really Kool Gizmos-Apprenticeship	Competency Based	Welder, Combination	Competency Based
Reactor Fixer	Duke Harris	Chernobyl Avoidance		Powerhouse Mechanic	Time Based
The first three were set manually, which is why they have values in them. The fourth was the test case I used for this trigger:
trigger setTradeDefaults on Program_Trade__c(before insert, before update) {
    for (Program_Trade__c pt : Trigger.new){
		System.debug('Trigger setTradeDefaults initial value of pt.Training_Type__c:' + pt.Training_Type__c);
		System.debug('Trigger setTradeDefaults initial value of pt.Trades__r.Training_Type__c:' + pt.Trades__r.Training_Type__c);
        if (String.isBlank(pt.Training_Type__c)){
            pt.Training_Type__c = pt.Trades__r.Training_Type__c;
            System.debug('Trigger setTradeDefaults assigned pt.Training_Type__c the value :' + pt.Training_Type__c);
        }
    }
}
And the debug log shows these three entries when I saved the program trade with the Training Type field left empty:
12:47:20:033 USER_DEBUG [3]|DEBUG|Trigger setTradeDefaults initial value of pt.Training_Type__c:null
12:47:20:034 USER_DEBUG [4]|DEBUG|Trigger setTradeDefaults initial value of pt.Trades__r.Training_Type__c:null
12:47:20:034 USER_DEBUG [7]|DEBUG|Trigger setTradeDefaults assigned pt.Training_Type__c the value :null
This happened at both insert and update, and the debug trace tels me that (a) the trigger fired and (b) the if condition passed.  But what it doesn't tell me is why pt.Trades__r.Training_Type__c is empty.  My best guess (which I fear is the case) is that in order to have visibilty into the lookup record beyond the fields expressly translated on the Program Trade record, I either need to run a SOQL query within the body of the trigger (which seems excessive for the purpose) OR create formula field(s) on Program Trade to make those value(s) accessible directly on the Program Trade record (which doesn't seem like it would be any more efficient than the query solution) and use those to set the default value(s) of the actual data fields.

Neither solution is especially appealing, so I'm hoping that in my novice-ness there's just something I haven't learned yet that would be a better idea. In a perfect world, I'd do this translation client side, and display the default values in real time, but that doesn't appear to be an option -- at least in the Lightning UI. I've seen recommendaiotns for using Workflow rules for tasks like this, but there seems to be a divide on whether those are a good idea these days. Sounds like Workflow in general is being phased out, which doesn't bode well for future proofing in my app.


 
Can anyone helpme out in scheduling a batch apex which need torun at 12:10 AM Everyday.

My batch apex code:
global class BatchImpliedConsentLead implements Database.Batchable<sObject> {
    global integer recordsProcessed = 0;
    global Database.QueryLocator start(Database.BatchableContext bc){
        return Database.getQueryLocator('SELECT Id, Implied_Consent__c,Implied_Consent_Date__c,HasOptedOutOfEmail,CASL_Opt_In__c,CASL_Opt_In_Status__c, Implied_Consent_Expiry__c from Lead WHERE Implied_Consent__c != null AND Implied_Consent_Expiry__c != null');
    }
    global void execute(Database.BatchableContext bc, List<Lead> scope){
        for(lead l: scope){
            //date d = l.Implied_Consent_Expiry__c.date();
            if((l.Implied_Consent__c == true) && (l.Implied_Consent_Expiry__c.date() <= system.today()) ){
                l.Implied_Consent_Date__c = null;
                l.Implied_Consent__c = false;
                l.HasOptedOutOfEmail = true;
                l.CASL_Opt_In__c = false;
                l.CASL_Opt_In_Status__c = 'Removed';
                
            }
            update scope;
        }
    }
        global void finish(Database.BatchableContext bc){
            system.debug(recordsProcessed +'records Processed');
            AsyncApexJob job = [select Id, Status, NumberOfErrors, JobItemsProcessed, TotalJobItems,CreatedBy.Email from AsyncApexJob where Id =: bc.getJobId()];
    }

}

 
Hello, everyone. I created a node to flatten User Manager Ids to a dimension named "UserManagerIds". It is listed as an output field many times in the Register_PipelineTrending node, but I cannot use it in a dashboard or lens using the following SAQL:
 
q = load "pipeline_trending"
q = foreach q generate 'Opportunity.Owner.UserManagerIds';

Has anyone come across a similar situation?
How  to stop the page from refreshing continuously...?

apex page :

<apex:page controller="searchClass">
    <script>
    
    window.onload = function()
    {
        some();
        }
    
    </script>
    
    <apex:form >
        <apex:pageBlock>
            <apex:pageBlockSection >
               <apex:actionfunction action="{!searchContact}" name="some">            

            <apex:pageBlockTable value="{!Listcontacts}" var="con" id="abc">
                <apex:column value="{!con.Name}"/>
                
            </apex:pageBlockTable>
              </apex:actionfunction>

            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>

apex class :

 public class searchClass
{
   
    public List<Contact> result{get;set;}
    public List<Contact> Listcontacts {get;set;}
    public searchClass()
    {
        
           Listcontacts = new List<Contact>();
    }
               

    public void searchContact()
    {
      
        Listcontacts = [ SELECT Name from Contact];
            System.debug('aaaaaaaaaaaaaaaaaaaaa'+Listcontacts);

    }
    
     }





 
For some reason, my Contact object still shows existing contacts inside my unit tests even though I am not using seeAllData=true...
 
@isTest
public class TravelDetailGateway_Tests {
    @isTest
    public static void loadData_Tests() {
        Test.loadData(Account.sobjectType, 'test_data_accounts'); //file contains 10 rows.
        //contact in file is associated to account 9 in the file above.
        Test.loadData(Contact.sobjectType, 'test_data_contacts'); //file coontains 1 row.
        
        integer acctCount = [SELECT count() FROM Account];
        integer ctcCount = [SELECT count() FROM Contact];
        
        system.assertEquals(10, acctCount);
        system.assertEquals(1, ctcCount); //assertion fails and returns 11 records.
    }
}

 
Below are part of the Test Class Code which fails;
Method Name: deleteAttachments
Pass/Fail: Fail
Error Message: System.NullPointerException: Attempt to de-reference a null object
Stack Trace: Class.AttachmentUtilsTest.deleteAttachments: line 137, column 1

Class: AttachmentUtilsTest
Method: NamemodifyAttachments
Pass/Fail: Fail
Error Message: System.NullPointerException: Attempt to de-reference a null object
Stack Trace: Class.AttachmentUtilsTest.modifyAttachments: line 115, column 1

Please help, thanks.
/**
 * Test class for attachmentUtils and filesUtils classes
*/
@isTest
public class AttachmentUtilsTest{

    static integer NUMBER_OF_FILES = 5;
    
    //this is a test setup method - will be automatically executed before each test method
    @testSetup static void createAgriFiReportandAttachments() {
        
        
        
        //Set up AgriFi Application (record)
        AgriFI_Application__c App =new AgriFI_Application__c();
        //App.Name = 'new AgriFI Reference()';
        //App.LeadBusinessName = 'Weymouth';
        //App.LeadContactSurname = 'Ken';
        insert App;
        
        
        AgriFI_Report__c ast = new AgriFI_Report__c();
        ast.AgriFI_Application__c = App.id;
        
        insert ast;
        
        //create and insert the attachments
        list<attachment> atts = new list<attachment>();
        
        for(integer i=0;i<NUMBER_OF_FILES;i++){
            attachment att = new attachment();
            att.parentId = ast.id;
            att.name = 'a';
            att.body = Blob.valueOf('Attachment Body');
            atts.add(att);
        }
        
        //this should cause the trigger to fire and concatenate attachment names in the Attachment_Name__c field
        //names should be 300 characters long (200 x with spaces in between, plus trailing space)
        insert atts;
        
        //create and insert files
        list<ContentVersion> contentVersions = new list<ContentVersion>();
        
        for(integer i=0;i<NUMBER_OF_FILES;i++){
            String filesString = 'Binary string of the files';

            ContentVersion conVer = new ContentVersion();
            conVer.ContentLocation = 'S'; // S specify this document is in SF, use E for external files
            conVer.PathOnClient = 'file.txt'; // The files name, extension is very important here which will help the file in preview.
            
            conVer.Title = 'c'; // Display name of the files
            conVer.VersionData = EncodingUtil.base64Decode(filesString); // converting your binary string to Blog
            contentVersions.add(conVer);
        
        }
               
        insert contentVersions;
        
        list<ContentDocumentLink> contentDocLinks = new list<ContentDocumentLink>();
        
        for(ContentVersion conVer: [SELECT contentDocumentId from ContentVersion WHERE Title = 'c']){
            //Create ContentDocumentLink
            ContentDocumentLink cDe = new ContentDocumentLink();
            cDe.ContentDocumentId = conVer.contentDocumentId;
            cDe.LinkedEntityId = ast.Id; // you can use objectId,GroupId etc
            cDe.ShareType = 'I'; // Inferred permission, checkout description of ContentDocumentLink object for more details
            cDe.Visibility = 'AllUsers';
            contentDocLinks.add(cDe);
        }
               
        insert contentDocLinks;
        
    }
    
    //test to see if trigger is correctly modifying field on assignment when 200 attachments are added
    public static testmethod void addAttachments(){
    
        //assert that the attachment name field is correct
        string names = [SELECT Attachment_Names__c 
                        FROM AgriFI_Report__c][0].Attachment_Names__c;
                               
        //Each file name is 1 character long
        //And the 'attachment names' field contains each filename with a space in between
        //So length of Attachment Names should = number of files * 2 characters * 2 (attachments and content) - 1 space
        if(names!=null) system.assertEquals(NUMBER_OF_FILES * 2 * 2 - 1,names.length());
        
    }
    
    
    //test to see if trigger is correctly modifying field on assignment when one attachment name is changed
    public static testmethod void modifyAttachments(){
    
        //select an attachment and modify its name
        attachment att = [    SELECT id, name
                              FROM attachment
                              ][0];
        att.name = 'aaaa';
        
        contentVersion cv = [SELECT id, Title from ContentVersion][0];
        cv.Title = 'cccc';
        
        test.startTest();
        update att;
        update cv;
        test.stopTest();
        
        //test that names field has increased by 4
        //assert that the attachment name field is correct
        string names = [SELECT Attachment_Names__c 
                        FROM AgriFI_Report__c][0].Attachment_Names__c;
                        
        
        //Increases by 6 characters total
        system.assertEquals(NUMBER_OF_FILES * 2 * 2 - 1 + 6,names.length());
        
    }
    
    //test to see if trigger is correctly modifying field on assignment when one attachment name is deleted
    public static testmethod void deleteAttachments(){
    
        //select an attachment and delete it
        attachment att = [    SELECT id
                              FROM attachment
                              ][0];
        
        
        test.startTest();
        delete att;
        test.stopTest();
        
        //test that names field is now decreased by 2
        //assert that the attachment name field is correct
        string names = [SELECT Attachment_Names__c 
                        FROM AgriFI_Report__c][0].Attachment_Names__c;
                               
        system.assertEquals(NUMBER_OF_FILES * 2 * 2 - 1 - 2,names.length());
    }
    
}



 
Hi, I am trying to return on formula text type field, the outcome if 3 fields are empty to return text inactive if they are not empty and filled in return text active.

Can this be achieved? below is what I have so far :
IF(ISBLANK(Account_Name__c)&& ISBLANK(Name) && ISBLANK( CtM_Close_Date__c ) ,"Inactive","Active")
Hi! 
I'm struggling with creating a field validation rule that requires multiple fields to be not blank if anyone moves the lead from "Unqualified" to "MQL".  I've cobbled the below together from a similar Opportunity validation rule but it does not work:

AND (
ISPICKVAL(Status, "MQL"),
ISPICKVAL(PRIORVALUE(Status), "Unqualified"),
NOT(ISBLANK(State)) 
NOT(ISBLANK(Industry))
)

Can anyone show me what I'm doing wrong?
I've created a process builder flow that creates a child record when a certain stage is selected on the Opportunity record. I want to avoid having multiple child records created if one already exists. 

Here is a screenshot of the criteria I used to trigger the action:
Define Criteria Screenshot (https://www.screencast.com/t/Zisb0hjd0SI)

1. [Opportunity].StageName = "Financial Interview"

I believe I need to add another condition to check if a Financial_Interview__c record exists, do not execute this action. 

Thank you in advance. 
  • April 02, 2020
  • Like
  • 0
I have written this trigger which adds and opportunity to any new account insertions and account updates (where the account does not have an existing related opportunity).  My current test class provides 76% coverage.  Any advice would be appreciated!

APEX TRIGGER:
trigger AddRelatedRecord on Account(after insert, after update) {

    if (Trigger.isInsert) {
        for (Account a : Trigger.new) {
            Opportunity opp = new Opportunity();
            opp.Name = a.Name + ' Opportunity';
            opp.StageName = 'Prospecting';
            opp.CloseDate = System.today().addMonths(1);
            opp.AccountId = a.Id;
            insert opp;

        }
    }

    if (Trigger.isUpdate) {
        List<Opportunity> oppList = new List<Opportunity>();

        List<Account> accountsWithoutOppsAndGotUpdated = [
                SELECT Id, Name
                FROM Account
                WHERE Id NOT IN (SELECT AccountId FROM Opportunity) AND Id IN :Trigger.new];

 
        for (Account a : accountsWithoutOppsAndGotUpdated) {
            oppList.add(new Opportunity(Name = a.Name + ' Opportunity',
                    StageName = 'Prospecting',
                    CloseDate = System.today().addMonths(1),
                    AccountId = a.Id));
        }
        insert oppList;
    }
}

HERE IS MY CURRENT TEST CLASS:
@IsTest
private class AddRelatedRecordTest {

    @IsTest public static void addRelatedRecordTestonInsert() {

        Account testAcc = new Account(Name = 'My Account Test');
        insert testAcc;
        update testAcc;
        
        System.assert(true, 'Account Updated');

    }

}
I would want to write a batch class to consider some Account records which have a flag unchecked and then compare them with a duplicate Account records created with the same name which are checked to update other values. I am new to APEX please let me know how can I frame the code.
Global class myBatch implements Database.Batchable<sobject>{
    Global myBatch(){
        }
global Database.Querylocator start(Database.Bachablecontext context){

   return Database.getQuerylocator([Select ID, Name from Account where BATCH_PROCESS__c = FALSE]);
}

global void execute(Database.BatchableContext BC, List<Account> scope){
    //I would want to get those Account names which have a BATCH_PROCESS__c AS TRUE to compare 

list<Account> acc = ([Select Name from Account where BATCH_PROCESS__c = TRUE]);
    set<string> st = new set<string>();
    for(Account act: acc){
    st.add(act.name);
}
 try{
     
     for(Account active:scope){
         
         //I am struck here on how to compare the values from the string
     }
  }catch(Exception e){}
}
}

 
Iam getting this error :-


System.UnexpectedException: No more than one executeBatch can be called from within a test method. Please make sure the iterable returned from your start method matches the batch size, resulting in one executeBatch invocation.
Stack Trace: External entry point

@isTest(seealldata = true)
public class QuoteTrigger_PayTerms_GenerateDoc_Test{
             
         Static testMethod Void testMethod2(){
           
             Account acc = new Account();
             acc.Name = 'Test Account';
             acc.Website ='www.test.com';
             acc.Type='Banking';
             insert acc;
             
             Contact con = new contact();
             con.lastname='test contact';
             con.LeadSource = 'Inbound';
             con.Contact_Status__c='Open';
             con.accountid=acc.id;
             insert con;
             
             opportunity opp = new opportunity();
             opp.name ='Test Opp';
             opp.stagename='Closed Won';
             opp.Type= 'New Business';
             opp.CloseDate=system.today().addmonths(2);
             opp.Upsell_Potential__c ='No';
             opp.RenewalDate__c = system.today();
             opp.accountid=acc.id;
             opp.Contact_Name__c=con.id;
             insert opp;  
             
             OpportunityContactRole ocr = new OpportunityContactRole();
                ocr.ContactId = con.Id;
                ocr.OpportunityId = opp.Id;
                ocr.IsPrimary = TRUE;
                ocr.Role = 'Decision Maker';
                insert ocr;
             
             SBQQ__Quote__c oldquote2 = new SBQQ__Quote__c();
             oldquote2.SBQQ__Primary__c = true;
             oldquote2.SBQQ__Opportunity2__c = opp.id;
             oldquote2.SBQQ__StartDate__c = system.today();
             oldquote2.SBQQ__EndDate__c= system.today().addmonths(3);
             oldquote2.SBQQ__SubscriptionTerm__c=1;
             oldquote2.Status_Of_Approval__c='Pending';
             oldquote2.Document_Template__c= 'Auto Renew 3';
             oldquote2.SBQQ__PaymentTerms__c= 'monthly';
             oldquote2.SBQQ__BillingCountry__c ='United States';
             oldquote2.Long_Form__c=false;
             oldquote2.Logo__c = false;
             oldquote2.Attach_Terms_and_Conditions__c= 'No';
             insert oldquote2;
   //--------------------------------------------------------------------------Annual Starts here----------------
             oldquote2.Document_Template__c= 'Auto Renew';
             oldquote2.SBQQ__PaymentTerms__c= 'Annual';
             oldquote2.Logo__c = false;
             oldquote2.Attach_Terms_and_Conditions__c= 'Enterprise SaaS';
             update oldquote2;
             
             oldquote2.Document_Template__c= 'Auto Renew';
             oldquote2.SBQQ__PaymentTerms__c= 'Annual';
             oldquote2.Logo__c = true;
             oldquote2.Attach_Terms_and_Conditions__c= 'Enterprise SaaS';      
             update oldquote2;   
             
             oldquote2.Document_Template__c= 'Auto Renew';
             oldquote2.SBQQ__PaymentTerms__c= 'Monthly';
             oldquote2.Logo__c = false;
             oldquote2.Attach_Terms_and_Conditions__c= 'Enterprise SaaS';
             update oldquote2;
             
             oldquote2.Document_Template__c= 'Auto Renew';
             oldquote2.SBQQ__PaymentTerms__c= 'Monthly';
             oldquote2.Logo__c = true;
             oldquote2.Attach_Terms_and_Conditions__c= 'Enterprise SaaS';      
             update oldquote2;   
         

         }
             
               
             Static testMethod Void testMethod3(){

//----------------------------------------------Standard saas------------------------------------------------
           

             Account acc = new Account();
             acc.Name = 'Test Account';
             acc.Website ='www.test.com';
             acc.Type='Banking';
             insert acc;
             
             Contact con = new contact();
             con.lastname='test contact';
             con.LeadSource = 'Inbound';
             con.Contact_Status__c='Open';
             con.accountid=acc.id;
             insert con;
             
             opportunity opp = new opportunity();
             opp.name ='Test Opp';
             opp.stagename='Closed Won';
             opp.Type= 'New Business';
             opp.CloseDate=system.today().addmonths(2);
             opp.Upsell_Potential__c ='No';
             opp.RenewalDate__c = system.today();
             opp.accountid=acc.id;
             opp.Contact_Name__c=con.id;

             insert opp;  
             
              OpportunityContactRole ocr = new OpportunityContactRole();
              ocr.ContactId = con.Id;
              ocr.OpportunityId = opp.Id;
              ocr.IsPrimary = TRUE;
              ocr.Role = 'Decision Maker';
              insert ocr;
             
             SBQQ__Quote__c oldquote2 = new SBQQ__Quote__c();
             oldquote2.SBQQ__Primary__c = true;
             oldquote2.SBQQ__Opportunity2__c = opp.id;
             oldquote2.SBQQ__StartDate__c = system.today();
             oldquote2.SBQQ__EndDate__c= system.today().addmonths(3);
             oldquote2.SBQQ__SubscriptionTerm__c=1;
             oldquote2.Status_Of_Approval__c='Pending';
             oldquote2.Document_Template__c= 'Auto Renew';
             oldquote2.SBQQ__PaymentTerms__c= 'monthly';
             oldquote2.SBQQ__BillingCountry__c ='United States';
             oldquote2.Long_Form__c=false;
             oldquote2.Logo__c = false;
             oldquote2.Attach_Terms_and_Conditions__c= 'No';
             insert oldquote2;

             oldquote2.Document_Template__c= 'Auto Renew';
             oldquote2.SBQQ__PaymentTerms__c= 'Annual';
             oldquote2.Logo__c = false;
             oldquote2.Attach_Terms_and_Conditions__c= 'Standard SaaS';
             update oldquote2;
             
             oldquote2.Document_Template__c= 'Auto Renew';
             oldquote2.SBQQ__PaymentTerms__c= 'Annual';
             oldquote2.Logo__c = true;
             oldquote2.Attach_Terms_and_Conditions__c= 'Standard SaaS';      
             update oldquote2;   
             
             oldquote2.Document_Template__c= 'Auto Renew';
             oldquote2.SBQQ__PaymentTerms__c= 'Monthly';
             oldquote2.Logo__c = false;
             oldquote2.Attach_Terms_and_Conditions__c= 'Standard SaaS';
             update oldquote2;
             
             oldquote2.Document_Template__c= 'Auto Renew';
             oldquote2.SBQQ__PaymentTerms__c= 'Monthly';
             oldquote2.Logo__c = true;
             oldquote2.Attach_Terms_and_Conditions__c= 'Standard SaaS';      
             update oldquote2;   
         

         }
            
    
        
    }
  • March 31, 2020
  • Like
  • 0
Hello, 

I have logic in an email that works perfectly on one custom object, but when repurposing that logic into another custom object's email it does not work.

This is my snipit that does not work:

<apex:repeat var="cb" value="{!relatedTo.Advance__r.CoBrand__c}">
<apex:outputPanel rendered="cb == 'BrandA'">
The BrandA Company
</apex:outputPanel>
<apex:outputPanel rendered="cb != 'BrandA'">
The BrandB Company
</apex:outputPanel>
</apex:repeat>


I checked and {!relatedTo.Advance__r.CoBrand__c} does populate on its own within the email body, but the apex statement does not render any text. I had to go with the == and != approach because CoBrand__c can have many values but the only time the statement needs to be different is for BrandA.

Is there something wrong with the syntax? 

 
Hello all

i am trying to Design a Trigger where it should throw an error upon duplicate record creation, i know this can be achived with Duplicate management, but i have Custom Lookup field(User) which is not showing in the matching rules, Hence i am trying to write trigger, basically i have 3 Custom fields User(Assignedto__c ) which is 
Lookup(User) and other fields are 
Quater_Year__c which is picklist and Month (
Month__c) which is picklist field, 

Please Help with the trigger
trigger contactDuplicatePreventer on Contact(before insert, before update) 
{
	Set<String> setEmailID = new set<String>();
	Set<Id> setContID = new set<ID>();
    for (Contact Contact : System.Trigger.new) 
	{
        if ((Contact.Email != null) &&  (System.Trigger.isInsert ||  (Contact.Email != System.Trigger.oldMap.get(Contact.Id).Email))) 
		{
			setEmailID.add(Contact.Email);
			setContID.add(Contact.id);
		}
    }

	List<Contact> lstCOntact = [select id ,email from contact where email in :setEmailID and id not in :setContID ];
    Map<String, Contact> contactMap = new Map<String, Contact>();

	for(Contact cont : lstCOntact)
	{
		contactMap.put(cont.email, cont);
	}	

    for (Contact Contact : System.Trigger.new) 
	{
        if ((Contact.Email != null) &&  (System.Trigger.isInsert ||  (Contact.Email != System.Trigger.oldMap.get(Contact.Id).Email))) 
		{
			if(contactMap.containsKey(Contact.Email))
			{
				Contact.Email.addError('A Contact with this email address already exists.');
			}
		}	
	}	
}