• Abdul Khatri
  • PRO
  • 4729 Points
  • Member since 2015

  • Chatter
    Feed
  • 151
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 4
    Questions
  • 1279
    Replies
UseCase In Account Object:

Created a Trigger when the ParentAccount is selected in account object ,need to copy  the phone number and name and insert the record.
how can i add the Trigger in the Apex Class and Write Test Class...
 
trigger CopyAccountTriggerTest on Account (before insert) {
  
   
    if(checkRecursiveTest.runOnce()) {
        Set<Id> accountIds = new Set<Id>();
        for (Account acc : Trigger.new) {
            if (acc.ParentId != null){
                accountIds.add(acc.ParentId);
            }
            if(accountIds.size() > 0){  
                  List<Account> accounts = [select id,Name,Phone from account where id in :accountIds ];
                
                for (Account acc2 : Trigger.new) {
                    if (acc2.ParentId != null){
                        acc2.Name = 'Duplicate'+accounts[0].Name;
                        acc2.Phone= 'Duplicate'+accounts[0].Phone;
                    }
                }
            }
        }
 }

  
 
    
}



Apex Class:
=========
 
public class checkRecursiveTest {
    private static boolean run = true;
    public static boolean runOnce(){
     if(run){
     run=false;
     return true;
    }else{
        return run;
    }
    }
}

 
trigger CopyAccountTriggerTest on Account (before insert) {
  
   
    if(checkRecursiveTest.runOnce()) {
        Set<Id> accountIds = new Set<Id>();
        for (Account acc : Trigger.new) {
            if (acc.ParentId != null){
                accountIds.add(acc.ParentId);
            }
            if(accountIds.size() > 0){  
                  List<Account> accounts = [select id,Name,Phone from account where id in :accountIds ];
                
                for (Account acc2 : Trigger.new) {
                    if (acc2.ParentId != null){
                        acc2.Name = 'Duplicate'+accounts[0].Name;
                        acc2.Phone= 'Duplicate'+accounts[0].Phone;
                    }
                }
            }
        }
 }

  
 
    
}

ApexClass:
 
public class checkRecursiveTest {
    private static boolean run = true;
    public static boolean runOnce(){
     if(run){
     run=false;
     return true;
    }else{
        return run;
    }
    }
}

UseCase In Account Object:

Created a Trigger when the ParentAccount is selected in account object ,need to copy  the phone number and name and insert the record.
how can i add the Trigger in the Apex Class and Write Test Class...

Thanks 
Samantha
 
Hi - basic beginner apex question but struggling. 

The list TR2 will have duplicate values for Supplier__c. I want to end up with map with count of records for each Supplier__c.

What needs to go in the for loop to get this ? Thanks 
 
List<Trading_Relationship__c> Tr2 = [SELECT Supplier__c FROM Trading_Relationship__c WHERE Supplier__c IN :AccIds ORDER By Supplier__c ASC];

Map<ID, Integer> Map1 = new Map<ID, Integer>();
        
 for (Trading_Relationship__c eachTr : Tr2){   
            
            
        }
I can't figure out why the insert function isn't working. Can anyone help me? Thank you so much.

CONTROLLER:

public class ApartmentMapLister {

    public Map_Lead__c MapLead {get;set;}
    public Map_Point__c MapPoint {get;set;}
    public Map<Integer, Map_Point__c> ApartmentMap {get;set;}
    Public List<Wrapper> Wrapperlist {get;set;}

    public ApartmentMapLister() {
        MapLead = [SELECT ID, NAME, First_Name__c, Last_Name__c FROM Map_Lead__c WHERE ID=:ApexPages.currentPage().getParameters().get('id')];
    }    

    public Map<Integer, Map_Point__c> getonebedadmin() {

       Wrapperlist = new List<Wrapper>();
       
       ApartmentMap = new Map<Integer, Map_Point__c>();
       List<Map_Point__c> ApartmentList = [SELECT Id, Name, IsSelected__c FROM Map_Point__c Order By Name];

        for(Map_Point__c mp: ApartmentMap.values()) {
            Wrapper wrap = new Wrapper();
            wrap.mappoint = mp;
            Wrapperlist.add(wrap);
            }
                    
       for(Integer index = 0 ; index < ApartmentList.size() ; index++) {
           ApartmentMap.put(index, ApartmentList[index]);
       }
       return ApartmentMap;
    }

    public class Wrapper{
    
        public boolean isSelected {get;set;}
        public Map_Point__c mappoint {get;set;}
               
    }
    
