• SFDC Apex Dev
  • NEWBIE
  • 59 Points
  • Member since 2018
  • Salesforce Developer

  • Chatter
    Feed
  • 1
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 29
    Questions
  • 41
    Replies
I am new to coding in general and to Apex in particular so any help I can get is greatly appreciated.

I am building a trigger that will create a new custom object record from an opportunity.

I plan to use process builder to fire the trigger when a particular opp type is created or when a particular field in that opp is updated.

I want the new record to be related to the Opp so i want to pull the Opp ID and some of the fields into the trigger to use in the new record.

How do i pull that specific data in?

Like I said, I am new at this but willing to work and learn.

Best regards,
Steve
 
Hi Everyone,

I want to optimize the below apex code, but I'm facing technical chalenge. I want to add the repetetive code used in if and else block in some function so that I can call that in the if else block instead of adding the repetetive code.

Highlighting the code below which is repeated and has to be added to some function which can be called in place of that and can able to reduce the line of code and optimize it.
public class void newClass{	
	@RemoteAction
	global static ccrz.cc_RemoteActionResult newMethod(final ccrz.cc_RemoteActionContext ctx,string a, string locale){
		ccrz.cc_RemoteActionResult res = new ccrz.cc_RemoteActionResult();
		Boolean guestUsr = false;
		String USER_LOCALE;
		String User_Locale_Search;
		if(String.isBlank(locale)){
			USER_LOCALE = UserInfo.getLocale();
			if(String.isBlank(USER_LOCALE)){
				USER_LOCALE = 'en_US';
			}
		}else{
			USER_LOCALE = locale;
		}
		if(UserInfo.getUserType() == 'Guest') {
			if(!String.isBlank(locale)){
				USER_LOCALE = locale;
				User_Locale_Search = '%'+ locale +'%';
			}else{
				USER_LOCALE = 'en_US';
			}
			guestUsr = true;
		}
		
		try{
			Id recordType = Schema.SObjectType.O_C_R__c.getRecordTypeInfosByName().get('Nav').getRecordTypeId();
			O_M_P__c oModelProd = getoTaxonomyId(sku);
			O_C_R__c o = [select id, P_T__c,C_T__c,Ch_Ca__c,Par_Ca__r.Name, Relationship_Type__c,RecordTypeId from O_C_R__c where Ch_Ca__r.Name=: oModelProd.O_Cat_P__r.Name and Relationship_Type__c = 'sn_p5' and RecordTypeId=:recordType ];
			O_C_R__c p = [select id, P_T__c,C_T__c,Ch_Ca__c,Par_Ca__c,Par_Ca__r.Name,RecordTypeId,Relationship_Type__c from O_C_R__c where Ch_Ca__r.Name =: o.Par_Ca__r.Name and  RecordTypeId = :recordType and Relationship_Type__c= 'sn_q4'];
			O_C_R__c q = [select id, P_T__c,C_T__c,Ch_Ca__c,Par_Ca__c,Par_Ca__r.Name,RecordTypeId,Relationship_Type__c  from O_C_R__c where Ch_Ca__r.Name =: p.Par_Ca__r.Name and  RecordTypeId = :recordType and Relationship_Type__c = 'sn_r3'];
			O_C_R__c r = [select id, P_T__c,C_T__c,Ch_Ca__c,Par_Ca__c, Par_Ca__r.Name from O_C_R__c where Ch_Ca__r.Name =: q.Par_Ca__r.Name];
			
			details addNewDetails = new details();
			if(guestUsr == false){
				if(USER_LOCALE == 'en_US'){
					if (oModelProd!= null){
						addNewDetails.customName = oModelProd.C_Pro__r.Custom__c;
					}
					if(q!=null){
						addNewDetails.rName = q.P_T__c;
						addNewDetails.rid = q.Par_Ca__c;
						addNewDetails.qName = q.C_T__c;
						addNewDetails.qid = q.Ch_Ca__c;
					}
					if(p != null){
						addNewDetails.pName =  p.C_T__c;
						addNewDetails.pid =  p.Ch_Ca__c;
					}
					if(o != null){
						addNewDetails.oName =  o.C_T__c;
						addNewDetails.oid =  o.Ch_Ca__c;
					}
					if(r!= null){
						addNewDetails.l1Name = r.P_T__c;
					}
				}else{
					if (oModelProd!= null){
						addNewDetails.customName = oModelProd.C_Pro__r.Custom__c;
					}
					if(o != null){
						O_Cat_P_18N__c i18NCatalog = [select id,Title__c,O_Cat_P__c,O_Cat_P__r.Title__c,name from O_Cat_P_18N__c where O_Cat_P__c =: o.Ch_Ca__c and Locale__c =: USER_LOCALE];
						addNewDetails.oName = i18NCatalog.Title__c ;
						addNewDetails.oid =  o.Ch_Ca__c;
						addNewDetails.oNameURL = o.C_T__c;
					}
					if(p != null){
						O_Cat_P_18N__c i18NCatalog = [select id,Title__c,O_Cat_P__c,O_Cat_P__r.Title__c,name from O_Cat_P_18N__c where O_Cat_P__c =: p.Ch_Ca__c and Locale__c =: USER_LOCALE];
						addNewDetails.pName = i18NCatalog.Title__c ;
						addNewDetails.pid =  p.Ch_Ca__c;
						addNewDetails.pNameURL =  p.C_T__c;
					}
					if(q!=null){
						O_Cat_P_18N__c i18NCatalog = [select id,Title__c,O_Cat_P__c,O_Cat_P__r.Title__c,name from O_Cat_P_18N__c where O_Cat_P__c =: q.Ch_Ca__c and Locale__c =: USER_LOCALE];
						O_Cat_P_18N__c i18NCatalog1 = [select id,Title__c,O_Cat_P__c,O_Cat_P__r.Title__c,name from O_Cat_P_18N__c where O_Cat_P__c =: q.Par_Ca__c and Locale__c =: USER_LOCALE];
						addNewDetails.qName = i18NCatalog.Title__c;
						addNewDetails.rName = i18NCatalog1.Title__c;
						addNewDetails.rid = q.Par_Ca__c;
						addNewDetails.qid = q.Ch_Ca__c;
						addNewDetails.rNameURL = q.P_T__c;
						addNewDetails.qNameURL = q.C_T__c;
					}
					if(r!= null){
						O_Cat_P_18N__c i18NCatalog = [select id,Title__c,O_Cat_P__c,O_Cat_P__r.Title__c,name from O_Cat_P_18N__c where O_Cat_P__c =: r.Par_Ca__c and Locale__c =: USER_LOCALE];
						addNewDetails.l1Name = i18NCatalog.Title__c;
						addNewDetails.l1NameURL = r.P_T__c;
					}
				}
			}else{
				if(USER_LOCALE == Label.HN_DefaultLocale){
					if (oModelProd!= null){
						addNewDetails.customName = oModelProd.C_Pro__r.Custom__c;
					}
					if(q!=null){
						addNewDetails.rName = q.P_T__c;
						addNewDetails.rid = q.Par_Ca__c;
						addNewDetails.qName = q.C_T__c;
						addNewDetails.qid = q.Ch_Ca__c;
					}
					if(p != null){
						addNewDetails.pName =  p.C_T__c;
						addNewDetails.pid =  p.Ch_Ca__c;
					}
					if(o != null){
						addNewDetails.oName =  o.C_T__c;
						addNewDetails.oid =  o.Ch_Ca__c;
					}
					if(r!= null){
						addNewDetails.l1Name = r.P_T__c;
					}
				}else{
					if (oModelProd!= null){
						addNewDetails.customName = oModelProd.C_Pro__r.Custom__c;
					}
					if(o != null){
						O_Cat_P_18N__c i18NCatalog = [select id,Title__c,O_Cat_P__c,O_Cat_P__r.Title__c,name from O_Cat_P_18N__c where O_Cat_P__c =: o.Ch_Ca__c and Locale__c LIKE: User_Locale_Search];
						addNewDetails.oName = i18NCatalog.Title__c ;
						addNewDetails.oid =  o.Ch_Ca__c;
						addNewDetails.oNameURL =  o.C_T__c;
					}
					if(p != null){
						O_Cat_P_18N__c i18NCatalog = [select id,Title__c,O_Cat_P__c,O_Cat_P__r.Title__c,name from O_Cat_P_18N__c where O_Cat_P__c =: p.Ch_Ca__c and Locale__c LIKE: User_Locale_Search];
						addNewDetails.pName = i18NCatalog.Title__c ;
						addNewDetails.pid =  p.Ch_Ca__c;
						addNewDetails.pNameURL =  p.C_T__c;
					}
					if(q!=null){
						O_Cat_P_18N__c i18NCatalog = [select id,Title__c,O_Cat_P__c,O_Cat_P__r.Title__c,name from O_Cat_P_18N__c where O_Cat_P__c =: q.Ch_Ca__c and Locale__c LIKE: User_Locale_Search];
						O_Cat_P_18N__c i18NCatalog1 = [select id,Title__c,O_Cat_P__c,O_Cat_P__r.Title__c,name from O_Cat_P_18N__c where O_Cat_P__c =: q.Par_Ca__c and Locale__c LIKE: User_Locale_Search];
						addNewDetails.qName = i18NCatalog.Title__c;
						addNewDetails.rName = i18NCatalog1.Title__c;
						addNewDetails.rid = q.Par_Ca__c;
						addNewDetails.qid = q.Ch_Ca__c;
						addNewDetails.rNameURL = q.P_T__c;
						addNewDetails.qNameURL = q.C_T__c;
					}
					if(r!= null){
						O_Cat_P_18N__c i18NCatalog = [select id,Title__c,O_Cat_P__c,O_Cat_P__r.Title__c,name from O_Cat_P_18N__c where O_Cat_P__c =: r.Par_Ca__c and Locale__c LIKE: User_Locale_Search];
						addNewDetails.l1Name = i18NCatalog.Title__c;
						addNewDetails.l1NameURL = r.P_T__c;
					}
				}
			}
			if(addNewDetails!=null){
				res.success = true;
				res.data = addNewDetails;
			}else{
				res.success = false;
			}
		}catch(Exception exp){
			res.success = false;
			res.data = exp.getMessage() + ' ' + exp.getLineNumber();
		}
		return res ;
	}

	public class details{
		public string l1Name{get;set;}
		public string rName{get;set;}
		public string rid{get;set;}
		public string qName{get;set;}
		public string qid{get;set;}
		public string pName{get;set;}
		public string pid{get;set;}
		public string oName{get;set;}
		public string oid{get;set;}
		public string customName{get;set;}
		public string l1NameURL{get;set;}
		public string rNameURL{get;set;}
		public string qNameURL{get;set;} 
		public string pNameURL{get;set;}       
		public string oNameURL{get;set;}
	}
}

