• Moonpie
  • NEWBIE
  • 110 Points
  • Member since 2020

  • Chatter
    Feed
  • 3
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 60
    Replies
Below is the code I have written and the test class code covergae is 90%. Can anyone make the changes in the code so that ot gets deployed in prod. Error says test class code covergae is 0. I have written the code to add list of leads to be displayed on account. 

Apex class

public  class PartnerLeadController {
    public Account acc{get;set;}
    public List<Lead> LeadList{get;set;}  
    Set<String> UserContactId = new Set<String>(); 
    public PartnerLeadController(ApexPages.StandardController stdController) {
        LeadList = new List<Lead>();
        this.acc = (Account)stdController.getRecord();
        list<contact> conlist=[Select Id From Contact WHERE AccountId =:acc.Id]; 
        for(User u: [Select Id, Name, ContactId FROM USER WHERE isactive=TRUE AND ContactId In:conlist]){
            UserContactId.add(u.Id);
        }
        LeadList = [select id,Name,CreatedDate,Company,OwnerId,Owner.Name,LeadSource,MAU__c,Estimated_Opportunity_Deal__c,recordType.Name,CRM_User__r.Name,CRM_User__r.Id,CRM_User__c, Status, Account__c,LastName, Account__r.id,Account__r.OwnerId
                    from Lead 
                    where    CRM_User__c !=null And Account__c=: acc.Id AND LeadSource='Partner' AND recordType.Name = 'Partner Lead Registration' ];
    }
}

Vf page

<apex:page standardController="Account" extensions="PartnerLeadController" lightningStylesheets="true" sidebar="false"  >

    <apex:form >
       

        <apex:pageBlock rendered="true" >
            <apex:outputPanel layout="block" styleClass="container">
            <apex:pageBlockTable value="{!LeadList}" var="ld" width="100" >
               
                          
            <apex:column >
                <apex:outputLink value="/{!ld.Owner}" target="_top">{!ld.Owner.Name}</apex:outputLink>
                <apex:facet name="header">Owner Name</apex:facet>
            </apex:column>/> 
                
                 <apex:column ><apex:outputField value="{!ld.Name}" />
                <apex:facet name="header">Lead Name</apex:facet>
            </apex:column>
            <apex:column ><apex:outputField value="{!ld.Status}" />
                <apex:facet name="header">Status</apex:facet>
            </apex:column> 
                <apex:column ><apex:outputField value="{!ld.Company}" />
                <apex:facet name="header">Company</apex:facet>
            </apex:column> 
                 <apex:column ><apex:outputField value="{!ld.MAU__c}" />
                <apex:facet name="header">MAU</apex:facet>
            </apex:column> 
                <apex:column ><apex:outputField value="{!ld.Estimated_Opportunity_Deal__c}" />
                <apex:facet name="header">Estimated Opportunity Deal</apex:facet>
            </apex:column> 
                
            <apex:column ><apex:outputField value="{!ld.CreatedDate}" />
                <apex:facet name="header">CreatedDate</apex:facet>
         
            </apex:column> 
            </apex:pageBlockTable>
                </apex:outputPanel>
        </apex:pageBlock>  
      
    </apex:form>
</apex:page>

Test class

@isTest
public class PartnerLeadControllerTestClass {
    
    static testMethod void leadscontroller()
    {        
        Account myaccount = new Account (name='Test');
        insert myaccount;
        
        PageReference pageRef = Page.PartnerleadList;
        pageRef.getparameters().put('recordId', myaccount.Id);  
     
        Test.setCurrentPage(pageRef);
        
        
        Apexpages.StandardController sc = new Apexpages.StandardController(myaccount);
        PartnerLeadController partlead = new PartnerLeadController(sc);   
          
        
            }
   
}
I have written a test class to add list of leads

@isTest
private class UpdateUnitPriceTest {

    static testMethod void myUnitTest() {

        Test.startTest();

       Account myaccount = new Account (name='Test');
        insert myaccount;
        
LeadList = [select id,Name,CreatedDate,Company,OwnerId,Owner.Name,LeadSource,recordType.Name,CRM_User__r.Name,CRM_User__r.Id,CRM_User__c, Status, Account__c,LastName, Account__r.id,Account__r.OwnerId
                    from Lead 
                    where    CRM_User__c !=null And Account__c=: acc.Id AND LeadSource='Partner' AND recordType.Name = 'Partner Lead Registration' ];
    }