    public void InsertApartment(){
        
        for(Wrapper wr : Wrapperlist){
        
            if(wr.mappoint.isSelected__c == true){
                
        Map_List__c ml = new Map_List__c();
            ml.Map_Lead__c=ApexPages.currentPage().getParameters().get('id');
            ml.Map_Point__c=wr.mappoint.ID;
            ml.Unique__c=(MapLead.NAME + wr.mappoint.AIMid__c);
            insert ml;
            }
        }
    }
    

      public PageReference SaveRecords(){
    
        List<Map_Point__c> records = new List<Map_Point__c>();
        for(Map_Point__c df : ApartmentMap.values()) {
            records.add(df);
        }
        // Bulk update with one DML call
        update records;
        return null;
      }
}


VISUALFORCE PAGE:
<apex:page sidebar="false" showHeader="false" cache="true" id="page" docType="HTML" readOnly="false" controller="ApartmentMapLister">
<apex:form >
    {!MapLead.First_Name__c} {!MapLead.Last_Name__c}
    
    <apex:pageBlock >
       <apex:pageBlockButtons location="top">
           <apex:commandButton value="Save" action="{!InsertApartment}"/>
       </apex:pageBlockButtons>
       <apex:pageBlockTable value="{!onebedadmin}" var="Map_Point__c">
            <apex:column >
                <apex:inputField value="{!onebedadmin[Map_Point__c].IsSelected__c}"/>
            </apex:column>
            <apex:column >
                <apex:inputField value="{!onebedadmin[Map_Point__c].Name}"/>
            </apex:column>
        </apex:pageBlockTable>
    </apex:pageBlock>
</apex:form>
</apex:page>
I wrote this. But its not wokrking if one of the fields is blank(but working if both are blank). what changes should i make ?
IF(
AND(NOT(ISBLANK( abc__c )) , NOT(ISBLANK( xyz__c ))) ,


IMAGE("/servlet/servlet.ImageServer?id=0150R000001JUkT&oid="+$Organization.Id, "icon" ,24, 128),
""
)

 
I have a Visualforce Page, with some input text fields. (There is NO standard or custom object associated with this Page). There is a button 'Generate PDF'. On click of this button, PDF needs to be generated having all the input text values.
How do we send the input text values to the PDF? (PDF is getting generated having only labels, no values) Please let me know!
  • October 25, 2021
  • Like
  • 0
Hope this is the right area to post this.  I am logged into SalesForce Lightning and can move around normally with our data. When I open up a new tab and access Workbench, the objects I run a query against are not ours.  For example, our Account object has 26 records in it currently.  But in Workbench, a count against the Account object indicates there are over 200,000 records.  Also the custom fields are not listed. I havent logged in a little over a month but up until my last login, everything was fine.  Any help and/or ideas?
Hi folks,

I have a custom code for dependent Picklist lightning component which is inserted in the case ,like below,now my requirement is whenever user wants to close the case ,i need to display a message in my custom picklist lightning component as below

"Level 1, level 2 and level 3 field must be populated before saving."

Here is the case stages as "CLOSED" and custom picklist component screenshot

User-added image


Your help is highly apreciated

Regards,
Fiona
I try not divided by 0 

I have variable with the Yearky Results this is the code
IF((AND(ISBLANK(Q1_c__c),ISBLANK(Q2_c__c),ISBLANK(Q3_c__c),ISBLANK(Q4_c__c))), 0,

IF((Q1_c__c + Q2_c__c + Q3_c__c + Q4_c__c) = Goal_Number__c,Goal_Number__c,

(((Q1_c__c + Q2_c__c + Q3_c__c + Q4_c__c)/Goal_Number__c)/4)))

With 4 Quarents with results 
 
Variable = Q1_c__c
IF(OR(ISBLANK(Q1_Value__c),ISBLANK(Q1_Goal__c)),0,Q1_Value__c / Q1_Goal__c) 

By in this quarter variables in one year you can use one quarter only or two or 3 or used all. And add to this you go over of 5,000 caracters in each formula. How can i do this 
Using the following call and JSON data I have been trying to Create a new opportunity attached to an account. Headers/Call are correct as I've been able to create Leads/Accounts. Something with the JSON is wrong but i'm not sure what it is. 

/services/data/v53.0/sobjects/Opportunity

data={
'Name': "Test opportunity",
'Accountid': "XXXXXXXXXXXXX",
'closedate': "1/12/2021",
'stagename':"Needs Analysis",
'Probability': "10"
}
Hi folks,