For guest user and loggedin user the code is repetetice. Can anyone please help me to optimize/reduce the line of code?
I'm trying to write the below piece of code and calling it in after update context on opportunity.
I want to send email to the reciepient once the opportunity updated to stage 5 and product code on related opportunity product is STD.
I've created the email template as well and using the email tmplate id in the code but I'm not getting any email notification. Can anyone please help me out to correct the code?
public static void emailAlert(list<Opportunity> newOpportunityList, Map<Id,Opportunity> oldOpportunityMap){
        Set<id> OpptyId = new Set<id>();
        List<OpportunityLineItem> lstOptyLineItem = new List<OpportunityLineItem>();
        for(Opportunity ObjOppty: newOpportunityList){
            if(oldOpportunityMap.get(ObjOppty.Id).StageName != ObjOppty.StageName && ObjOppty.StageName == 'Won'){
                OpptyId.add(ObjOppty.id);
            }
        }
        if(OpptyId.size() > 0){
          lstOptyLineItem = [Select id,Name,ProductCode from OpportunityLineItem where OpportunityId IN: OpptyId AND ProductCode = 'STD';    
        }
        
        if(lstOptyLineItem.size() > 0){
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            List<String> sendTo = new List<String>{'cgupta@gmail.com'};
            mail.setTemplateId('00X02000000A34cEAC');
            mail.setToAddresses(sendTo);
            //system.debug('to address'+ mail.setToAddresses);
            mail.setOrgWideEmailAddressId(System.Label.Support_Email_Address);
            //system.debug('org address'+ mail.setOrgWideEmailAddressId);
           // mail.setTargetObjectId(primaryContact);
            List<Messaging.SingleEmailMessage> allmsg = new List<Messaging.SingleEmailMessage>();
            allmsg.add(mail);
            system.debug('mail sent'+mail);
            try {
                Messaging.sendEmail(allmsg,false);
                return;
            } catch (Exception e) {
                System.debug(e.getMessage());
            }
        }
    }

Please help me here to correct the above code.
Here is the Scenario:
We're having Email-to-Case functionality. Whenever a new Email received on case the case field Status Alert should get updated with value "Received" and when replied to that email same field should get blank.

Can anyone please help me out with this trigger?
 
trigger emailMessageTrigger on EmailMessage (before insert, before update) {
    Set<Id> caseIdSet = new Set<Id>();
    list<Case> casList = new list<Case>();
    
    for(EmailMessage email: Trigger.new){
        caseIdSet.add(email.ParentId);
    }
    
    if(caseIdSet != null && caseIdSet.size() > 0){
        casList = [Select Id, Status, Status_Alert__c from Case where Id IN: caseIdSet AND Status != 'New' AND Status_Alert__c	!= 'New Email Received'];
    }
    
    for(EmailMessage newEmail: Trigger.new){
        if(casList.size() > 0){
            for(Case cas: casList){
                cas.Status_Alert__c	 = 'New Email Received';
                update cas;
            }
        }
    }
}

 

We had a button with the below JS code
JS Code on Button

{!requireScript("/soap/ajax/30.0/connection.js")} 
{!requireScript("/soap/ajax/30.0/apex.js")} 

var opp = new sforce.SObject("Opportunity");
opp.id = "{!Opportunity.Id}"; 
try {
   opp.Def_Sc = true;

   var optresult = sforce.connection.update([opp]);
   if(optresult[0].success=='false') {
      alert(optresult[0].errors.message);
   } else {
      sforce.apex.execute('EmbedAutomation', 'automationForSales',    {optyId:'{!Opportunity.Id}', action:'Default'});    
alert('{!$Label.Def_Proceed}');
   }
} catch(err) {
   alert(err.message);
}
document.location = '/{!Opportunity.Id}';

Now need to convert this JS code in vf page. I tried below but not working as expected.

 

<apex:page standardController="Opportunity" showHeader="false">   
    <head>
        <style type='text/css'>
            .popupBackground{
            left: 20%;
            color:red;
            position: fixed;
            width: 450px;
            height: 100px;
            margin-left: -200px;
            top: 50px;
            }
            .popupBackground .close{
            position: absolute;
            background:#008CBA;
            color: white;
            bottom: 0;
            right: 10px;
            font-size: 10px;
            text-decoration: none;
            width:50px;
            }
        </style>
    </head>
    
    <apex:form >
        <body onload="init();">
            <apex:outputPanel styleClass="popupBackground" rendered="{!successMsg}">
                <center>
                    <apex:outputText value="{!$Label.Def_Proceed}" escape="false"/>
                    <apex:commandButton value="OK" styleClass="close" onclick="parent.window.close();"/>
                </center>
            </apex:outputPanel>
            <apex:outputPanel styleClass="popupBackground" rendered="{!errMsg}">
                <center>
                    <apex:outputText value="{!$Label.Error}" escape="false"/>
                    <apex:commandButton value="OK" styleClass="close" onclick="parent.window.close();"/>
                </center>
            </apex:outputPanel>
        </body>
    </apex:form>
    
    <script src="/soap/ajax/30.0/connection.js"></script >
    <script src="/soap/ajax/30.0/apex.js"></script>
    <script>
    sforce.connection.sessionId = "{!$Api.Session_ID}";
    function init()
    {
        var successMsg;
        var errMsg;
        var opp = new sforce.SObject("Opportunity");
        opp.id = "{!Opportunity.Id}";
        
        try {
            opp.Def_Sc = true;
            
            var optresult = sforce.connection.update([opp]);
            if(optresult[0].success=='false') {
                errMsg = true;
            } else {
                
                sforce.apex.execute('EmbedAutomation', 'automationForSales', {optyId:'{!Opportunity.Id}', action:'Default'});
                successMsg = true;
            }
        } catch(err) {
            errMsg = true;
        }
    }
    </script>
</apex:page>

Need to use standard controller with extension customcontroller but didn't get success yet. It should be look like below screenshot.

User-added image
I want to show the error message or success message once we are clicking the button on opportunity and shoud show the message as per the screenshot.


User-added image
Please anyone can help me out in this?
{!REQUIRESCRIPT("/soap/ajax/13.0/connection.js")}
{!requireScript("/soap/ajax/30.0/apex.js")}
var oppObj = new sforce.SObject("Opportunity");
oppObj.Id = '{!Opportunity.Id}'; 
var result = sforce.connection.update([oppObj]);
if (result[0].success=='false') {
alert(result[0].errors.message);
}
else {
sforce.apex.execute('ApexClass', 'methodName', {optyId:'{!Opportunity.Id}', action:'Default'});
alert('{!$Label.Success}');
}
}
document.location = '/{!Opportunity.Id}';

I've simply addeed the entire code to vf page, standardcontroller as Opportunity.
I need to use CSS as well so that the error msg can be displayed in left top instead of the alert box which displayed at the center on top.

Please help ASAP.
trigger LinkEnCusToAccP on Acc_P__c (before insert, before update) {
    // Data load bypass    
    if(IsUtil.adminByPass()) return;
    
    Private Integer iCount = 0;

    for (Acc_P__c a : Trigger.new) {
        if(Trigger.isUpdate) {
            if(a.Account__c != Trigger.old[iCount].Account__c) {
                a.Ent_Cus__c = [select Ent_Cus__c from Account where Id = :a.Account__c limit 1].Ent_Cus__c;
            }
            iCount++;
        } else {
            if(a.Account__c != null) {
                a.Ent_Cus__c = [select Ent_Cus__c from Account where Id = :a.Account__c limit 1].Ent_Cus__c;
            }
        }
    }
}
Hi All,

Here is the scenario : 
On the account object, create a new field to store the date and time stamp of the most recent change to the account name or the account address.

I have written th code but it's not working.. could any please help me out to correct it?? Is it possible to update date on changes without querying any account in class??

public class AccountHandler {
    public static void updateAccount(List<Account> accountList, Map<Id,Account> oldAccountMap)){
        
        Set<Id> accid = new Set<Id>();
               
        If(accid.size()>0){
            
            List<Account> accList = [SELECT Id, Name, Physical_Address__c from Account where Id in:accid);
            
            if(accList.size()>0){
                
                for(Account acc:accList) {
                    
                    if(Trigger.IsUpdate && !oldAccountMap.isEmpty() && oldAccountMap.containsKey(acc.Id) &&
                    ((oldAccountMap.get(acc.Id).Name != acc.Name || oldAccountMap.get(acc.Id).Physical_Address__c != acc.Physical_Address__c)){
                        acc.Address_Change_Date__c = System.now();
                    }                    
                }
            }        
            Update accList;
        }
    }
}


I am calling this method in after update.. from trigger controler...
AND(NOT(ISBLANK(Component__c)),AND(OR(AND(Component__r.Product__r.yes__c = FALSE,NOT(ISPICKVAL(Component__r.type__c,"exhausted"))),NOT(ISPICKVAL( Component__r.Status__c,"install"))),Service__c = FALSE),$RecordType.Name='supportive', 
$Setup.settings__c.Validate__c = FALSE, 
ISBLANK(source__c),ISPICKVAL(Categories__c,"fields"),OR(ISPICKVAL(Reasons__c,"appear"), ISPICKVAL(Reasons__c,"Maintenance")),NOT(ISPICKVAL(Origin,"Portal")),Component__r.Product__r.source__c = "RT")
//Generated by wsdl2apex

public class AsyncMWParts {
    public class cancelPartsRespFuture extends System.WebServiceCalloutFuture {
        public MWParts.cancelPartsResp getValue() {
            MWParts.cancelPartsResp response = (MWParts.cancelPartsResp)System.WebServiceCallout.endInvoke(this);
            return response;
        }
    }
    public class createPartsRespFuture extends System.WebServiceCalloutFuture {
        public MWParts.createPartsResp getValue() {
            MWParts.createPartsResp response = (MWParts.createPartsResp)System.WebServiceCallout.endInvoke(this);
            return response;
        }
    }
    public class AsyncSOAPOverHTTPs {
        public String endpoint_x = 'https://abc2b-dev.sales.com/Common/PurchaseOrder-2.0';
        public Map<String,String> inputHttpHeaders_x;
        public String clientCertName_x;
        public Integer timeout_x;
        private String[] ns_map_type_info = new String[]{'https://abc2b.sales.com/Common/PurchaseOrder-2.0', 'MWParts'};
        public AsyncMWParts.cancelPartsRespFuture beginCancelParts(System.Continuation continuation,MWParts.RMAShipmentLine[] sObject_x) {
            MWParts.cancelPartsReq request_x = new MWParts.cancelPartsReq();
            request_x.sObject_x = sObject_x;
            return (AsyncMWParts.cancelPartsRespFuture) System.WebServiceCallout.beginInvoke(
              this,
              request_x,
              AsyncMWParts.cancelPartsRespFuture.class,
              continuation,
              new String[]{endpoint_x,
              'cancelPartsOrderAction2_0',
              'https://abc2b.sales.com/Common/PurchaseOrder-2.0',
              'cancelPartsReq',
              'https://abc2b.sales.com/Common/PurchaseOrder-2.0',
              'cancelPartsResp',
              'MWParts.cancelPartsResp'}
            );
        }
        public AsyncMWParts.createPartsRespFuture beginCreateParts(System.Continuation continuation,MWParts.RMAShipmentLine[] sObject_x) {
            MWParts.createPartsReq request_x = new MWParts.createPartsReq();
            request_x.sObject_x = sObject_x;
            return (AsyncMWParts.createPartsRespFuture) System.WebServiceCallout.beginInvoke(
              this,
              request_x,
              AsyncMWParts.createPartsRespFuture.class,
              continuation,
              new String[]{endpoint_x,
              'createPartsOrderAction2_0',
              'https://abc2b.sales.com/Common/PurchaseOrder-2.0',
              'createPartsReq',
              'https://abc2b.sales.com/Common/PurchaseOrder-2.0',
              'createPartsResp',
              'MWParts.createPartsResp'}
            );
        }
    }
}
Created two field (data type-picklist) on the opportunity and have to make the fields mandatory when the Sales Occupy = Field Sales AND the stage is advancing beyond Stage 2, then these 2 fields mandatory.