        // Verify the expressions are the same
        System.assertEquals('Lead list',+LeadList);

        

        Test.stopTest();

    }
}

Apex class
@isTest
public class PartnerLeadControllerTestClass {
    
    static testMethod void leadscontroller()
    {        
        Account myaccount = new Account (name='Test');
        insert myaccount;
        
        PageReference pageRef = Page.PartnerleadList;
        pageRef.getparameters().put('recordId', myaccount.Id);  
        Test.setCurrentPage(pageRef);
        
        Apexpages.StandardController sc = new Apexpages.StandardController(myaccount);
        PartnerLeadController partlead = new PartnerLeadController(sc);   
        partlead.getlead();
        partlead.initlead();
    }
   
}
public class SearchAccount_ctrl {
    
    public string city{get;set;}
    public Boolean show{get;set;}
    public integer size{get;set;}
   List<Account> AccList{get;set;}
    
    Public SearchAccount_ctrl()
    {
        Size=0;
        Show=False;
        AccList=new List<Account>();
    }
    
    Public void Search()
    {
        AccList=[Select id,Name,Rating,Industry From Account where Billingcity=:city];
        Size= AccList.size();
        If(size>0)
        {
            show=true;    
        }
        else
        {
            show=false;
        }
        
    }

}
=======================
VF Page:
<apex:page controller="SearchAccount_ctrl">
    <apex:form>
        <apex:pageBlock>
            <apex:pageblocksection >
                <apex:outputLabel id="a1">
                    <apex:pageblocktable title='Search Result' value="{!AccList}" var="item">
                      <apex:column value="{!item.Name}"/>  
                      <apex:column value="{!item.Billingcity}"/> 
                      <apex:column value="{!item.Rating}"/> 
                      <apex:column value="{!item.Industry}"/> 
                    </apex:pageblocktable>
                </apex:outputLabel>
            </apex:pageblocksection>
            <apex:commandButton title="Search" action="{!Search}"/>
        </apex:pageBlock>
    </apex:form>
</apex:page>
Since a week or so I suddenly get `INVALID_SESSION_ID: Session expired or invalid` errors when trying to deploy to a sandbox. Around the same time, I suddenly started seeing the line `*** Deploying with REST ***` when running an `sfdx force:source:deploy`.

I never used to see my token expire before. Now I have to daily go and re-auth my org connection.

This seems like a regression. What's going on?
trigger TriggerNew1Problem on Account(after insert)
{
    Set<String> setacc = new Set<String>();
    for(Account a : Trigger.new)
    {
        setacc.add(a.Name);
    }
    
    List<Account> acclist = [Select Id, Name, (Select Id, Name From Opportunities)
    From Account Where Name In : setacc
    ];
    List<Opportunity> opplist = new List<Opportunity>();
    
    Map<String, Account> nmap = new Map<String, Account>();
    for(Account a : acclist)
    {
        nmap.put(a.Name, a);
    }
    
    for(Account acc : Trigger.new)
    {
        if(nmap.get(acc.Name)!=null)
        {
            opplist.add(new Opportunity(AccountId =acc.Id, Name ='Duplicate Opportunity'+acc.Name, StageName = 'prospecting'
            , CloseDate = System.today()));         
        }
        else if(nmap.get(acc.Name)==null)
        {
             opplist.add(new Opportunity(AccountId =acc.Id, Name ='First Opportunity'+acc.Name, StageName = 'prospecting'
            , CloseDate = System.today()));
        }
    }
    if(opplist.size()>0)
    {
        insert opplist;
    }
}
when i inserted duplicate name in account then print duplicate opportunity name on the bases of account if not a duplicate account name then print first opportunity
But First Opportunity is not printed
public class CC {
@AuraEnabled
    public static Contact UpdateCC(Id recId) {
        if(recId==null){
            return null;
        }
        Contact c=[Select Id,checkbox__c FROM Contact WHERE Id=:recId LIMIT 1];
        c.checkbox__c =c.checkbox__c ==false ? true : false;
        update c;
        system.debug('cnt** '+cnt);
        return c;
    }

}
Dear Salesforce Professional