while calling a service at test class at Line 58 saying
here is test class code 
// Set mock callout class 
        Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
        
        // Call method to test.
        // This causes a fake response to be sent
        // from the class that implements HttpCalloutMock. 
        HttpResponse res = HerokuBanSync.getBANInfoUpdate('990135742');
        
        // Verify response received contains fake values
        String contentType = res.getHeader('Content-Type');
        System.assert(contentType == 'application/json');
        String actualValue = res.getBody();
        String expectedValue = '{"GSMStackableSOC__c":"false"}';
        System.assertEquals(actualValue, expectedValue);
        System.assertEquals(200, res.getStatusCode());

User-added image
How to resolve the "Non static method cannot be referenced from a static context:" error

Thanks in advance
Fiona




 

I have a formula text field that looks up the Account_Owner_Role__c (text) from the Account record. 

I now need the formula to populate only if a text field on the Account contains "Hunter" 

This is what I've tried:

IF(
OR(
TEXT(Sales_Role__c)='Hunter - 1',
TEXT(Sales_Role__c)='Hunter - 2',
TEXT(Sales_Role__c)='Manager - Hunter 1')
),
Account_Owner_Role__c
))

 

Hello - Below is a soql query I'm using to retrieve leads and a For Loop to update the lead. I'm finding that the For Loop selects a record at random. Sometimes the For Loop updates the oldest lead and sometimes the newest lead. Is there any logic to the record returned by the For Loop if no index is specified? 
 
existingLead = [SELECT Id, street, LastName, PostalCode, 
           LastNameStreetAndZipCode__c, Core_Number_Text__c, Status, Home_Phone__c,
           CreatedDate, Core_Number__c, Policy_Core_Number__c, Lead_Type__c 
                                FROM LEAD 
                                WHERE  (
                                    Policy_Core_Number__c IN :coreNumberTextSet OR
                                    Core_Number__c IN :coreNumberTextSet
                                    OR ( LastNameStreetAndZipCode__c IN :lastNameStreetZipSet
                                        AND Core_Number__c NOT IN :coreNumberTextSet)
                                    OR (LastNameStreetAndZipCode__c IN :setOfPoBoxes
                                        AND Core_Number__c NOT IN :coreNumberTextSet))
                                AND Household__c != null
                                AND Duplicate__c != True
                                AND IsDeleted = False
                                ORDER BY CreatedDate ASC
                                LIMIT 20000];

 
if(existingLead.size() > 0){
                for(Lead leadsToAddToMap : existingLead) {
                    mapOfCoreNumbers.put(leadsToAddToMap.Core_Number__c, 
                              leadsToAddToMap.Core_Number__c);
                   
                    mapOfCreatedDate.put(leadsToAddToMap.LastNameStreetAndZipCode__c, 
                        leadsToAddToMap.CreatedDate);
                }
            }
I hope u understand my question. Please help as I am very very new to Lightning web component. Is there any way to insert both these using uiRecordApi ???? if yes plz explain how.

Hi All,

 

string templateId = '00XN0000002LbV8MAK';
string domainUrl = URL.getSalesforceBaseUrl().toExternalForm();
HttpRequest req = new HttpRequest();
req.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionID());
req.setHeader('Content-Type', 'application/json');
req.setEndpoint(domainUrl+'/services/data/v51.0/tooling/query/?q=select+id,SenderType,templateId+from+WorkflowAlert+where+templateId=\''+templateId+'\'');
req.setMethod('GET'); 
Http h = new Http();
HttpResponse res = h.send(req);
system.debug(res.getBody());
Map<String, Object> deserialized = (Map<String, Object>)JSON.deserializeUntyped(res.getBody());
Object data1 = deserialized.get('records');
System.debug(deserialized.get('records'));
System.debug(deserialized.get('size'));

 

res.getBody(); -> {"size":1,"totalSize":1,"done":true,"queryLocator":null,"entityTypeName":"WorkflowAlert","records":[{"attributes":{"type":"WorkflowAlert","url":"/services/data/v51.0/tooling/sobjects/WorkflowAlert/01WN00000005esGMAQ"},"Id":"01WN00000005esGMAQ","SenderType":"CurrentUser","TemplateId":"00XN0000002LbV8MAK"}]}

 

Im trying to get ,"SenderType":"CurrentUser"  value but values is not returning: 

System.debug(deserialized.get('records')); --> [{"TemplateId":"00XN0000002LbV8MAK","SenderType":"CurrentUser","Id":"01WN00000005esGMAQ","attributes":{"url":"/services/data/v51.0/tooling/sobjects/WorkflowAlert/01WN00000005esGMAQ","type":"WorkflowAlert"}}]

 

How to get SenderType Value?

 

Thanks in Advance,

Hi Everyone,