I tried below... but not working....Could you please correct me??

AND ( NOT ( ISPICKVAL ( StageName,  '2. Discover' )  )  ),
 ISPICKVAL(Sales__c, 'Field Sales'), ISBLANK ( TEXT ( Fin_Se__c ) ) || ISBLANK ( TEXT ( Fin_Se_Type__c ) ) )
global class UrlUtils {
    
    global static String getBase(String url){
        String[] split = StringUtils.split(url, '?');
        if(split == null || split.size() == 0){
            return null;
        }
        return split[0];
    }

    global static Map<String,String> getParams(String url){
        //url -> http://google.com?api=x&xyz=123
        Map<String,String> returnMap = new Map<String,String>();
        String[] split = StringUtils.split(url, '?');
        //split -> ['http://google.com','api=x&xyz=123']
        if(split == null || split.size() != 2 || split[1] == null){
            return returnMap;
        }
        split = StringUtils.split(split[1],'&');
        //split -> ['api=x','xyz=123']
        if(split != null && split.size() > 0){
            String[] split2 = null;
            for(String keyValuePair : split){
                //keyValuePair -> 'api=x'
                split2 = StringUtils.split(keyValuePair,'=');
                returnMap.put(
                    (split2 == null || split2.size() < 1 ? '' : split2[0]),
                    EncodingUtil.urlDecode(split2 == null || split2.size() < 2 ? '' : split2[1], 'UTF-8'));
            }
        }
        return returnMap;
    }

    global static String ensureUrlBeginsWithHttp(String url){
        if(StringUtils.isNotEmpty(url)){
            final String lowerCaseUrl = StringUtils.lowerCase(url);
            if(    !StringUtils.startsWith(lowerCaseUrl, 'http://') 
              &&   !StringUtils.startsWith(lowerCaseUrl, 'https://')){
                url = 'http://' 
                    + StringUtils.stripStart(
                        (StringUtils.contains(lowerCaseUrl, '//') 
                            ? StringUtils.substringAfter(url, '//') 
                            : url)
                        ,'/:'
                    );
            }
        }
        return url;
    }

}
In this trigger, I am populating the custom field oManager from the standard field Manager and vice-versa... but I need to do one more thing.. if the oManager is null, it should reflect the null value in Manager field also... I tried but that time because of for loop it is not letting me to complete the logic 2.....

APEX TRIGGER
trigger UserTrigger on User (Before Insert, Before Update) {
    
    for(User thisUser : Trigger.New) {
        //Logic 1 -  oManager != null, if oManager is not changed and not equal to manager
        if((thisUser.oManager != null && Trigger.IsInsert) 
        || (Trigger.IsUpdate && thisUser.oManager != null && Trigger.OldMap.get(thisUser.Id).oManager == thisUser.oManager
            && thisUser.oManager != thisUser.Manager)) {
            thisUser.Manager = thisUser.oManager;
        }
//Logic 2
         if(Trigger.IsUpdate && thisUser.Manager != null && Trigger.OldMap.get(thisUser.Id).Manager != thisUser.Manager)) {
            thisUser.oManager = thisUser.Manager;
        }
    }    
}
global class BatchClassSending implements Database.Batchable<sObject>,Database.AllowsCallouts {

    global void execute(Database.BatchableContext BC,List <sObject> scope){
        system.debug('scope>>>>>'+scope);
     list<S_Order__c> approvedO_List = (list<S_Order__c>)scope;
     set<Id> woId_List= new set<Id>();
     
         if(System.Now().minute() > 12 && System.Now().minute() < 15 && !Test.isRunningTest() )
         System.abortJob(bc.getJobId());

     for(S_Order__c oObj:approvedW_List){
        woId_List.add(oObj.Id);
     }
     
     if(!woId_List.isEmpty()){
        P_Sending.sendingODetailOnApprovalofO(woId_List);
     }
    }    
}
APEX CLASS
public class LeadTerritoryManagementController {

    @AuraEnabled
    public static wrapperClass getLeadAssignmentTerritories(){
        wrapperClass returnwrapperClass = new  wrapperClass();
        returnwrapperClass.leadAssignmentSAE = [SELECT Name, Assigned_SAE__r.Name, SAE_Territory_Name__c,Assigned_SAE__c FROM SAE_Assignment_table__c];
        returnwrapperClass.leadAssignmentSDR = [SELECT Name, AE_Territory_Name__c, Assigned_AE__r.Name, Assigned_SDR__r.Name FROM AE_Assignment_table__c];
        return returnwrapperClass;
    }
    // method for fetch User values dynamic
    @AuraEnabled
    public static List<User> searchUser() {
        List<User> activeUsers = [SELECT Id,Name,ProfileId,IsActive FROM User WHERE isActive =true LIMIT 10];
        return activeUsers;
    }
    // method for update records after inline editing
    @AuraEnabled
    public static wrapperClass saveleadAssignmentSDR(string wrapperClassDetail) {
        wrapperClass wrapperClassData= (wrapperClass)System.JSON.deserializeStrict(wrapperClassDetail, wrapperClass.class);
        List<AE_Assignment_table__c> leadAssignmentAEList=new List<AE_Assignment_table__c>();
        leadAssignmentAEList=wrapperClassData.leadAssignmentSDR;
        update leadAssignmentAEList;

        List<SAE_Assignment_table__c> leadAssignmentSAEList=new List<SAE_Assignment_table__c>();
        leadAssignmentSAEList=wrapperClassData.leadAssignmentSAE;
        update leadAssignmentSAEList;

        return wrapperClassData;
    }

    public class wrapperClass{
        @AuraEnabled public List<SAE_Assignment_table__c> leadAssignmentSAE{get;set;}
        @AuraEnabled public List<AE_Assignment_table__c> leadAssignmentSDR{get;set;}
    }
}

TEST CLASS
@isTest
public class LeadTerritoryManagementController_Test {
    
    static testmethod void controllerTest(){
        User usr = [SELECT Id,Name,ProfileId,IsActive FROM User WHERE isActive =true LIMIT 1];
        
        System.runAs(usr){
            Test.startTest();
            List<AE_Assignment_table__c> aeTable = new List<AE_Assignment_table__c>();
            AE_Assignment_table__c AE = new AE_Assignment_table__c();
            AE.AE_Territory_Name__c = 'QWERTY';
            AE.Assigned_AE__c = usr.Id;
            AE.Assigned_SDR__c = usr.Id;
            aeTable.add(AE);
            insert aeTable;
            
            List<SAE_Assignment_table__c> saeTable = new List<SAE_Assignment_table__c>();
            SAE_Assignment_table__c SAE = new SAE_Assignment_table__c();
            SAE.Assigned_SAE__c = usr.Id;
            SAE.SAE_Territory_Name__c = 'ABC';
            saeTable.add(SAE);
            insert saeTable;
            
            LeadTerritoryManagementController.getLeadAssignmentTerritories();
            LeadTerritoryManagementController.searchUser();
            Test.stopTest();
        }        
    }   
}

only 52% code coverage... 3rd method the bold one not covered...

Created one process builder to update the records on user object. This process builder is working whenever any record has been updated on user account. This will update the manager field on user account which is a lookup field whenever a custom field manager 2 will be updated which is also a lookup field. I have referenced the manager field to manager 2 field means if I will update the manager 2 field it will auto update the manager field also on the same user record. But getting error if trying to update the manager field only. It is not letting me to update only manager field...

 

Error is:
Unable to Finish Processing Request
An error has occurred while processing your request. The salesforce.com support team has been notified of the problem. If you believe you have additional information that may be of help in reproducing or correcting the error, please contact support@salesforce.com. Please indicate the URL of the page you were requesting as well as any other related information. We apologize for the inconvenience. 

Thank you again for your patience and assistance. And thanks for using salesforce.com!

APEX CLASS

public with sharing class MultiselectController {
    public SelectOption[] leftOptions { get; set; }
    public SelectOption[] rightOptions { get; set; }

    @TestVisible private void setOptions(SelectOption[] options, String value) {
        system.debug('##--setOptions.options: '+ options);
        system.debug('##--setOptions.value: '+ value);
        options.clear();
        String[] parts = value.split('&');
        for (Integer i=0; i<parts.size()/2; i++) {
            options.add(new SelectOption(EncodingUtil.urlDecode(parts[i*2], 'UTF-8'), 
              EncodingUtil.urlDecode(parts[(i*2)+1], 'UTF-8')));
        }
    }

    public String leftOptionsHidden { get; set {
           leftOptionsHidden = value;
           setOptions(leftOptions, value);
        }
    }

    public String rightOptionsHidden { get; set {
           rightOptionsHidden = value;
           setOptions(rightOptions, value);
        }
    }
}

TEST CLASS
@isTest
public class MultiselectControllerTest {
    
    static testMethod void testOptions(){        
        MultiselectController msc=new MultiselectController();
        SelectOption[] selop = new SelectOption[]{};
        String str='UTF-8';
        msc.setOptions(selop,str);
        selop.clear();
    }
    
    static testMethod void testOptions1(){        
        MultiselectController msc=new MultiselectController();
        List<SelectOption> leftOptions = new List<SelectOption>{};        
        String str1='UTF-8';
        msc.leftOptionsHidden = 'PB';
        msc.setOptions(leftOptions, str1);
    }
    
    static testMethod void testOptions2(){        
        MultiselectController msc=new MultiselectController();
        List<SelectOption> rightOptions = new List<SelectOption>{};        
        String str2='UTF-8';
        msc.rightOptionsHidden = 'Pitney';
        msc.setOptions(rightOptions, str2);
    }
}

getting error: null pointer exception: attempt to de-reference to null object
at bold and italic and underlined line in test class
public class NewClass {

    public static ServicePower.spLogin fetchLoginInfo() {
        ServicePower.spLogin servicePowerLogin = new ServicePower.spLogin();
        String orgId = UserInfo.getOrganizationId().subString(0,15);
        ServicePower_Credentials__c creds = ServicePower_Credentials__c.getValues(orgId);
        String spUser = creds.SpUser__c;
        String dbUser = creds.DBUser__c;
        String dbPassWord = creds.DBPassword__c;
        
        servicePowerLogin.databaseUser = dbUser;
        servicePowerLogin.password = dbPassWord;
        servicePowerLogin.spUser = spUser;
        return servicePowerLogin;
    }        

    public static ServicePower.TimeRequest mapJobChangeFinishTimeRequest(String woName, String finishDateTime) {
        ServicePower.TimeRequest request= new ServicePower.TimeRequest();
        request.login = fetchLoginInfo();
        request.jobId = woName;
        request.finishtime = finishDateTime;
        return request;
    }
        
    public static void SPowerUpdateEndTime(List<S_Order__c> woList){
         Map<String, String> woNameTimeMap = new Map<String, String>();
         List<String> woNameList = new List<String>();
         Datetime woFinishTime;
         for(S_Order__c wo : woList)
            { 
                if (wo.Update_Duration__c != null && wo.Add_Subtract_Minutes__c != null )
                    {
                        woFinishTime = wo.S__Scheduled_Date_Time__c.addSeconds(Integer.valueOf(wo.S__Serv_Duration__c));
                        System.debug('order Current Finish Time: ' + woFinishTime);
                        DateTime newDateTime;
                        List<String> woString;
                        if (wo.Update_Duration__c == 'Add')
                            newDateTime = wo.Scheduled_End__c.addMinutes((Integer)wo.Add_Subtract_Minutes__c);
                        else
                            newDateTime = wo.Scheduled_End__c.addMinutes((Integer)wo.Add_Subtract_Minutes__c * -1);
                        woNameList.add(wo.Name);
                        woNameTimeMap.put(wo.Name, newDateTime.formatgmt('yyyy-MM-dd\'T\'HH:mm'));
                        wo.S__Opti_Status__c = 'OPT_PENDING';
                     }
            }
            
            if (woNameTimeMap.size() > 0)
                updateEndTime(woNameTimeMap, woNameList); 
                
    }
    