I am a beginner in Programming.
Please help me resolve this problem.

I have a requirement to create a child record (on Billing Line object) if parent records (on Billing object) exist I need to attach the child record (Billing Line) to the parent (Billing) but if Parent record doesn't exist I need to create parent and child records.

This trigger is supposed to fire when I check a checkbox on a TEST object.

For some reason, my code can't find parent records and can't create one.

I get this error message
"TriggerTestBillingLineCreate: execution of AfterUpdate caused by: System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [AcctSeed__Customer__c]: [AcctSeed__Customer__c] Class.testBillingLineCreate.createBillingLine: line 48, column 1 Trigger.TriggerTestBillingLineCreate: line 5, column 1"

Basically, it is saying the required field is missing when I am trying to create a parent record. I don't understand why it is missing if I populate it there and in some cases why it needs to create a parent record if a parent exists in a database. It just needs to find it and link a child record to the parent.

I attached my code below. I appreciate any advice. Thank you for your help!


public class testBillingLineCreate {
    public static void createBillingLine (list<TEST__c> TestList, map<id, TEST__c> oldMap)
    {
     list<AcctSeed__Billing_Line__c> billingLineList=new List<AcctSeed__Billing_Line__c>();      
     list<AcctSeed__Billing__c> billingList= new list<AcctSeed__Billing__c>();
        
         for(TEST__c objtest:TestList)
        {
        if(objtest.Billed__c==true && oldMap.get(objtest.Id).Billed__c==false)

        {
          for(AcctSeed__Billing__c billings:[select id, name, AcctSeed__Customer__c, advAcctSeed__Matter__c from AcctSeed__Billing__c where AcctSeed__Status__c='Approved']){

          if(billings.AcctSeed__Customer__c==objtest.Account__c && billings.advAcctSeed__Matter__c==objtest.Matter__c){

            AcctSeed__Billing_Line__c bill=new AcctSeed__Billing_Line__c();
           bill.AcctSeed__Billing__c=billings.Id;
            bill.AcctSeed__Project__c=objtest.Project__c;
            bill.AcctSeed__Hours_Units__c=objtest.time__c;                  
            bill.AcctSeed__Rate__c=objtest.Rate__c; 

            billingLineList.add(bill);
        }




         else {
              AcctSeed__Billing__c billings2=new AcctSeed__Billing__c();
              billings2.AcctSeed__Customer__c= objtest.Account__c;
               billings2.advAcctSeed__Matter__c=objtest.matter__c;
            billings2.AcctSeed__Status__c='Approved';
             billings2.AcctSeed__Date__c=date.today();
             billingList.add(billings2);

               AcctSeed__Billing_Line__c bill1=new AcctSeed__Billing_Line__c();
           bill1.AcctSeed__Billing__c=billings2.Id;
            bill1.AcctSeed__Project__c=objtest.Project__c;
            bill1.AcctSeed__Hours_Units__c=objtest.time__c;                  
            bill1.AcctSeed__Rate__c=objtest.Rate__c; 

            billingLineList.add(bill1);

            }
    }

        }
        insert billingList;
        insert billingLineList;
        }}}
Hello, I wanted to know if we use a Database.update() method in an Apex class for an sObject, does this update invoke 'before update' Apex trigger on that sObject?

Thanks for you help.
Hi, 
I am trying to create an error message for a parent object that returns a value from the child object.
The objects I'm using are Asset and a custom object Asset_Assignment__c. 
I can't seem to figure out how to return the value for the error message. 
Any help would be appreciated. 

Here's my code 
 