problem statement: 
I am passing a SOQL query through a textArea of my Visualforce page. I want my controller to split the query and get a list of the queried coloums:

For ex. : InputQuery : 'Select Id, Name, Rating from Account' or 
'Select Id,Name,Rating from Account'(without space in fields)

Output result : List<String>= ['id', 'Name','Rating'];

I tried with InputQuery.split(' ') method but unable to get desired result. Please help me with this.
Hi,
I have written following apex class and test class. I'm getting an error saying "List has no rows for assignment to SObject" and my test class is getting failed though my code coverage is 91%. I'd appreciate any assistance.



public  class MMAResultReportController

{
    public List<DOAS_AVS_RESPONSE_LEVEL_1__c> avsresults {get;set;}
    public Test_MMA2__c avsRequest {get;set;}
    public string strRequestID{get;set;}
    
    //public string searchRef{get;set;}
    public  MMAResultReportController(){
        system.debug('####Printing page reference');
        system.debug(System.currentPageReference().getParameters().get('RequestID'));
        strRequestID=System.currentPageReference().getParameters().get('RequestID');
        
        getavsRequest();
    }
    public void getavsRequest(){
        avsRequest= new Test_MMA2__c();
        //system.debug ('####strRequestID is: '+strRequestID);
        //system.debug('####Variable is: ' + strRequestID);
        avsRequest = [select MMA_Request_ID__c,MMA_RecordType__c,MMA_Suffix__c,MMA_DOB__c,MMA_Middle_Name__c,MMA_Flag__c,MMA_Sex__c,MMA_SSN__c,MMA_First_Name__c, MMA_Last_Name__c, MMA_Family_ID__c, MMAReportDate__c,MMA_BENE_SSN1__c,
from Test_MMA2__c where MMA_Request_ID__c =:strRequestID];//                                                                 
    }
    
           
    
}


Test Class-

@isTest(SeeAllData=true)
public class MMAResultReportController_Test {
    @istest static void test(){

        Test_MMA2__c tes= new Test_MMA2__c ();
        tes.name='Sample';
        tes.MMA_First_Name__c='John';
        tes.MMA_Last_Name__c='Smith';
        tes.MMAReportDate__c=date.today();
        tes.MMA_Middle_Name__c='De';
       
        insert tes;
        test.startTest();
     
       MMAResultReportController ce= new MMAResultReportController();
      
        ce.getavsRequest();
        test.stopTest();
    }

 
I have two custom objecrt 1. stock_register__c 2. stock_regirser_line__c
i have master detail relation field quantity__c with stock_register__c(parent object) and  stock_regirser_line__c (chield)

I need to write a before insert and before update trigger to restrict the  sum of quantiy__in stock_regirser_line__c can not be more that  allocated_quanity__c in the parent object(stock_register__c)

Please help!!
thanks in advance!!
I'm trying to write an SOQL query that will pull information from the Contact object and the Event Object.  When I tried to use Event as the child object, I received an error message that Event could not be the child, so I switched the query around to this:
SELECT Event.whoid, Event.StartDateTime, Event.Subject, (select contact.id, contact.firstname, contact.lastname, contact.MailingStreet, contact.MailingCity, contact.MailingState, contact.MailingPostalCode from Contact)
from Event
Where Event.whoid = '0034M000020OgliQAC'

Unfortunately, it still isn't working.  It tells me "Didn't understand relationship 'Contact' in FROM part of query call.".  What am I doing wrong?

In SQL, the query would look like this:
Select Event.Whoid, Event.StartDateTime, Event.Subject, Contact.firstname, contact.lastname, contact.MailingStreet, Contact.MailingCity, contact.MailingState, contact.MailingPostalCode
from Event
Join Contact on Event.Whoid = Contact.id
where event.whoid = '0034M000020OgliQAC'

Any assistance would be greatly appreciated.
Hi,

I am looking to see the best approach for Salesforce CI. I have gone through many forum and blogs but haven't been able to grasp them. I tried to setup CI for the entire org but facing a lot of challeges which I guess you guys quite aware of.

What I am looking to do incremental deployment based on the git diff, dynamically generate package.xml based on the metadata committed which I think would be manageable something like sfdc-git-package https://www.npmjs.com/package/sfdc-git-package. I am having a hard time implementing this.

Please someone help
Can someone help me to show how I can change the Sales Console Lightning Layout. Currently it is showing as shown in the screen shot below as 3 Column layout. I wanted to change the layout to show the highlight panel on top. I am finding no help from Salesforce help section or trailhead for this. Please bear in mind I am talking about Lightning Sales Console and not Classic. I did the Edit Page and takes me but doesn't allow me to change the layout. 

User-added image
Is there a way to hide "Save & New" Button from the Task page Layout?

User-added image

I looked at everywhere and couldn't find the solution. I do want to give them Create/Edit Permission so no option there to remove that.

Please help
Custom URL for the cast creating inline headers and side bar. I tried the following addition things