    @future(callout=true)
    public static void updateEndTime(Map<String, String> nameTimeMap, List<String> woNameList){
        try{    
            for (String woName: woNameList){
               
                String newDateTime = nameTimeMap.get(woName);
                ServicePower.TimeRequest request = mapJobChangeFinishTimeRequest(woName, newDateTime);
                System.debug('This is the request');
                System.debug(request);
                S_ServicePower_Service2.sp objSP = new S_ServicePower_Service2.sp();
                ServicePower.StandardResponse response= objSP.ChangeJobFinishTime(request);
                System.debug('This is the response ' + response);
                ServicePower.ReturnCode returnCode = response.result;
                S_Order__c wo = [select S__Opti_Status__c, S__Opti_Error__c, Update_Duration__c,  Add_Subtract_Minutes__c  from S_Order__c where name =: woName];
                
                if(S_SP_ErrorCodesMapper.isSuccess(returnCode.code)){
                    wo.S__Opti_Status__c = 'OPT_COMPLETED';
                }else{
                    wo.S__Opti_Status__c = 'OPT_ERROR';
                }
                
                String errorText = 'Return Code:' + returnCode.code + ' | Return Type:' + returnCode.type_x + ' | Return Note:' + returnCode.errNote + ' | Return Msg:' + S_SP_ErrorCodesMapper.getStatusMsg(returnCode.code);
                SM.WSCH_CommonUtils.setOptimizerErrorText(wo, errorText);
                
                wo.Update_Duration__c = null;
                wo.Add_Subtract_Minutes__c = null;
                update wo;
            }
        }catch(Exception e){
           system.debug('Exception occured in updateEndTime() ' + e.getMessage());
        }
    }
}
APEX CLASS

public class Mynewclass{
    static List<St__c> lstSO = new List<St__c>();
    static List<St__c> lstSOnew = new List<St__c>();
    static Map<String,NewItem> fisMap  = new Map<String,NewItem>();
    static Map<String,NewItem> fiMap  = new Map<String,NewItem>();
    
public Static void CreateStObjRec(List<SC__Order__c> SoList){
    List<NewItem> lstNew = new List<NewItem>();
    Map<String,SC__Order__c> woMap  = new Map<String,SC__Order__c>();
    Map<String,St__c> soMap = new Map<String,St__c>();
    integer lstctr =0;
    
    for(SC__Order__c SO : SoList){
        lstctr=lstctr+1;
        system.debug('SO.Send_Trigger_Status__c '+SO.Send_Trigger_Status__c);
        system.debug('SO.SC__Order_Status__c '+SO.SC__Order_Status__c);
        system.debug('SO.SC__Order_Type__c '+SO.SC__Order_Type__c);
        system.debug('SO.Follow_Up__c '+SO.Follow_Up__c);
        system.debug('SO.Pro_Services_Inc__c '+SO.Pro_Services_Inc__c);
        system.debug('SO.Opportunity_ID__c '+SO.Opportunity_ID__c);
        
        if (SO.Send_Trigger_Status__c == 'Not Requested' && SO.SC__Order_Status__c != 'DONE' && SO.SC__Order_Type__c.containsIgnoreCase('install') && SO.Follow_Up__c == false && !String.isBlank(String.valueOf(SO.Pro_Services_Inc__c)) && !String.isBlank(SO.Opportunity_ID__c) && (SO.Opportunity_ID__c.length()==18 || SO.Opportunity_ID__c.length()==15 )){
             system.debug(' system.debug at 29');
             
               if ((!String.isBlank(SO.SC__Country__c)) && (!String.isBlank(String.ValueOf(SM_Route_Settings__c.getValues(SO.SC__Country__c)))) && SM_Route_Settings__c.getValues(SO.SC__Country__c).Valid_for_Proj__c == true){             
                     
                     system.debug(' Inside loop ');
                     SO.Send_Trigger_Status__c = 'Send Requested';
                     
                     NewItem post = new NewItem();
                     post.ParentId = SO.ID;
                     post.Body = 'Staging Object Record added for Wrk '+ SO.Name +' for interfacing to CM' +'\n';
                     post.Body = post.Body + 'CM Send Trigger Status is ' + SO.Send_Trigger_Status__c +'\n';  
                     post.Body = post.Body + 'Order status is ' + SO.SC__Order_Status__c +'\n';  
                     post.Body = post.Body + 'Order Type is ' + SO.SC__Order_Type__c +'\n';
                     post.Body = post.Body + 'Pro Services Inc is ' + SO.Pro_Services_Inc__c +'\n';
                     post.Body = post.Body + 'Opportunity ID is  ' + SO.Opportunity_ID__c +'\n';
                     post.Body = post.Body + 'Country is  ' + SO.SC__Country__c ;
                                 
                     if (!String.isBlank(SO.ID))
                     {
                         lstNew.add(post);
                     }
                     system.debug(' SO DETAILS ============== : '+SO);
                     fiMap.put(SO.OwnerId+lstctr.format(),post);
                     system.debug('fismap details >>>>>>>>'+fiMap);
                     system.debug('SO.name+lstctr.format() === '+SO.OwnerId+lstctr.format());
                     
                     St__c SO = new St__c();
                     SO.RecordTypeId = getRecordType('Wrk');
                     SO.Opportunity_ID__c = SO.Opportunity_ID__c;
                     SO.Order_ID__c = SO.ID;
                     SO.Order_Number__c = SO.ID;
                     lstSO.add(SO);
                                          
                     soMap.put(wo.OwnerId+lstctr.format(),SO);
                     woMap.put(wo.OwnerId+lstctr.format(),SO);            
             }
               else if ((String.isBlank(SO.SC__Country__c)) || (String.isBlank(String.ValueOf(SM_Route_Settings__c.getValues(SO.SC__Country__c)))) || SM_Route_Settings__c.getValues(SO.SC__Country__c).Valid_for_Proj__c == false){             
                     system.debug('Inside not meet criteria at 73===========================');
                     SO.Send_Trigger_Status__c = 'Does Not Meet Criteria';
                     
                     NewItem post = new NewItem();
                     post.ParentId = SO.ID;
                     post.Body = 'Wrk '+ SO.Name +' does not meet criteria for interfacing to CM'+'\n';
                     post.Body = post.Body + 'CM Send Trigger Status is ' + SO.Send_Trigger_Status__c +'\n';  
                     post.Body = post.Body + 'Order status is ' + SO.SC__Order_Status__c +'\n';  
                     post.Body = post.Body + 'Order Type is ' + SO.SC__Order_Type__c +'\n';
                     post.Body = post.Body + 'Pro Services Inc is ' + SO.Pro_Services_Inc__c +'\n';
                     post.Body = post.Body + 'Opportunity ID is  ' + SO.Opportunity_ID__c +'\n';
                     post.Body = post.Body + 'Country is  ' + SO.SC__Country__c;
            
                     if (!String.isBlank(SO.ID))
                     {
                         lstNew.add(post);
                     }
                     fiMap.put(wo.OwnerId+lstctr.format(),post);  
                 }        
        }  
        
    if (!lstNew.isEmpty()){
        upsert lstNew;   
    }
       
    if (!soMap.isEmpty()){
            Insert soMap.values();
        }
        system.debug('soMap Values : '+ soMap);
        system.debug('fiMap Values == : '+ fiMap);
        for(String mapKey: soMap.keySet()){
            SC__Order__c temp = SOMap.get(mapKey);
            St__c sso = soMap.get(mapKey);
            temp.Obj_Name__c = sso.ID;
            SOMap.put(mapkey,temp);
            NewItem fi = fiMap.get(mapKey);
            if (fi != null){
                system.debug('New Item '+fi);
                system.debug('sso.id == '+ sso.id);
                if (!String.isBlank(sso.id)){
                      if (String.isBlank(fi.Parentid)){
                        system.debug('debug at 191 line ==');
                        fi.Parentid = sso.id;
                        fisMap.put(sso.id,fi);
                    }
                }
            }
        }        
        system.debug('fisMap values ================'+fisMap.values());    
   } 
}
TRIGGER
trigger Count_Activities on Event (after insert, after delete, after update) {
    Map<Id,Opportunity> oppMap = new Map<Id,Opportunity>();
    if(trigger.isUpdate){        
            for(Event e:Trigger.new){
                objEventSet.add(e.whatId);

            }            
    }
  
    if(trigger.isInsert || trigger.isUndelete){        
            for(Event e:Trigger.new){
                objEventSet.add(e.whatId);
            }
    }

    if(trigger.isDelete){
        for(Event e:Trigger.old){
            objEventSet.add(e.whatId);

        }
    }    
    
    Map<Id,Opportunity> objOpp=new Map<Id,Opportunity>([Select Id,IsClosed,Activity_Due_Date__c from Opportunity where Id In :objEventSet]);

    if(trigger.isInsert || trigger.isUndelete){
        for(Event e:Trigger.new){          
            if(objOpp.containsKey(e.WhatId)){                
                if(e.ActivityDateTime >= System.now()){
                    if(oppMap.containsKey(e.WhatId)){
                         if(e.ActivityDateTime != null && (oppMap.get(e.WhatId)).Activity_Due_Date__c != null && (oppMap.get(e.WhatId)).Activity_Due_Date__c < e.ActivityDateTime){
                            (oppMap.get(e.WhatId)).Activity_Due_Date__c = e.ActivityDateTime;
                        } else if (e.ActivityDateTime != null && (oppMap.get(e.WhatId)).Activity_Due_Date__c == null){
                            (oppMap.get(e.WhatId)).Activity_Due_Date__c = e.ActivityDateTime;
                        }
                    }
                    else{
                         if(e.ActivityDateTime != null && (objOpp.get(e.WhatId)).Activity_Due_Date__c != null && (objOpp.get(e.WhatId)).Activity_Due_Date__c < e.ActivityDateTime){
                            (objOpp.get(e.WhatId)).Activity_Due_Date__c = e.ActivityDateTime;
                        } else if (e.ActivityDateTime != null && (objOpp.get(e.WhatId)).Activity_Due_Date__c == null){
                            (objOpp.get(e.WhatId)).Activity_Due_Date__c = e.ActivityDateTime;
                        }
                        if(objOpp.get(e.whatId).IsClosed==false){
                            oppMap.put(e.WhatId,objOpp.get(e.whatId));

                        }
                    }
                }
            }
        }
    }   

    if(trigger.isDelete){
        Map<Id,DateTime> opportunityByLatestDueDateMap = new Map<Id,DateTime>();
        List<Event> eventList = [Select Id, ActivityDateTime,WhatId from Event where whatId =: objOpp.Keyset() AND Id NOT IN : objEventSet limit 50000];
        for(Event et : eventList){
            if(opportunityByLatestDueDateMap.containsKey(et.WhatId)){
                if(opportunityByLatestDueDateMap.get(et.WhatId) < et.ActivityDateTime){
                    opportunityByLatestDueDateMap.put(et.WhatId,et.ActivityDateTime);
                }
            } else {
                opportunityByLatestDueDateMap.put(et.WhatId,et.ActivityDateTime);
            }
        }
        for(Event e:Trigger.old){
            if(objOpp.containsKey(e.WhatId)){
                if(e.ActivityDateTime >= System.now()){
                    if(oppMap.containsKey(e.WhatId)){
                        (oppMap.get(e.WhatId)).Activity_Due_Date__c = opportunityByLatestDueDateMap.get(e.WhatId);
                    }
                    else{
                        (objOpp.get(e.WhatId)).Activity_Due_Date__c = opportunityByLatestDueDateMap.get(e.WhatId);
                        if(objOpp.get(e.whatId).IsClosed==false){
                            oppMap.put(e.WhatId,objOpp.get(e.whatId));

                        }
                    }
                }
            }
         }
     }

    if(trigger.isUpdate){
        for(Event e:Trigger.new){
            if(objOpp.containsKey(e.WhatId)&& Trigger.oldMap.containsKey(e.Id)){
                    if(oppMap.containsKey(e.WhatId)){
                        if(e.ActivityDateTime != null && (oppMap.get(e.WhatId)).Activity_Due_Date__c != null && (oppMap.get(e.WhatId)).Activity_Due_Date__c < e.ActivityDateTime){
                            (oppMap.get(e.WhatId)).Activity_Due_Date__c = e.ActivityDateTime;
                        } else if (e.ActivityDateTime != null && (oppMap.get(e.WhatId)).Activity_Due_Date__c == null){
                            (oppMap.get(e.WhatId)).Activity_Due_Date__c = e.ActivityDateTime;
                        }
                    }
                    else{
                        if(e.ActivityDateTime != null && (objOpp.get(e.WhatId)).Activity_Due_Date__c != null && (objOpp.get(e.WhatId)).Activity_Due_Date__c < e.ActivityDateTime){
                            (objOpp.get(e.WhatId)).Activity_Due_Date__c = e.ActivityDateTime;
                        } else if (e.ActivityDateTime != null && (objOpp.get(e.WhatId)).Activity_Due_Date__c == null){
                            (objOpp.get(e.WhatId)).Activity_Due_Date__c = e.ActivityDate;
                        }
                        if(objOpp.get(e.whatId).IsClosed==false){
                            oppMap.put(e.WhatId,objOpp.get(e.whatId));

                        }
                    }                
            }
        }    
    }
    if(!oppMap.isEmpty()){
        Database.SaveResult[] oppListstatus = Database.update(oppMap.values(), false);
        for(Database.SaveResult sr : oppListstatus) {
            for(Database.Error err : sr.getErrors()) {
                if(!sr.isSuccess()){
                    trigger.new[0].addError(err.getMessage());

                }
            }
        }
    }
}
TEST CLASS
@isTest
private class Count_ActivitiesTest{
     Static List<Event> lst = new List <Event>();    
     private static void data(){
        PI_Role__c pi = new PI_Role__c();
           pi.name='18';
           pi.Business_Unit__c='ABC';
           pi.Primary__c=true;
           pi.Role__c= 'AB Opp Queue';
           insert pi;
    }    
     private static void setupdata(){
        String canString  = Math.round(Math.random()*Math.pow(10, 7))+''+ Math.round(Math.random()*Math.pow(10, 4))+'';
        Account acc=new Account(Name='Accenture'+ canString.substring(0,4), SAP_Account__c = 'Test XYZ ACCOUNT');
        Database.insert(acc,true);
        
        OpportunityRecordTypeInfo__c recTypeInfo =New  OpportunityRecordTypeInfo__c();
        recTypeInfo.Name='PBBI Opportunity';
        recTypeInfo.Id__c= '01280000000AaAC';
        Database.insert(recTypeInfo,false);        
        Id recTypeId = recTypeInfo.Id__c;
        Date myDate = System.Today()+30;
        
        Opportunity opt = new Opportunity(Name = 'Test Opportunity 551', AccountId = acc.id, Type = 'Existing - Compliance', CloseDate = myDate,ForecastCategoryName = 'Pipeline', StageName = '2. Identify', Amount=12345, RecordTypeId = recTypeId ,Count_Activities__c=1 ,Vertical__c='Communications');
        Database.insert(opt,false);
        
        Opportunity opt1 = new Opportunity(Name = 'Test Opportunity 551', AccountId = acc.id, Type = 'Existing - Compliance', CloseDate = myDate,ForecastCategoryName = 'Pipeline', StageName = '2. Identify', Amount=12345, RecordTypeId = recTypeId ,Count_Activities__c=NULL ,Vertical__c='Communications');
        Database.insert(opt1,false);
        Event e = new Event(WhatId = opt.id, DurationInMinutes = 30, ActivityDateTime = system.now()+1, ActivityDate = System.Today() + 1);
        lst.add(e);
        Event f = new Event(WhatId = opt1.id, DurationInMinutes = 30, ActivityDateTime = system.now()+1, ActivityDate = System.Today() + 1);
        lst.add(f);
        Database.insert(lst,false);
        CustomSettingCreation.CreateCustomSettingData();
     }
     static testMethod void myTestMethod(){       
        data();
        setupdata();
        Test.startTest();
        system.assertEquals(2,lst.size());
        Test.stopTest(); 
     }
}

the bold, italic and underlined part not able to cover .. please help me
APEX CLASS

public class ImplementationTabAccount {
    