trigger AssetAssignmentValidation on Asset (before update, before insert) {
    LIST <string> AssetList = NEW LIST <string>();
    for(Asset a : Trigger.new){
        if(a.Status == 'Available' && a.OwnerID != NULL){
            AssetList.add(a.Name);
            
                    List <Asset_Assignment__c> assignmentlist = [SELECT Name FROM Asset_Assignment__c WHERE Asset_Name__c in : AssetList];
                     for (Asset_Assignment__c aa : assignmentlist)
                     {
                            string assignmentnumber = '';
                            assignmentnumber = aa.name;
                            return assignmentnumber; 
                     }
            a.adderror('Asset cannot be marked as available because it is currently assigned ' + 'Asset Assignment Number: ' + assignmentnumber);
        }
   }
   

}


 
Hello All,

Getting the error "The formula expression is invalid: Syntax error. Found ','" on PB when i used the formula expression.

Snippet:
IF([Object__c].amount__c <>  null, [Object__c].amount__c ,0)

Thanks,
VSK98​​​​​​​
  • May 11, 2020
  • Like
  • 0
Here is my Code

Apex Trigger
============
trigger EventUpdate on EventApproval__c (after update,before update) {
    
    List<String> ListAuto=new List<String>();
    //List<Event>lstEvent=new List<Event>();
    map<id,Event> mapevntupdate= new map<id,Event>();
    List<Id> EventToBeUpdatedId = new List<Id>();
    
    System.debug('trigger.new---'+trigger.new);    
    for(EventApproval__c EvAppr:trigger.new){
        ListAuto.add(EvAppr.EventAuto__c);
        EventToBeUpdatedId.add(EvAppr.Id);
    }
    System.debug('ListAuto---'+ListAuto);
    if(trigger.isAfter && Onetimeinsertupdate.EventUpdatetrigger){
        //lstEvent=[Select id,Ownerid,Description,Subject,Tavelled_From__c,Travelled_To__c,Kms_Travelled__c,Public_Transport_Fare__c,EventAuto__c,Reimbursement_Amount__c from Event where (EventAuto__c !=Null and EventAuto__c in :ListAuto) ];
        
            
            mapevntupdate=new map<id,Event>([Select id,Ownerid,Telephone_call_type__c,EventSubject__c,Description,Subject,Tavelled_From__c,
                      Travelled_To__c,Kms_Travelled__c,Public_Transport_Fare__c,
                                             EventAuto__c,Reimbursement_Amount__c,
                                             Sales_Manager_Assistance__c 
                                             from Event 
                                             where (EventAuto__c !=Null and EventAuto__c in :ListAuto) ]);
       
        system.debug('-----------map---'+ mapevntupdate.values());    
        for(EventApproval__c EvAppr:trigger.new){
            for(Event ev: mapevntupdate.values()){
                if(EvAppr.EventAuto__c==ev.EventAuto__c){
                    ev.Tavelled_From__c=EvAppr.Tavelled_From__c;   
                    ev.Travelled_To__c=Evappr.Travelled_To__c;
                    ev.Kms_Travelled__c=EvAppr.Kms_Travelled__c;
                    ev.Public_Transport_Fare__c=EvAppr.Public_Transport_Others_Fare__c;
                    //ev.Reimbursement_Amount__c=Integer.valueof(EvAppr.Reimbursement_Amount__c); 
                    ev.Description=EvAppr.Description__c;   
                    ev.Public_Transport_Mode__c=Evappr.Public_Transport_Mode__c;
                    ev.Conveyance_Mode__c=EvAppr.Conveyance_Mode__c;
                    ev.Status__c=EvAppr.Status1__c;
                    ev.Sales_Manager_Assistance__c=EvAppr.Sales_Manager_Assistance__c;
                    
                    // new code added by Ashish
                    ev.Telephone_call_type__c=EvAppr.Telephone_call_type__c;
                    ev.EventSubject__c=EvAppr.EventSubject__c;
                   // ev.Reason_for_winning__c=EvAppr.Reason_for_winning__c;
                  //  ev.Reason_for_losing__c=EvAppr.Reason_for_losing__c;
                   // ev.Reason_for_dropping__c=EvAppr.Reason_for_dropping__c;
                  //  ev.OtherDetails__c=EvAppr.OtherDetails__c;
                  //  ev.OtherDetails1__c=EvAppr.OtherDetails1__c;
                  //  ev.OtherDetails2__c=EvAppr.OtherDetails2__c;//Code End Here

                }
                
                
            } 
        }     
        
        // Logic for updating the Event Status and Comment 
        
        
        List<ProcessInstance>lstprocess = [Select p.TargetObjectId, p.Status, (Select StepStatus,Comments From Steps where StepStatus!='Started') From ProcessInstance p where TargetObjectId in :trigger.newMap.keyset()];
        if(lstprocess .size()>0){ 
            for(Event ev:mapevntupdate.values()){ 
                for(ProcessInstance step :lstprocess ){
                    for( ProcessInstanceStep st:step.Steps){
                        ev.Comments__c=st.Comments; 
                        
                        system.debug('--------------------Steps Ststus----- '+st.StepStatus);
                        system.debug('##########+comments are----'+st.Comments);
                    }
                    /*if(step.Status!='Started'){
ev.Status__c=step.Status;
}else{
ev.Status__c='Pending';
}*/
                    
                    ev.Approved_Date__c=system.today();
                    system.debug('@@@@@@Approval Status---'+step.Status);
                }
                
            }
            
        }  
        system.debug('&&&&&&&&&&&&&&&&&&'+mapevntupdate.size());
        if(mapevntupdate.size()>0){
            system.debug('&&&&&&&&&&&&&&&&&&');
            Onetimeinsertupdate.eventupdateflag=false;
            Onetimeinsertupdate.EventUpdatetrigger = false;
            //update lstEvent;
            update mapevntupdate.values();
            system.debug('************'+mapevntupdate.size());
            
        }
        
        
        //MyFutureClass.myMethod(EventToBeUpdatedId,ListAuto);
        
        
        Onetimeinsertupdate.EventUpdatetrigger=false;
    }
    if(Trigger.isBefore){
        List<ProcessInstance>lstprocess = [Select p.TargetObjectId, p.Status, (Select StepStatus, Comments From 
                                                                               
                                                                               Steps where StepStatus!='Started') From ProcessInstance p where TargetObjectId in :trigger.newMap.keyset()];
        if(lstprocess .size()>0){ 
            for(EventApproval__c Ev:trigger.new){ 
                for(ProcessInstance step :lstprocess ){
                    for( ProcessInstanceStep st:step.Steps){
                        ev.Comments__c=st.Comments; 
                        
                        system.debug('--------------------Steps Ststus----- '+st.StepStatus);
                        system.debug('##########+comments are----'+st.Comments);
                    }
                    
                    /* if(step.Status!='Started'){
ev.Status1__c=step.Status;
}else{
ev.Status1__c='Pending';
}*/
                    //ev.Status1__c=step.Status;
                    // ev.Approved_Date__c=system.today();
                    system.debug('@@@@@@Approval Status---'+step.Status);
                }
                
                
            }
        }
        
    }
       
}