            urlConcat += '&inline=0';
            urlConcat += '&isdtp=lt';
            urlConcat += '&isdtp=nv';
            urlConcat += '&isdtp=vw';

the only one that work is '&isdtp=nv' but after saving the activity, the hyperlink in the related list doesn't work. I have attached a screen shot 

User-added image

Anyone can help?

 
Hi,

I am looking to see the best approach for Salesforce CI. I have gone through many forum and blogs but haven't been able to grasp them. I tried to setup CI for the entire org but facing a lot of challeges which I guess you guys quite aware of.

What I am looking to do incremental deployment based on the git diff, dynamically generate package.xml based on the metadata committed which I think would be manageable something like sfdc-git-package https://www.npmjs.com/package/sfdc-git-package. I am having a hard time implementing this.

Please someone help
When I execute this query
List<AggregateResult> query = [
    SELECT Max(Id) Id, AccountId, Max(CustomField__c) 
    FROM Asset WHERE Status = 'X' 
    AND (CustomField__c = 'Z' 
    OR CustomField__c = 'Y') 
    GROUP BY AccountId LIMIT 1000 
];

The first time, happen an error:
Internal Salesforce.com Error

But the second time, I executed this query, the result with success 

User-added image

Why does this happen?
I am working on building an apex code that checks incoming emails that have a null or blank value in the subject line and will set a placeholder value in the subject line that will be the new case subject line. 
What am I missing in this field and what is the potential duplicate trigger that is being used. 
Thanks User-added image
Hello!
I have an unmanaged package installed that I am pushing a change for.
Upon validation, I am receiving the following error in production (repeated for each test line):


System.QueryException: List has no rows for assignment to SObject
Stack Trace: Class.CaseStatusChangeTriggerHandlerTest.getUser: line 139, column 1 Class.CaseStatusChangeTriggerHandlerTest.testAccessible1: line 66, column 1

Below is the full code for the test class.
Does anyone know of a way I could rewrite the @istest lines so that they don't fail when they don't find a user? I put the line in bold below that the above error references.

@IsTest
public class CaseStatusChangeTriggerHandlerTest {

    @testSetup static void setupTestdata() {
        
        Case newCase = new Case();
        newCase.Subject = 'Unittest';
        newCase.Status = 'New';
        insert newCase; 
        
        Case testCase = [select Subject, Status from Case where Subject = 'Unittest']; 
        System.assertEquals(testCase.Subject, 'Unittest');
    }
        
    @IsTest static void testOnAfterInsert(){

        Case[] testCase = [select Subject, CaseNumber, Status, Owner.Name from Case where Subject = 'Unittest'];
        
        CaseStatusChangeTriggerHandler.OnAfterInsert(testCase);
        
        Case_Status_Change__c[] caseStatusChange = [select Name from Case_Status_Change__c where Case__r.Id =:testCase[0].Id];
        
        System.assertEquals(caseStatusChange[0].Name, testCase[0].CaseNumber + ' status: New');    
    }        
    @IsTest static void testOnAfterUpdate(){

        Map<Id, Case> oldObjectMap = new Map<Id, Case>();
          
        Case[] testCase = [select Subject, CaseNumber, Status, Owner.Name from Case where Subject = 'Unittest'];
        
        Case_Status_Change__c  statusChange = new  Case_Status_Change__c();
        statusChange.Name = testCase[0].CaseNumber + ' status: New';
        statusChange.Case__c = testCase[0].Id;
        statusChange.Status_Name__c = testCase[0].Status;
        statusChange.Set_Time__c = Datetime.now();
        insert statusChange;
        
        testCase[0].Status = 'Escalated';

        Case oldCase = new Case();
        oldCase.Subject ='Unittest';
        oldCase.Status = 'New';
        oldCase.Id=testCase[0].Id;
        oldObjectMap.put(testCase[0].Id, oldCase);
        
        CaseStatusChangeTriggerHandler.OnAfterUpdate(testCase, oldObjectMap);
        
        Case_Status_Change__c[] caseStatusChange = [select Name from Case_Status_Change__c where Case__r.Id=:testCase[0].Id and Change_Time__c = null];        
        System.assertEquals(caseStatusChange[0].Name, testCase[0].CaseNumber + ' from New to Escalated');    
    }     
    /**
     *Tests if the user does not have access to Case and Case_Status_Change__c objects
     */
    @IsTest static void testAccessible1(){
       
        User u = getUser('NotAccessible1');

        System.runAs(u) {
            try {
                testOnAfterInsert();
                System.assert(false, 'fail the test if no exception thrown ');
            }
            catch (QueryException e) {
                 System.assertEquals(e.getMessage(), 'Insufficient access to Case or User objects');         
            }   
        }  
    }    