    @AuraEnabled
    public static List<Implementation__c> checkingImplementation(Id account) {
        
        List<Opportunity> oppList = new List<Opportunity>();
        oppList = [Select Id, Name from Opportunity where opportunity.AccountId =:account];
        System.debug('Opportunitiessss'+oppList);
        
        Set<Id> oppIds = new Set<Id>();
        if(oppList.size()>0){
            
            for (Opportunity op : oppList) {  
                oppIds.add(op.Id);
            }
        }
        System.debug('oppIds' + oppIds);
        
        List<Implementation__c> impList = new List<Implementation__c>();
        impList = [Select Id,Name,Account_Name__c, Implementation_Stage__c,Opportunity_Name__c FROM Implementation__c where Implementation__c.Opportunity_Name__c=:oppIds];
        System.debug('implist'+impList);
        return impList;
    }
}

TEST CLASS

@isTest
public class ImplementationTabAccountTest {
    static testmethod void test(){
        Account acc= new Account(Name = 'ABC', RecordTypeId = Schema.SObjectType.Account.getRecordTypeInfosByName().get('Prospect').getRecordTypeId());
        insert acc;
        
        Opportunity opp = new Opportunity(Name = 'Test', Id = acc.Id);
        insert opp;
        
        Implementation__c impliment = new Implementation__c(Id = opp.Id);
        insert impliment;       
    }    
}
{!REQUIRESCRIPT("/soap/ajax/13.0/connection.js")}
{!requireScript("/soap/ajax/30.0/apex.js")}
var oppObj = new sforce.SObject("Opportunity");
oppObj.Id = '{!Opportunity.Id}'; 
var result = sforce.connection.update([oppObj]);
if (result[0].success=='false') {
alert(result[0].errors.message);
}
else {
sforce.apex.execute('ApexClass', 'methodName', {optyId:'{!Opportunity.Id}', action:'Default'});
alert('{!$Label.Success}');
}
}
document.location = '/{!Opportunity.Id}';

I've simply addeed the entire code to vf page, standardcontroller as Opportunity.
I need to use CSS as well so that the error msg can be displayed in left top instead of the alert box which displayed at the center on top.