Test Class 27 percent code coverage 
============================
@isTest
public class TestEventUpdateTest {
public static testMethod void testcontroller(){
test.startTest();
    
Account acc=new Account();
acc.Name='test Account';
Opportunity opp = new Opportunity();
opp.Accountid = acc.id;
opp.StageName = '00-Pending';
opp.CloseDate = system.today();
opp.name = 'Test Opportunity';
opp.Hardware__c=true;
opp.No_Of_Units_Of_Hardware__c=5;
opp.INR_Hardware_Contract_Value_In_Lacs__c=5;
opp.Product_Type__c='Hardware';
insert opp;
update opp;
    
Event objevent=new Event(WhatID = opp.id,Subject='visit');
objevent.DurationInMinutes = 1;
objevent.Subject='Test subject';
objevent.StartDateTime=System.today()-1;
objevent.Tavelled_From__c='kanpur';
objevent.Travelled_To__c='delhi';
objevent.Kms_Travelled__c=10;
objevent.Status__c='New';
objevent.Public_Transport_Fare__c=100;
insert objEvent;
objevent.Tavelled_From__c='lucknow';   
objevent.Travelled_To__c='mumbai';
objevent.Kms_Travelled__c=14;
objevent.Public_Transport_Fare__c=200; 
update objevent;
    
map<id,EventApproval__c> mapevntappupdate= new map<id,EventApproval__c>();
EventApproval__c objevent1=new EventApproval__c(); 
objevent1.Tavelled_From__c='kanpur';
objevent1.Travelled_To__c='delhi';
objevent1.Kms_Travelled__c=10;
objevent1.Kms_Travelled__c=10;
objevent1.Conveyance_Mode__c='test';
objevent1.Telephone_call_type__c='Service call';
objevent1.Reason_for_winning__c='Product quality';
objevent1.Reason_for_dropping__c='Insufficient budget';
objevent1.Reason_for_losing__c='Mapping';
objevent1.OtherDetails__c='Test';
objevent1.OtherDetails1__c='Test1';
objevent1.OtherDetails2__c='Test2';
insert objevent1;
    
objevent1.Tavelled_From__c='lucknow';   
objevent1.Travelled_To__c='mumbai';
objevent1.Kms_Travelled__c=14;
objevent1.Public_Transport_Mode__c='test';
objevent1.Conveyance_Mode__c='test';
objevent1.Sales_Manager_Assistance__c='test';
objevent1.Telephone_call_type__c='Service call';
objevent1.Reason_for_winning__c='Product quality';
objevent1.Reason_for_dropping__c='Insufficient budget';
objevent1.Reason_for_losing__c='Mapping';
objevent1.OtherDetails__c='Test';
objevent1.OtherDetails1__c='Test1';
objevent1.OtherDetails2__c='Test2';
update objevent1;


/*opp.StageName='Prospect';
update opp;
opp.StageName='Proposal in Play';
update opp;
opp.StageName='Demo';
update opp;
opp.StageName='Negotiation';
update opp;
opp.StageName='Closed Won';
update opp;*/
List<Opportunity> oppmapid = [SELECT Id, Name, StageName FROM Opportunity];
system.debug('oppmapID@@@@@@@@@@@@@@@@@@@'+oppmapid);
test.stopTest();
}
}
public class N1apex {
   @AuraEnabled
    public static ID mySearch(String phon){
        Contact acc=[select ID,Phone,AccountId from Contact where Phone=:phon];
        return acc.AccountId;
    }
    @AuraEnabled
    public static string names(String firstname,String lastname,ID accountId){
        String status;
        try{
        contact c=new contact();
        c.FirstName=firstname;
        c.LastName=lastname;
        c.AccountId=accountId;
        insert c;
        status='Record inserted';
    }
        catch(Exception e){
            status='Record Failed';
        }
        return status;
}
}
----------------------------------------------------------------------------------------------------------------
<aura:event type="COMPONENT" description="Event template" >
    <aura:attribute name="accountId" type="ID"/>
