• 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'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
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 ) ) )