Please help ASAP.
I'm trying to write the below piece of code and calling it in after update context on opportunity.
I want to send email to the reciepient once the opportunity updated to stage 5 and product code on related opportunity product is STD.
I've created the email template as well and using the email tmplate id in the code but I'm not getting any email notification. Can anyone please help me out to correct the code?
public static void emailAlert(list<Opportunity> newOpportunityList, Map<Id,Opportunity> oldOpportunityMap){
        Set<id> OpptyId = new Set<id>();
        List<OpportunityLineItem> lstOptyLineItem = new List<OpportunityLineItem>();
        for(Opportunity ObjOppty: newOpportunityList){
            if(oldOpportunityMap.get(ObjOppty.Id).StageName != ObjOppty.StageName && ObjOppty.StageName == 'Won'){
                OpptyId.add(ObjOppty.id);
            }
        }
        if(OpptyId.size() > 0){
          lstOptyLineItem = [Select id,Name,ProductCode from OpportunityLineItem where OpportunityId IN: OpptyId AND ProductCode = 'STD';    
        }
        
        if(lstOptyLineItem.size() > 0){
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            List<String> sendTo = new List<String>{'cgupta@gmail.com'};
            mail.setTemplateId('00X02000000A34cEAC');
            mail.setToAddresses(sendTo);
            //system.debug('to address'+ mail.setToAddresses);
            mail.setOrgWideEmailAddressId(System.Label.Support_Email_Address);
            //system.debug('org address'+ mail.setOrgWideEmailAddressId);
           // mail.setTargetObjectId(primaryContact);
            List<Messaging.SingleEmailMessage> allmsg = new List<Messaging.SingleEmailMessage>();
            allmsg.add(mail);
            system.debug('mail sent'+mail);
            try {
                Messaging.sendEmail(allmsg,false);
                return;
            } catch (Exception e) {
                System.debug(e.getMessage());
            }
        }
    }

Please help me here to correct the above code.
Here is the Scenario:
We're having Email-to-Case functionality. Whenever a new Email received on case the case field Status Alert should get updated with value "Received" and when replied to that email same field should get blank.

Can anyone please help me out with this trigger?
 
trigger emailMessageTrigger on EmailMessage (before insert, before update) {
    Set<Id> caseIdSet = new Set<Id>();
    list<Case> casList = new list<Case>();
    
    for(EmailMessage email: Trigger.new){
        caseIdSet.add(email.ParentId);
    }
    
    if(caseIdSet != null && caseIdSet.size() > 0){
        casList = [Select Id, Status, Status_Alert__c from Case where Id IN: caseIdSet AND Status != 'New' AND Status_Alert__c	!= 'New Email Received'];
    }
    
    for(EmailMessage newEmail: Trigger.new){
        if(casList.size() > 0){
            for(Case cas: casList){
                cas.Status_Alert__c	 = 'New Email Received';
                update cas;
            }
        }
    }
}

 
Hello all,
Most of my Class has coverage except for the following.
This is part of a Class that parses a Multiselect and puts each value on its own line.  
I know that actComments != null but I do not know how to get the following to have coverage.
Any help is appreciated.
P
actComments = actComments.removeEnd('\n'); // Removing the last line breaker
    tc.Comment__c = actComments;
    comToUpdate.add(tc);

 
How to update no child count(Field) in parent account detail page its follow account hierarchy up to three levels using Trigger.

trigger NumberOfChieldCount on Account (after Insert, after Update, after delete) {
    Set<id> ids= new Set<id>();
    List<Account> acclist = new List<Account>();
    integer count = 0;
   if(Trigger.isInsert || Trigger.isUpdate){
        for(Account acc: Trigger.new){
            if(acc.ParentId!=null)
                ids.add(acc.ParentId);
            acclist.add(acc);
        }
    }
    
    if(Trigger.isDelete){
        for(Account acc: Trigger.old){
            if(acc.ParentId!=null)
                ids.add(acc.ParentId);
            acclist.add(acc);
        }
    }   
    if(ids.size()>0){
        List<Account> accchild = new List<Account>([select id,Parentid from Account where Parentid IN: ids]);
        List<Account> accparent = new List<Account>([select id,Nubmer_of_Chields__c from Account where id IN: ids]);
        /*integer nochilds=[select count() from Account where Parentid in :ids];
        system.debug('nochilds::::::::'+nochilds);
        integer noofchilds=[select count() from Account where id in :ids];
        system.debug('noofchilds::::::::'+noofchilds);
        system.debug('accchild 27-->'+accchild);
        system.debug('accparent 28-->'+accparent);
        integer noof;
        integer nofchids;
        integer nc;*/
        for(Account ac: accparent){
            count =0;
            for(Account acchilds: accchild){
                /*if(acchilds.Nubmer_of_Chields__c!=null && ac.Nubmer_of_Chields__c!=null)
                    nofchids=integer.valueof(acchilds.Nubmer_of_Chields__c)+integer.valueof(ac.Nubmer_of_Chields__c);
                if(acchilds.Nubmer_of_Chields__c!=null && ac.Nubmer_of_Chields__c==null)
                    nofchids=integer.valueof(acchilds.Nubmer_of_Chields__c);   
                
                system.debug('noof:::: 36'+nofchids );*/
                if(acchilds.Parentid == ac.id)
                    count++;
                   else
                    count--;
            }
            //ac.Nubmer_of_Chields__c =string.valueof(count); 
            /*system.debug('ac.Nubmer_of_Chields__c::::::::'+ac.Nubmer_of_Chields__c);
            system.debug('count:::: 47'+count);
            system.debug('count:::: 47'+nofchids);*/
            //if(count>0 && nofchids!=null)
                //ac.Nubmer_of_Chields__c =string.valueof(count+nofchids); 
            //if(count>0 && nofchids==null) 
               //if(ac.Parentid == ac.id)
                ac.Nubmer_of_Chields__c =string.valueof(count);
               
                    
            /*else
                ac.Nubmer_of_Chields__c =string.valueof(count);  */         

        }
        
        try{
            upsert accparent;
        }catch(DMLException ex){
            System.debug('Exception is '+ex);
        }
    }
}
Note:Create  new field Nubmer_of_Chields__c in Account(Object).

A-->No of child are 2+1 =3
   B--->2
      c---->1
 
I am new to coding in general and to Apex in particular so any help I can get is greatly appreciated.

I am building a trigger that will create a new custom object record from an opportunity.

I plan to use process builder to fire the trigger when a particular opp type is created or when a particular field in that opp is updated.

I want the new record to be related to the Opp so i want to pull the Opp ID and some of the fields into the trigger to use in the new record.

How do i pull that specific data in?

Like I said, I am new at this but willing to work and learn.

Best regards,
Steve
 
public inherited sharing class LWCExampleController {
    @AuraEnabled(Cacheable = true)
    public static list<Account> fetchAccounts(String strObjectName) {
        if(String.isNotBlank(strObjectName)) {
            return Database.query('SELECT Id, Name, Industry From ' + strObjectName + ' limit 10');
        }
        else {
            return null;
        }
    }
}
Hello!  I updated a Time Based Workflow that's working perfectly in Sandbox, but now won't deploy due to errors on the tests:

User-added image
Do I have to somehow update these tests in order for them to pass?

Thanks!

Mike

trigger RG_OpportunityTgr on Opportunity (after insert, before update) {
     if(Trigger.isInsert){
        Map<Id, Opportunity> oppMap=new Map<Id, Opportunity>();
        RG_OpportunityTgrCls.OpportunityAssignUpdateCount(Trigger.new, oppMap, TRUE, FALSE);
    }
    
    IF(Trigger.IsUpdate){
        RG_OpportunityTgrCls.OpportunityAssignUpdateCount(Trigger.new, Trigger.oldMap, false, TRUE);
        Id userProfileId = userinfo.getProfileId();
        Id currentUserId = UserInfo.getUserId();
        String userProfileName = [SELECT ID, Name from Profile Where Id = : userProfileId].Name;
        if( (userProfileName != 'System Administrator' && currentUserId != System.Label.Natalie_userId
            && currentUserId != System.Label.Barry_Fitts_UserId)){
            RG_OpportunityTgrCls.OwnerReasonCheck(Trigger.new, Trigger.oldMap);
            }
    }
}


APex: class

public class RG_OpportunityTgrCls {
    
    public static void OpportunityAssignUpdateCount(List<Opportunity> oppList, Map<Id, Opportunity> oldOppMap, boolean isInsert, boolean IsUpdate){
        
        Map<Id,Integer> userIdTocountMap = new Map<Id, integer>();
        Map<Id, Integer> userIdToCountMinusMap= new Map<Id, Integer>();
        
        Map<Id,Boolean> usedIdToPlusMinusMap = new Map<Id, Boolean>();
        
        for(Opportunity opp: OppList){
            if(opp.LeadSource != 'SOI' && opp.T2T_Agent__c == Null){
                
                
                Integer count = 1;
                IF(isInsert){
                    
                    //      IF(userIdTocountMap.containsKey(opp.OwnerId)){
                    //        count+=userIdTocountMap.get(opp.OwnerId);
                    //      userIdTocountMap.put(opp.OwnerId, count);
                    //}ELSE
                    userIdTocountMap.put(opp.OwnerId, count);
                    
                    usedIdToPlusMinusMap.put(opp.OwnerId,True);
                }
                if(IsUpdate && oldOppMap.GET(opp.Id)!=NULL && opp.OwnerId!=oldOppMap.GET(opp.Id).OwnerId){
                    //new user to add count
                    opp.Pullback_Campaign__c = System.today();
                    if(userIdTocountMap.containsKey(opp.OwnerId)){
                        
                        count+=userIdTocountMap.get(opp.OwnerId);
                        userIdTocountMap.put(opp.OwnerId, count);
                        usedIdToPlusMinusMap.put(opp.OwnerId,True);
                    }else{
                        
                        userIdTocountMap.put(opp.OwnerId, count);
                        
                        usedIdToPlusMinusMap.put(opp.OwnerId,True);
                        
                    }
                    //previous user to minus count
                    if(userIdTocountMap.containsKey(oldOppMap.GET(opp.Id).OwnerId)){
                        
                        count+=userIdTocountMap.get(oldOppMap.GET(opp.Id).OwnerId);
                        userIdTocountMap.put(oldOppMap.GET(opp.Id).OwnerId, count);
                        
                        usedIdToPlusMinusMap.put(oldOppMap.GET(opp.Id).OwnerId, FALSE);
                    }else{
                        
                        userIdTocountMap.put(oldOppMap.GET(opp.Id).OwnerId, count);
                        
                        usedIdToPlusMinusMap.put(oldOppMap.GET(opp.Id).OwnerId, FALSE);
                    }
                    
                    
                }
                
                system.debug('userIdTocountMap+32'+userIdTocountMap);
            }
            
            System.debug('userIdTocountMap==>'+userIdTocountMap);
            
            List<User> updateUserList = new List<User>();
            IF(userIdTocountMap.size()>0){
                for(User u : [SELECT Id,LeadAssignCount__c,Daily_Lead__c FROM User WHERE Id in : userIdTocountMap.keySet()]){
                    decimal leadAssignCountt=0;
                    decimal dailylead=0;
                    IF(usedIdToPlusMinusMap.get(u.Id)!=NULL && usedIdToPlusMinusMap.get(u.Id) && userIdTocountMap.GET(U.ID)!=NULL){
                        leadAssignCountt= ( u.LeadAssignCount__c!=NULL?u.LeadAssignCount__c:0 ) + userIdTocountMap.GET(U.ID);
                        dailylead= ( u.Daily_Lead__c!=NULL?u.Daily_Lead__c:0 ) + userIdTocountMap.GET(U.ID);
                    }
                    else IF(usedIdToPlusMinusMap.get(u.Id)!=NULL && !usedIdToPlusMinusMap.get(u.Id) && userIdTocountMap.GET(U.ID)!=NULL){
                        leadAssignCountt= ( u.LeadAssignCount__c!=NULL?u.LeadAssignCount__c:0 ) - userIdTocountMap.GET(U.ID);
                        dailylead= ( u.Daily_Lead__c!=NULL?u.Daily_Lead__c:0 ) - userIdTocountMap.GET(U.ID);
                    }
                    
                    
                    updateUserList.add(new User(Id=u.Id, LeadAssignCount__c =leadAssignCountt<0?0:leadAssignCountt, Daily_Lead__c =dailylead<0?0:dailylead));
                }
                
                system.debug('updateUserList==>'+updateUserList);
                IF(!updateUserList.isEmpty())  
                    UPDATE updateUserList;
            }
        }
    }
    public static void OwnerReasonCheck(List<Opportunity> oppList, Map<Id, Opportunity> oldOppMap){
        
        Set<Id> oppIds = new Set<Id>();
        set<Id> UserIds = new set<Id>();
        List<Ownership_Assignment__c> ownAssList = new List<Ownership_Assignment__c>();
        List<User> userlist = new List<user>();
        List<User> userexemptlist = new List<user>();
        set<ID> userexempt = new set<id>();
        userexemptlist = [Select Id,profileid  from User where ID =:userinfo.getuserid()]; 
        
        
        
        for(user u:userexemptlist){
            
            if(u.id != System.Label.Barry_Fitts_UserId && u.id != System.Label.Natalie_userId ){
                userexempt.add(u.id);
            }
        }
        if(userexempt.size()>0){
            for(Opportunity opp: OppList){
                if(opp.OwnerId!=oldOppMap.get(opp.Id).OwnerId ){
                    oppIds.add(opp.Id);
                    userIds.add(opp.ownerid);
                }
                
            }
            ownAssList = [Select Id from Ownership_Assignment__c where Appointment_Name__c IN :oppIds];
            userlist = [Select Id,In_Out__c,LRT_qualifications__c  from User where ID IN :userIds];
            
            
            for(Opportunity opp: OppList){
                for(user us:userlist){
                    if (ownAssList.isempty()&&opp.OwnerId!=oldOppMap.get(opp.Id).OwnerId
                        && !URL.getCurrentRequestUrl().getQuery().contains('IFrameOrigin') && us.In_Out__c == TRUE && 
                        opp.Service_Request__c == null ){
                            opp.addError(System.Label.LRT_Validation);  
                        }
                    else  if (ownAssList.isempty()&&opp.LRT_Reason__c==null&&opp.OwnerId!=oldOppMap.get(opp.Id).OwnerId 
                              && !URL.getCurrentRequestUrl().getQuery().contains('IFrameOrigin') &&
                              opp.Service_Request__c == null){
                                  opp.addError(System.Label.LRT_Reason);  
                              }
                    if(!String.isBlank(us.LRT_Qualifications__c)){
                        List<String> pickValues = us.LRT_Qualifications__c.split(';');
                        String pickValuesStr ='' ;
                        for(String str : pickValues){
                            pickValuesStr = pickValuesStr + '\n' + str;
                        }
                        if(opp.LRT_Reason__c==null&&opp.OwnerId!=oldOppMap.get(opp.Id).OwnerId 
                           && !URL.getCurrentRequestUrl().getQuery().contains('IFrameOrigin') &&(!pickValuesStr.contains(opp.Consultation_Type__c))
                           && opp.Service_Request__c == null){
                               opp.addError('This agent does not serve that consultation type.');  
                           }
                    }
                    else{
                        opp.adderror('This Agent has no approved consultation types at this time.');
                        //return; 
                    }
                    
                }
            }
        }            
    }
}

Apex test class:

@isTest
public without sharing class RG_OpportunityTgrCls_Test {
    static testMethod void oppTriggerTestMethod(){
        Profile p = [Select id from profile where name = 'Listing Agent (Full License)'];
        ActionPlansTestUtilities ge = new ActionPlansTestUtilities();
        User u = ge.createTestUser(p);
        system.runAs(u){
            Id RecordTypeIdContact = Schema.SObjectType.Service_Request__c.getRecordTypeInfosByName().get('SOI').getRecordTypeId();        
            Service_Request__c  srq = new Service_Request__c ();
            srq.RecordTypeId = RecordTypeIdContact;
            srq.First_Name__c = 'srqtest';
            srq.Last_Name__c = 'lasttest';
            srq.Lead_Type__c = 'Buyer';
            srq.Market_Area__c = 'Atlanta';
            srq.Primary_Email__c = 'testsrq@test.com';
            srq.Primary_Phone__c = '3456789';
            insert srq;
            Opportunity op = new Opportunity();
            op.Name ='Op1';
            op.StageName = 'Won';
            op.StageName = 'Won';
            op.Service_Request__c =srq.id;
            op.Conversion_Type__c = 'Inbound';
            op.Consultation_Type__c = 'Phone Consultation';
            op.Conversion_Type__c = 'Inbound';
            op.CloseDate = Date.today();
            op.GoogleDrive_Link__c = 'test.test.com';
            op.OwnerId = u.Id;
            insert op;
            Ownership_Assignment__c oa = new Ownership_Assignment__c();
            oa.Appointment_Name__c = op.Id;
            insert oa;
            Test.startTest();
            
            DateTime dT = System.now();
            Date myDate = date.newinstance(dT.year(), dT.month(), dT.day());
            op.Appointment_time__c = Time.newInstance(18, 0, 0, 0);
            op.Market_Area__c = 'Athens';
            op.LeadSource ='Billboard';
            op.Description ='test test';
            op.LRT_Reason__c='test reason';
            Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
            op.ISA_Agent__c =UserInfo.getUserId();
            op.CloseDate = myDate;
            op.Type ='Buyer';
            op.OwnerId=UserInfo.getUserId();
            update op;
            Test.stopTest();
            
            system.assertEquals(u.Id, op.OwnerId);
        }
    }
    static testMethod void oppTriggerTestMethod2(){
        Profile p = [Select id from profile where name = 'System Administrator'];
        
        User u2 = new User(Alias = 'newUser', Email='newuser@testorg.com',
                           EmailEncodingKey='UTF-8', LastName='Test11ing', LanguageLocaleKey='en_US',
                           LocaleSidKey='en_US', ProfileId = p.Id,
                           TimeZoneSidKey='America/Los_Angeles', UserName='ne11wuser@testorg.com', LRT_qualifications__c ='Phone Consultation');
        Opportunity op = new Opportunity();
        op.Name ='Op1';
        op.StageName = 'Won';
        op.StageName = 'Won';
        op.Conversion_Type__c = 'Inbound';
        op.Consultation_Type__c = 'Phone Consultation';
        op.Conversion_Type__c = 'Inbound';
        op.CloseDate = Date.today();
        op.GoogleDrive_Link__c = 'test.test.com';
        op.OwnerId = UserInfo.getUserId();
        DateTime dT = System.now();
        Date myDate = date.newinstance(dT.year(), dT.month(), dT.day());
        insert op;
        
        Ownership_Assignment__c oa = new Ownership_Assignment__c();
        oa.Appointment_Name__c = op.Id;
        insert oa;
        
        
        User us = new User(Alias = 'standt', Email='standarduser@testorg.com', 
                           EmailEncodingKey='UTF-8', LastName='Test12ing', LanguageLocaleKey='en_US', 
                           LocaleSidKey='en_US', ProfileId = p.Id, 
                           TimeZoneSidKey='America/Los_Angeles', UserName='systaduser@testorg.com', LRT_qualifications__c ='Phone Consultation');
        insert us;
        System.runAs(u2) {
            Test.startTest();
            op.Type ='Buyer';
            op.Appointment_time__c = Time.newInstance(18, 0, 0, 0);
            op.Market_Area__c = 'Athens';
            op.LeadSource ='Billboard';
            
            op.Description ='test test';
            op.LRT_Reason__c='test reason';
            Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
            op.ISA_Agent__c =UserInfo.getUserId();
            op.CloseDate = myDate;
            op.ownerid = us.id;
            update op;
            us.LeadAssignCount__c = 2;
            update us;
            Test.stopTest();
        }
    }
    static testMethod void oppTriggerTestMethod3(){
        Profile p = [Select id from profile where name = 'Lead Coordinator'];
        
        User u2 = new User(Alias = 'newUser', Email='newuser@testorg.com',
                           EmailEncodingKey='UTF-8', LastName='Test11ing', LanguageLocaleKey='en_US',
                           LocaleSidKey='en_US', ProfileId = p.Id,
                           TimeZoneSidKey='America/Los_Angeles', UserName='ne11wuser@testorg.com', LRT_qualifications__c ='Phone Consultation');
        Opportunity op = new Opportunity();
        op.Name ='Op1';
        op.StageName = 'Won';
        op.StageName = 'Won';
        op.Conversion_Type__c = 'Inbound';
        op.Consultation_Type__c = 'Phone Consultation';
        op.Conversion_Type__c = 'Inbound';
        op.CloseDate = Date.today();
        op.GoogleDrive_Link__c = 'test.test.com';
        op.OwnerId = UserInfo.getUserId();
        DateTime dT = System.now();
        Date myDate = date.newinstance(dT.year(), dT.month(), dT.day());
        insert op;
        
        User us = new User(Alias = 'standt', Email='standarduser@testorg.com', 
                           EmailEncodingKey='UTF-8', LastName='Test12ing', LanguageLocaleKey='en_US', 
                           LocaleSidKey='en_US', ProfileId = p.Id, 
                           TimeZoneSidKey='America/Los_Angeles', UserName='systaduser@testorg.com', LRT_qualifications__c ='Phone Consultation',In_Out__c = True);
        insert us;
        
        
        System.runAs(u2) {
            Test.startTest();
            ApexPages.StandardController opportunity;
            ApexPages.currentPage().getParameters().put('id',op.id);
            
            op.Type ='Buyer';
            op.Appointment_time__c = Time.newInstance(18, 0, 0, 0);
            op.Market_Area__c = 'Athens';
            op.LeadSource ='Billboard';
            op.Description ='test test';
            Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
            op.ISA_Agent__c =UserInfo.getUserId();
            op.CloseDate = myDate;
            op.ownerid = us.id;
            update op;
            us.LeadAssignCount__c = 2;
            update us;
            Test.stopTest();
        }
    }
    
    }

This is my Class
-------------------
trigger trgStudentSchoolFields on Student_School_Fields__c (after insert, after update){
    String IntegrationUser = System.Label.IntegrationUser;
    map<string,string> mapContacts = new map<string,string>();
    list<Contact> listOfContact = new list<Contact>();
    list<Inquiry__c> inquiryList = new list<Inquiry__c>();
    list<Opportunity> oppList = new list<Opportunity>();
    String uid = userinfo.getUserId();
    String IntgUser;
    system.debug('USERID>>>' + uid);
    system.debug('IntegrationUser>>>' + IntegrationUser);
    list<Contact_Method__c> cmlist=new list<Contact_Method__c>();
    Set<string> stdscmid = New Set<string>();
    List<Error__c> errconlst = New List<Error__c>();
    List<Error__c> errlst = New List<Error__c>();  
   // if (!uid.contains(IntegrationUser))
   // {
    if(userinfo.getUserId() != '00555000003neB6'){
        list<Student_School_Fields__c> lstSchStud=new list<Student_School_Fields__c>();
        for(Student_School_Fields__c schstudobj:trigger.new)
        {
            stdscmid.add(schstudobj.id);
            lstSchStud.add(schstudobj);
            mapContacts.put(schstudobj.Contact__c, schstudobj.Student_Enrollment_Campus__c);
        }
        errconlst = [select ErrorCode__c, Error_Message__c, Error_Type__c, ObjectType__c, Status__c,
                     ContactRelated__c, OpportunityRelated__c, APIOperation__c
                     From Error__c 
                     Where Error_Type__c = 'Data' 
                     AND Status__c = 'Failed' 
                     AND ObjectType__c = 'StudentSchoolFields'
                     AND StudentSchoolFieldRelated__c IN :stdscmid];
        for (Error__c errobj:errconlst)
        {
            errobj.Status__c = 'Processed';
            errlst.add(errobj);
        }
        if (errlst.size() > 0)
            update errlst;
        
        if(mapContacts.size()>0 && !mapContacts.isEmpty()){
            for(Contact con : [SELECT Id, Student_Enrollment_Campus__c FROM Contact
                               where  id IN:mapContacts.keySet()]){
                                   string enrollment = mapContacts.get(con.id);
                                   System.debug('con'+con);
                                   System.debug('enrollment'+enrollment);
                                   if(enrollment != null){
                                       con.Student_Enrollment_Campus__c = enrollment; 
                                       listOfContact.add(con);
                                   }
                               }
            
            for(Inquiry__c inquiry : [SELECT Id, Student_Student_Enrollment_Campus__c, Contact__c FROM Inquiry__c
                                      where  Contact__c IN:mapContacts.keySet()]){
                                          System.debug('inquiry'+inquiry);
                                          string enrollment = mapContacts.get(inquiry.Contact__c);
                                          if(enrollment != null){
                                              inquiry.Student_Student_Enrollment_Campus__c = enrollment; 
                                              inquiryList.add(inquiry);
                                          }
                                      }
            for(Opportunity opp : [SELECT Id, ContactId , Student_Enrollment_Campus__c FROM Opportunity where
                                   ContactId  IN:mapContacts.keySet()]){
                                       System.debug('opp'+opp);
                                       string enrollment = mapContacts.get(opp.ContactId);
                                       if(enrollment != null){
                                           opp.Student_Enrollment_Campus__c = enrollment; 
                                           oppList.add(opp);
                                       }
                                   }
            if(listOfContact.size()>0 && !listOfContact.isEmpty()){
                TrgInquiryHandler.isStudentSchoolStopTriggerContact=true;
                update listOfContact;
            }
            if(inquiryList.size()>0 && !inquiryList.isEmpty()){
                update inquiryList;
            }
            if(oppList.size()>0 && !oppList.isEmpty()){
                TrgInquiryHandler.isStudentSchoolStopTriggerOpp=true;
                update oppList;
            }
        }
        string jsonstr=JSON.serialize(lstSchStud);
        
        if(Trigger.isAfter && Trigger.isInsert || Trigger.isAfter && Trigger.isUpdate )
        {   if(!System.isFuture() && !System.isBatch())
            studentSchoolFields.updateSchfldStudentsCVUe(jsonstr);
        }
   // }
        }
}


Test Class 
=============
@isTest
Public  class trgStudentSchoolFieldsTestClass {  
    public static testmethod void contactmethodtest(){
    
       set<string> conid=new set<string>();
        
        Contact con =new Contact();
        con.lastname = 'testmore';
        con.Subscribe_To_SMS_Service__c=true;
        con.Student_Enrollment_Campus__c = 'AUR';
        insert con;
        
        Inquiry__c  inq = new Inquiry__c();
        inq.Name = 'inasfewna===100years====createNewInq';
        inq.Student_Student_Enrollment_Campus__c = 'ONL';
        inq.Contact__c = con.id;
       // insert inq;

        
        Contact_Method__c cm=new Contact_Method__c();
        cm.Name='test';
        cm.Contact__c=con.Id;
        cm.Subscribe_To_SMS_Service__c=true;
        insert cm;
        conid.add(cm.id);
    }
    }
This test class is not Code Coverage in my Class were i am missing i am not understand can you please any one help me
Hi

I am new to the Apex development,i have never written  a test class for future method Apex class, can someone plz help me in writing the test class
 
public class FutureHandler {
    
    @future
    public static void updaterecs(Map<String,Id> oldManagerQuotaMap1){
        Map<Id,Quota__c> oldMapQuota = new Map<Id,Quota__c>();
        if(null != oldManagerQuotaMap1 && oldManagerQuotaMap1.size() > 0){
            for (aggregateResult result: [Select Manager_Quota__c, Sum(Inside_Sales_Roll_Up__c) 
                                          FROM Quota__c WHERE 
                                          Manager_Quota__c IN: oldManagerQuotaMap1.values() 
                                          GROUP BY Manager_Quota__c]) {
                                              system.debug('result'+result)    ;          
                                              oldMapQuota.put((Id)result.get('Manager_Quota__c'),new Quota__c(Id=(Id)result.get('Manager_Quota__c'),Actual_Amount__c =(Decimal)result.get('expr0')));         
                                          }
            
            for(Id qId : oldManagerQuotaMap1.values()){
                if(!oldMapQuota.containskey(qId)){
                    oldMapQuota.put(qId, new Quota__c(Id = qId,Actual_Amount__c = 0.0));
                }
            }
            
            if(null != oldMapQuota && oldMapQuota.size() > 0){
                update oldMapQuota.values();
            }
            
        }
    }
    
    
    public static void sendOppsForApproval(List<Opportunity> opps){
        
        List<Opportunity> oppsToBeSentForApproval = new List<Opportunity>();
        String monthYear = System.now().format('MMMM-yyyy');
        String month = monthYear.split('-')[0];
        String year = monthYear.split('-')[1];
        Date nextMonthStart = System.today().toStartOfMonth().addMonths(1).toStartOfMonth();
        List<Aggregate_Approval__c> appr = [Select Id from Aggregate_Approval__c where Month__c=:month And Year__c=:year]; 
        Id approvalId;
        if(appr.size()>0){
            approvalId = appr[0].Id;
            
            for(Opportunity opp : opps){
                opp.Aggregate_Approval__c = approvalId;
                opp.Status__c = 'In Approval';
                oppsToBeSentForApproval.add(opp);
            }
            update oppsToBeSentForApproval;
           // List<Approval.LockResult> li = Approval.lock(opps);
            
            Approval.ProcessSubmitRequest oppAggregateApproval = new Approval.ProcessSubmitRequest();
            oppAggregateApproval.setComments('Submitting opportunities for Approval for '+System.now().format('MMMM-yyyy'));
            oppAggregateApproval.setObjectId(approvalId);
            Approval.ProcessResult approvalResult = Approval.process(oppAggregateApproval); 
            
        } 
    }
}

 
Hello

I am new to the apex development, can anyone please help in writing test classes for the below trigger, i have no idea how to write a test classes for Triggers and Apex classes
 
trigger UserTrigger on User (after update) {
    
    Map<String,Id> newManagerQuotaMap = new Map<String,Id>();
    Map<String,Id> oldManagerQuotaMap = new Map<String,Id>();    
    Map<String,Quota__c> newReporteeQuotaMap = new Map<String,Quota__c>();
    Map<Id,Id> managerReporteemap = new Map<Id,Id>();
    Map<Id,Id> oldManagerReporteemap = new Map<Id,Id>();
    List<Quota__c> newMapQuota = new List<Quota__c>();
	List<Quota__c> oldMapQuota = new List<Quota__c>();
    
    for(User u : Trigger.new){
        if(u.managerid != Trigger.oldMap.get(u.Id).ManagerId){
            if(u.managerid != NULL)
                managerReporteemap.put(u.Id,u.managerId);
            
             if(Trigger.oldMap.get(u.Id).ManagerId != NULL)
              	oldManagerReporteemap.put(u.Id,Trigger.oldMap.get(u.Id).ManagerId);
        }
    }
    
    if(NULL != managerReporteemap && managerReporteemap.size() > 0 ){
        for(Quota__c qcm: [SELECT Id,Quater__c,Quater_Year__c, Assigned_To__c ,Manager_Quota__c FROM Quota__c WHERE Assigned_To__c IN : managerReporteemap.values()]){
            newManagerQuotaMap.put(qcm.Assigned_To__c + qcm.Quater__c + qcm.Quater_Year__c,qcm.Id);
        }
        
        for(Quota__c qcr : [SELECT Id,Quater__c,Quater_Year__c, Assigned_To__c ,Assigned_To__r.ManagerId, Manager_Quota__c FROM Quota__c WHERE Assigned_To__c IN : managerReporteemap.keyset()]){
            newReporteeQuotaMap.put(qcr.Assigned_To__r.ManagerId+ qcr.Quater__c + qcr.Quater_Year__c,qcr);
        }
        
        List<Quota__c> quotasOfReporteeupdate = new List<Quota__c>();
        if(newReporteeQuotaMap != NULL && newReporteeQuotaMap.size() > 0 ){
            for(String key : newReporteeQuotaMap.keySet()){
                if(newManagerQuotaMap.containsKey(key)){
                    newReporteeQuotaMap.get(key).Manager_Quota__c = newManagerQuotaMap.get(key);
                    
                }else{
                    newReporteeQuotaMap.get(key).Manager_Quota__c = NULL;
                }
                quotasOfReporteeupdate.add(newReporteeQuotaMap.get(key));
            }      
            if(NULL != quotasOfReporteeupdate && quotasOfReporteeupdate.size() > 0)
            	update quotasOfReporteeupdate;            
        }
                
        for (aggregateResult result: [Select Manager_Quota__c, Sum(Inside_Sales_Roll_Up__c) 
                                      FROM Quota__c WHERE 
                                      Manager_Quota__c IN: newManagerQuotaMap.values() 
                                      GROUP BY Manager_Quota__c]) {
                                              
			newMapQuota.add(new Quota__c(Id=(Id)result.get('Manager_Quota__c'),Actual_Amount__c =(Decimal)result.get('expr0')));         
        }
        
        	
        if(NULL != newMapQuota && newMapQuota.size() > 0){
        update newMapQuota;
    }
    
    	}
    
    if(NULL != oldManagerReporteemap && oldManagerReporteemap.size() > 0){
        for(Quota__c qcm: [SELECT Id,Quater__c,Quater_Year__c, Assigned_To__c ,Manager_Quota__c FROM Quota__c WHERE Assigned_To__c IN : oldManagerReporteemap.values()]){
            oldManagerQuotaMap.put(qcm.Assigned_To__c + qcm.Quater__c + qcm.Quater_Year__c,qcm.Id);
        }
        system.debug('oldManagerQuotaMap::' + oldManagerQuotaMap);
        if(NULL != oldManagerQuotaMap && oldManagerQuotaMap.size() > 0){
            futureHandler.updaterecs(oldManagerQuotaMap);
        }
     
    }      
    }



 
{!REQUIRESCRIPT("/soap/ajax/13.0/connection.js")}
{!requireScript("/soap/ajax/30.0/apex.js")}
var oppObj = new sforce.SObject("Opportunity");
oppObj.Id = '{!Opportunity.Id}'; 
var result = sforce.connection.update([oppObj]);
if (result[0].success=='false') {
alert(result[0].errors.message);
}
else {
sforce.apex.execute('ApexClass', 'methodName', {optyId:'{!Opportunity.Id}', action:'Default'});
alert('{!$Label.Success}');
}
}
document.location = '/{!Opportunity.Id}';