    @IsTest static void testAccessible2(){
        
        User u = getUser('NotAccessible2');
        
        System.runAs(u) {
            try {
                testOnAfterUpdate();
                System.assert(false, 'fail the test if no exception thrown ');
            }
            catch (QueryException e) {
                 System.assertEquals(e.getMessage(), 'Insufficient access to Case Status Change or business hours objects');         
            }   
        }
    }    
    @IsTest static void testCreatable(){
        
        User u = getUser('NotCreatable');
        
        System.runAs(u) {
            try {
                testOnAfterInsert();
                System.assert(false, 'fail the test if no exception thrown ');
            }
            catch (DmlException e) {
                 System.assertEquals(e.getMessage(), 'Insufficient permissions to create Case Status Change');         
            }    
        }        
        System.runAs(u) {
            try {
                testOnAfterUpdate();
                System.assert(false, 'fail the test if no exception thrown ');
            }
            catch (DmlException e) {
                 System.assertEquals(e.getMessage(), 'Insufficient permissions to create Case Status Change');         
            }    
        }     
    }    
    @IsTest static void testUpdatable(){
        
        User u = getUser('NotUpdatable');
        
        System.runAs(u) {
            try {
                testOnAfterUpdate();
                System.assert(false, 'fail the test if no exception thrown ');
            }
            catch (DmlException e) {
                 System.assertEquals(e.getMessage(), 'Insufficient permissions to update Case Status Change');         
            }
            
        }      
    }    
    public static User getUser(String profileName) {
        
        Profile p = [SELECT Id FROM Profile WHERE Name=:profileName limit 1];
        
        String testemail = 'atest@test.demo';
        User pu = new User(profileId = p.Id, username = testemail, email = testemail, 
                           emailencodingkey = 'UTF-8', localesidkey = 'en_US', 
                           languagelocalekey = 'en_US', timezonesidkey = 'America/Los_Angeles', 
                           alias='cspu', lastname='lastname');        
        return pu;
       
    }  
}
Please help me write a test class for an apex trigger that sends an email when a contact is created.
 
trigger EmailContact on Contact (after insert) {
List<Messaging.SingleEmailMessage> emailList= new List<Messaging.SingleEmailMessage>();
EmailTemplate emailTemplate = [Select Id,Subject,Description,HtmlValue,DeveloperName,Body from EmailTemplate where name='Contract Signed Thank you'];
for(Contact conObj:Trigger.new){
if (conObj.Email != null) {
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setTargetObjectId(conObj.Id);
mail.setSenderDisplayName('System Administrator');
mail.setUseSignature(false);
mail.setBccSender(false);
mail.setSaveAsActivity(true);
mail.setTemplateID(emailTemplate.Id);
mail.toAddresses = new String[]{conObj.Email};
emailList.add(mail);
}
}
if(emailList.size()>0){
Messaging.SendEmailResult[] results = Messaging.sendEmail(emailList);
if (results[0].success)
{
System.debug('The email was sent successfully.');
} else {
System.debug('The email failed to send: '+ results[0].errors[0].message);
}
}
}


 
This is what i have so far. i get an error that lines 9&15 are missing ','
@isTest private class EmailContactTestClass { static testMethod void validateEmailContact() { Contact c = new Contact(LastName='Test',Email='test@test.org'); System.debug(c.LastName); insert c; System.assertEquals(0, Limits.getEmailInvocations(); c = [SELECT id FROM Contact WHERE LastName ='Test' limit 1]; System.assertEquals(1, Limits.getEmailInvocations(); } }

 
  • May 15, 2022
  • Like
  • 0
I managed to modify some existing Apex, which should have been the hard part, but I can't get it to fail properly if the result = Null.  The Apex is used in a Flow and it performs a sosl query on a long text are field.  Then it updates the Opportunity.  Can someone help me terminate the Apex if the result = Null?
 
global class SearchDrugNameSynonyms {
   @InvocableMethod
   public static void getID(List<String> recordID) {
   Opportunity ThisOpportunity=[select Compound_Name__c from Opportunity where ID=:recordId[0] limit 1];
   
   String fieldValue = ThisOpportunity.Compound_Name__c;
String fieldName = 'Drug_Name_Synonyms__c';
String query = 'FIND {"'+ fieldValue + '"}  RETURNING ' +
                  ' Drug_Name__c (id, ' + fieldName + ' ) LIMIT 1';
 List<List<sObject>> result = System.Search.query(query);
system.debug('Search result: ' + result[0]);//Get search result

List<Drug_Name__c> ThisDrugName=new list<Drug_Name__c>();
    if(!result.isEmpty()){
    ThisDrugName=result[0];
       ThisOpportunity.Compound_Name2__c = ThisDrugName[0].id;
   Update ThisOpportunity;
    }
    else {}
     
   }
}

 
UseCase In Account Object:

Created a Trigger when the ParentAccount is selected in account object ,need to copy  the phone number and name and insert the record.
how can i add the Trigger in the Apex Class and Write Test Class...
 
trigger CopyAccountTriggerTest on Account (before insert) {
  
   
    if(checkRecursiveTest.runOnce()) {
        Set<Id> accountIds = new Set<Id>();
        for (Account acc : Trigger.new) {
            if (acc.ParentId != null){
                accountIds.add(acc.ParentId);
            }
            if(accountIds.size() > 0){  
                  List<Account> accounts = [select id,Name,Phone from account where id in :accountIds ];
                
                for (Account acc2 : Trigger.new) {
                    if (acc2.ParentId != null){
                        acc2.Name = 'Duplicate'+accounts[0].Name;
                        acc2.Phone= 'Duplicate'+accounts[0].Phone;
                    }
                }
            }
        }
 }

  
 
    
}



Apex Class:
=========
 
public class checkRecursiveTest {
    private static boolean run = true;
    public static boolean runOnce(){
     if(run){
     run=false;
     return true;
    }else{
        return run;
    }
    }
}

 
trigger CopyAccountTriggerTest on Account (before insert) {
  
   
    if(checkRecursiveTest.runOnce()) {
        Set<Id> accountIds = new Set<Id>();
        for (Account acc : Trigger.new) {
            if (acc.ParentId != null){
                accountIds.add(acc.ParentId);
            }
            if(accountIds.size() > 0){  
                  List<Account> accounts = [select id,Name,Phone from account where id in :accountIds ];
                
                for (Account acc2 : Trigger.new) {
                    if (acc2.ParentId != null){
                        acc2.Name = 'Duplicate'+accounts[0].Name;
                        acc2.Phone= 'Duplicate'+accounts[0].Phone;
                    }
                }
            }
        }
 }

  
 
    
}

ApexClass:
 
public class checkRecursiveTest {
    private static boolean run = true;
    public static boolean runOnce(){
     if(run){
     run=false;
     return true;
    }else{
        return run;
    }
    }
}

UseCase In Account Object:

Created a Trigger when the ParentAccount is selected in account object ,need to copy  the phone number and name and insert the record.
how can i add the Trigger in the Apex Class and Write Test Class...

Thanks 
Samantha
 
Hi - basic beginner apex question but struggling. 

The list TR2 will have duplicate values for Supplier__c. I want to end up with map with count of records for each Supplier__c.

What needs to go in the for loop to get this ? Thanks 
 
List<Trading_Relationship__c> Tr2 = [SELECT Supplier__c FROM Trading_Relationship__c WHERE Supplier__c IN :AccIds ORDER By Supplier__c ASC];

Map<ID, Integer> Map1 = new Map<ID, Integer>();
        