</aura:event>

----------------------------------------------------------------------------------------------------------------
<aura:component controller="N1apex">
    <aura:registerEvent name="myEvent" type="c:N1Event" />
    
    <div>
        <lightning:input label="phone" aura:id="pname"/>
        <lightning:button label="submit" onclick="{!c.show}"/>
    </div>
</aura:component>

({
	show : function(component, event, helper) {
    	var phone1=component.find("pname").get("v.value");        
        
        var action=component.get("c.mySearch");
        action.setParams({"phon":phone1});
        action.setCallback(this,function(response){
            console.log("Method invoked");
            var state=response.getState();
            if(state==='SUCCESS'){
                console.log("Operation Successfull");
                var accid=response.getReturnValue();
				var evt=component.getEvent("myEvent");
                evt.setParams({"accountId":accid});
                evt.fire();
            }
                else{
                    console.log("Operation Failed");
                }                
            }
        );
        $A.enqueueAction(action);
	}
})

----------------------------------------------------------------------------------------------------------------
<aura:component controller="N1apex">
    <aura:handler name="myEvent" event="c:N1Event" action="{!c.invoke}"/>
    <lightning:input label="LastName" aura:id="lname"/>
    <lightning:input label="FirstName" aura:id="fname"/>
    <c:N1Event_Child />
</aura:component>