I've simply addeed the entire code to vf page, standardcontroller as Opportunity.
I need to use CSS as well so that the error msg can be displayed in left top instead of the alert box which displayed at the center on top.

Please help ASAP.
Hi All,

How to write a scheduler class for daily and weekly for below Batch Apex
  • IF the recent Recharge record for 'Internet Plan' record was made 1 day ago and its 'Data Plan' = 'Daily', then create Recharge record.
  • IF the recent  Recharge for 'Internet Plan' was made 6 days ago and 'Data Plan' = 'Weekly', then create Recharge record.
    global class batchCreateRecharge implements Database.Batchable<sobject> {
      
        global Database.QueryLocator start(Database.BatchableContext bc){
          
            String query = 'SELECT Id, Data_Plan__c,Total_Amount__c FROM Internet_Plan__c';
            return Database.getQueryLocator(query);
        }
          
        global void execute(Database.BatchableContext bc, List<Internet_Plan__c> scope) {
          try {
         List<Recharge__c> rcList = new List<Recharge__c>();
            for(Internet_Plan__c IP : scope) {
               Recharge__c rc = new Recharge__c();
              rc.Amount__c = IP.Total_Amount__c;
               rc.Internet_Plan__c= IP.id;
             rcList.add(rc);
             System.debug('******Recharge list'+rcList);
            }
       insert rcList;
     }
             
                catch( DmlException e ) {
                    // HANDLES EXCEPTIONS RELATED TO DML STATEMENTS.
                    System.debug( 'QueryException:-\n' + e.getMessage() + '\nLine Number:-\n' + e.getLineNumber() );
                }
                catch( Exception e ) {
                    // HANDLES EXCEPTIONS OTHER THAN ABOVE SUCH AS NULL POINTER EXCEPTIONS OR ETC.
                    System.debug( 'QueryException:-\n' + e.getMessage() + '\nLine Number:-\n' + e.getLineNumber() );
                }
    
        } 
          
        global void finish(Database.BatchableContext bc) {
          
        }
    }

    Kindly Support and Suggest