 for (Trading_Relationship__c eachTr : Tr2){   
            
            
        }
In this Trigger Apex,we have two custom sobjects Train__c and Passanger__c. At in Train__c there are two fields Passanger_Old_Phone_Number__c and Passanger_New_Phone_Number__c. At in Passanger__c there are one field Phone_Number__c. If the Phone number in Phone_Number__c was changed by Passanger in Passanger__c then old phone number  can be store in Passanger_Old_Phone_Number__c and new phone number can be store in Passanger_New_Phone_Number__c.
There are Lookup Relationship between Passanger__c to Train__c

We want functionality in Trigger Apex
Thank you !
 
public class ProjectTriggerHandler {

    public static void updateProjectTypeOnAllRelatedRecords(Map<Id, Project__c> mapOfNewProject, Map<Id, Project__c> mapOfOldMap){
        
        if(mapOfNewProject != Null && mapOfOldMap != Null){
            Set<Id> proIds = new Set<Id>();
            
            for(Id newProID: mapOfNewProject.keySet()){
                Project__c newPro = mapOfNewProject.get(newProID);
                Project__c oldPro = mapOfOldMap.get(newProID);
                
                if(newPro.Type__c != oldPro.Type__c){
                    proIds.add(newProID);                    
                }
            }
            List<Timesheet_Entry__c> tsEntriesToUpdte = new List<Timesheet_Entry__c>();
            if(proIds.size()>0){
                List<Timesheet_Entry__c> tsEntries = [SELECT ID, Project_Type__c, Project__c FROM Timesheet_Entry__c 
                                                      WHERE Project__c IN:proIds WITH SECURITY_ENFORCED];
                for(Timesheet_Entry__c tsEntry:tsEntries){
                    tsEntry.Project_Type__c = mapOfNewProject.get(tsEntry.Project__c).Type__c;
                    tsEntriesToUpdte.add(tsEntry);
                }
            }
            if(tsEntriesToUpdte.size()>0){
            update tsEntriesToUpdte;
            }
        }
    }
}
I have a trigger that updates a custom variable. (after insert/update/delete). This works, but I want the trigger to fire and update the variable for all entries. But so that my records are not updated, inserted and deleted
Hi there,

I'm on a professional plan with sales cloud. We send Leads to salesforce via Zapier. Every Lead should get an email. 

According to this article https://help.salesforce.com/s/articleView?id=000334297&type=1 it's expected behaviour, but provides two solutions. However, both solutions seem to require a higher plan than the professional one.

What to do? Contacting support feels like a joke to me, I am fiddling around with them already for 2 weeks.
Hello everyone !!

I can run a query , which gets value from date picker, and returns me values in date range. It works fine. But, now I want to get the value of SObject name from dropdown list and run the same query. But, my select value of drowpdown is not coming in controller. Can you please help me? Stuck in many days.
Please run the code, you can understand. 

Controller:
public class ContactsByDateController {
public List<Account> cts {get;set;}
public Date fromDate {get;set;}
public Date toDate {get;set;}
String[] countries = new String[]{};    
string c {get;set;}
string objName {get;set;}

String query;
public ContactsByDateController() {
    
}
    /* dropdown list start 
     * */
       public List<SelectOption> getItems() {
        List<SelectOption> options = new List<SelectOption>();
        options.add(new SelectOption('Account','Account'));
        options.add(new SelectOption('Contacts','Contacts'));
        options.add(new SelectOption('Jobs__c','JObs'));
        options.add(new SelectOption('My_leads__c','My Leads'));
        options.add(new SelectOption('My_Customers__c','My Customers'));
        
        return options;
    }
    