({
	invoke : function(component, event, helper) {
        var lname=component.find("lname").get("v.value");
        var fname=component.find("fname").get("v.value");
        var acctid=component.getParams("accountId");
        var action=component.get("c.names");
        action.setParams({"lastname":lname,"firstname":fname,"accountid":acctid});
        action.setCallback(this,function(response){
            var state=response.getState();
            if(state==='SUCCESS'){
                alert(response.getReturnValue());
            }
            else{
                alert('Failed');
            }
        });
        $A.enqueueAction(action);
        
	}
})

--------------------------------------------------------------------------------------------------------------

<aura:application extends="force:slds">
    <c:N1Event_Parent />
</aura:application>

 
Probably a stupid question but here goes. I'm a long-time developer but pretty new to SalesForce Apex.

I have a custom object table containing a bunch of user Ids that is partially filled in. I need to assign fields from table to fields on account records.

Right now I am checking before each field assignment if that particular field is null before doing the assignment like:
if (ct.Id1 != null) {
   a.Id1 = ct.Id1;
}

Is there a better way to do this? There's a bunch of fields and it's a pain to write this over and over.

Thanks! 
Hi Team,
I am inserting the account records into the salesforce through another system.
for account record we have written code to generate the external ID of the records based on the i.e.First Name , Last Name and Primary Email.
if customer is inserting the same record with same 3 field values (i.e.First Name , Last Name and Primary Email) then these record should update the existing records only.
but now update operation is not working. only insert operation is working.
Kindly check below code of Handler Class:

=============Handler Class========Trigger EVENT : After Insert======
    
     public void Uniqueaccount(){
           
        list<Account> accToUpdate = new list<Account>(); 
        for(Account accountObj : newAccountList){
             
            Integer blankCount = 0;
            Account acc = accountObj.clone();
            acc.Id = accountObj.Id;
            if(!String.IsBlank(accountObj.FirstName)) {
                                          
                acc.SVC_ExternalCustomerId__c = accountObj.FirstName + '|';
            } else {  
               
                acc.SVC_ExternalCustomerId__c = '|';
                
                blankCount++;
            }            
            if(!String.IsBlank(accountObj.LastName )) {                
               
                acc.SVC_ExternalCustomerId__c = acc.SVC_ExternalCustomerId__c + accountObj.LastName + '|';
            } else {                
               
                acc.SVC_ExternalCustomerId__c = accountObj.SVC_ExternalCustomerId__c + '|';
                blankCount++;
            }            
            if(!String.IsBlank(accountObj.PersonEmail)){                
                
                acc.SVC_ExternalCustomerId__c = acc.SVC_ExternalCustomerId__c + accountObj.PersonEmail; 
            }
            else {                
                blankCount++;
            }   
           
            if(String.isNotBlank(accountObj.clearmdm__MDMStatus__c) &&
               accountObj.clearmdm__MDMStatus__c.equalsIgnoreCase('Merge Source')){                   
                  
                   acc.SVC_ExternalCustomerId__c = acc.SVC_ExternalCustomerId__c + '|' + accountObj.Id;
               }
            else if(blankCount > 0){
                acc.SVC_ExternalCustomerId__c = accountObj.SVC_ExternalCustomerId__c + '|' + accountObj.Id;
                acc.SVC_ExternalCustomerId__c = acc.SVC_ExternalCustomerId__c + '|' + accountObj.Id;
            }
            accToUpdate.add(acc);
            
        }
        try{
           
            update accToUpdate; 
            
        }
        Catch(DmlException e) {
            System.debug('An exception occurred:setCustomerUniqueKey** ' + e.getMessage());
        
        }
       
    }
Hi all,

My mission statement:  Use picklist values to determine whether or not a text field should be mandatory/required

I tried the formula above as a validation rule:

IF(ISPICKVAL(Charities_Register_Status__c , "Registered"),LEN( Charities_Register_No__c )<1, Charities_Register_No__c =NULL)


where 'Charities_Register_Status' = Picklist
and 'Charities_Register_No' = Required Text Field

I only want the 'Charities_Register_No' to be Mandatory/Required if the 'Charities_Register_Status__c' selection = 'Registered'

Can anyone confirm if the validation rule I've used above is correct to achieve this?  I've tested it and no matter what the 'Charities_Register_Status__c' selection, the 'Charities_Register_No' is still required.