Thanks
  • April 30, 2019
  • Like
  • 0
AND(NOT(ISBLANK(Component__c)),AND(OR(AND(Component__r.Product__r.yes__c = FALSE,NOT(ISPICKVAL(Component__r.type__c,"exhausted"))),NOT(ISPICKVAL( Component__r.Status__c,"install"))),Service__c = FALSE),$RecordType.Name='supportive', 
$Setup.settings__c.Validate__c = FALSE, 
ISBLANK(source__c),ISPICKVAL(Categories__c,"fields"),OR(ISPICKVAL(Reasons__c,"appear"), ISPICKVAL(Reasons__c,"Maintenance")),NOT(ISPICKVAL(Origin,"Portal")),Component__r.Product__r.source__c = "RT")
Created two field (data type-picklist) on the opportunity and have to make the fields mandatory when the Sales Occupy = Field Sales AND the stage is advancing beyond Stage 2, then these 2 fields mandatory.

I tried below... but not working....Could you please correct me??

AND ( NOT ( ISPICKVAL ( StageName,  '2. Discover' )  )  ),
 ISPICKVAL(Sales__c, 'Field Sales'), ISBLANK ( TEXT ( Fin_Se__c ) ) || ISBLANK ( TEXT ( Fin_Se_Type__c ) ) )