     public String[] getCountries() {
        return countries;
    }

    
    
    public void setCountries(String[] countries) {
        this.countries = countries;
    }
    
    /* dropdown list ends 
     * */

    /* variable assigning for selected list from dropdown*/
    
public void datepick1() {
Datetime fromDT = Datetime.newInstance(fromDate.year(), fromDate.month(), fromDate.day());
Datetime toDT = Datetime.newInstance(toDate.year(), toDate.month(), toDate.day());
objName = c;
String formattedFromDate = fromDT.format('yyyy-MM-dd\'T\'hh:mm:ss\'Z\'');
String formattedToDate = toDT.format('yyyy-MM-dd\'T\'hh:mm:ss\'Z\'');

if ( objName  == null ) {
 query = 'SELECT Name  FROM Account';
}
else {
 query = 'SELECT Name   FROM ' +objName;
}

query += ' WHERE CreatedDate >= ' + formattedFromDate;
query += ' AND CreatedDate <= ' + formattedToDate;
System.debug(query);
cts = Database.query(query);
}
public void clearResults() {
cts.clear();
}
}

Vsf page :

<apex:page docType="html-5.0" controller="ContactsByDateController" >
<apex:form >
<apex:input value="{! fromDate }" type="date" />
<apex:input value="{! toDate }" type="date" />
<apex:commandButton value="Search Contacts" action="{!datepick1}"/>
<apex:commandButton value="Clear Contacts" action="{!clearResults}"/>
<apex:selectList value="{!countries}" multiselect="false" size="3">
            <apex:selectOptions value="{!items}"/>
</apex:selectList><p/>
<apex:pageBlock title="Results in Range">
<apex:pageBlockTable value="{!cts}" var="ct">
<apex:column value="{!ct.Name}"/>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:form>
</apex:page>
Wondering if anyone has tackled this.
An Apex Trigger that looks at an inbound email (before insert, before update), and if there is an Attachment, and the Attachment is of certain File Types (.zip, .mp4, etc.) it does not create/update the case AND an email is sent to the sender notifying them that File Type is not accepted and to plesse resend their email with accepted File Type (.jpg, .png, .pdf).