• si ri
  • NEWBIE
  • 65 Points
  • Member since 2019

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 23
    Questions
  • 21
    Replies
I am creating events on Account object. In the event object I have two date/time fields Start Time and End Time.
My question is how I can validate new Start Time or End Time of an event exists with any  existing event related to an Account?

The only way I can think to validate if the sessions overlap is to use a trigger with the addError() method.
It means new event should not be created on an Account if there is an existing event relays with same date/time.
how can I compare the times of each event for an Account?

here is my trigger I am failing to achieve my requirement. Any one help me appretiated.
trigger sessionValidation on Event (before insert,before update) {
    Set<ID> accID = new set<ID>();

    for(Event eve : trigger.new)
    {
      accID.add(eve.AccountId);
    }
  
    List<Event> ExistingEventList = [Select StartDateTime , EndDateTime from Event where AccountID in : accID];
    system.debug('ExistingEventList :'+ExistingEventList);
    
    for(Event sNew : trigger.new)
    {
        
        for(Event sOld : ExistingEventList)
        {
                            if((sNew.StartDateTime <= sOld.StartDateTime && sNew.EndDateTime  >=  sOld.StartDateTime && sNew.EndDateTime <= sOld.EndDateTime) || 
                   (sNew.StartDateTime <= sOld.StartDateTime && sNew.EndDateTime  >= sOld.StartDateTime && sNew.EndDateTime >= sOld.EndDateTime) ||
                   )
            {
                sNew.addError('Overlap Session');
            }
        }
    }
}
 
  • October 22, 2019
  • Like
  • 0
Hi guys,
I knew how to calll void methods in test but How to call global static void  Rest API methods in test class?
 
  • September 30, 2019
  • Like
  • 0
Hi all,
Can we  query all the child records for a parent record where excluding a particular child ID?
  • September 20, 2019
  • Like
  • 0
Hi all, how convert a string into Datetime format in apex?
String starttime = '2018-12-29T15:30:00+05:30';
DateTime  dt = DateTime.valueof(starttime );
system.debug('dt value :' +dt ); 
dt = 2018-12-29 10:00:00
so now I want to convert (dt = 2018-12-29 10:00:00) equals to 
2018-12-29T10:00:00.000+0000 format. how I can convert this please guide me.
  • September 16, 2019
  • Like
  • 0
Hi all,
How to fetch records between StartDateTime and EndDateTime including StartDateTime and EndDateTime records by comparing with Activity date
StartDateTime : datatype( Date/Time)
EndDateTime   :datatype( Date/Time)
Activity date :datatype( Date/Time)


 My query:
List<Event> eventList = [select  WhatId, Subject, ActivityDate, StartDateTime, EndDateTime from Event where WhatId= :accountId and ActivityDate <= StartDateTime between  EndDateTime <= ActivityDate ];

Can anyone please help me with right query
  • September 10, 2019
  • Like
  • 0
Hi all, need some help to define validation logic.
On Event object, there are two fields Start time & End time.
The user should be able to create event before start time or after End time only.
It means if there is any event created, the another event shouldnot be created in the middle of the start and End time of that event on that particular date.
  • September 09, 2019
  • Like
  • 0
Hi all, 
            I am trying to invoke Lead assignment rule when ever certain criteria meets the trigger should fire.
        But I am getting the following error :  execution of AfterInsert caused by: System.DmlException: Update failed. First exception on row 0; first error: MISSING_ARGUMENT, Id not specified in an update call: []: 
        Can anyone guide me where I am donig wrong.Thanks in advance.
My Trigger:
trigger LeadAssignment on Lead (After insert,After update) {
    
    List<Lead> updateLeads = new List<Lead>();
    
    Lead newLead = new Lead();
    for(Lead l : trigger.new)
    {
        if(l.Status == '01-New' || l.Status == '50-Qualified')
        {
            AssignmentRule AR = new AssignmentRule();
            AR = [select id from AssignmentRule where SobjectType = 'Lead' and Active = true limit 1];
            
            Database.DMLOptions dmlOpts = new Database.DMLOptions();
            dmlOpts.assignmentRuleHeader.assignmentRuleId= AR.id;
            system.debug('dmlOpts***********'+dmlOpts);
             
             newLead.setOptions(dmlOpts);
           // updateLeads.add(newLead);
             
                    }
      
    }
    update newLead;
    system.debug('updateLeads************'+newLead);

}
  • September 04, 2019
  • Like
  • 0
Hi Experts,
         I have created a test class for a trigger and apex class for trigger code coverage is 78% and test class is 81% in Sandbox1.
         when I have created same test class for a trigger and apex class, for trigger code coverage is 0% and test class is 0% in another sanbox2.
         Both sanbox1 and sanbox2 are identical but I don't know why the code coverage is not happening in sanbox2. Can anyone know the reason?
  • August 30, 2019
  • Like
  • 0
Hi experts,
Can we  bypass a trigger when submitting the custom VF page?
  • August 20, 2019
  • Like
  • 0
I have a requirement that for an account there should be unique email id for every related contact. But in my code it is not working as per the requirement, it is checking all the contacts irrespective of Account. 
But I need to check only Account related contacts email id's.Here is my code please help me where I am doing wrong.

trigger ContactTrigger on Contact (before insert,before update)
 {
   
  set<ID> accId = new set<ID>();
   list<string> ContactEmails=new list<string>();
    for(Contact conVar:trigger.new)
    {
        ContactEmails.add(conVar.email);
        accId.add(conVar.AccountId);
    }
    
    system.debug('ContactEmails ************' +ContactEmails);
    
    list<Contact> listOfDuplicateContacts=[select id,email,Account.ID from Contact where email in :ContactEmails AND AccountID IN : accId];
      system.debug('listOfDuplicateContacts ************' +listOfDuplicateContacts);
    
    for(Contact con:trigger.new)
    {
        if(trigger.isInsert){
        if(listOfDuplicateContacts.size()!=0)
        {
            con.addError('Contact email already exists with this name');
        }
        }
        if(trigger.isUpdate)
        {
           for(Contact oldContact :trigger.old)
           {
               if(con.Email!=oldContact.Email && listOfDuplicateContacts.size()!=0)
               {
                   con.addError('Contact email already exists with this name');
               }
           }
        }
    }
}
  • August 12, 2019
  • Like
  • 0
Hi everyone, 
 I have requirement that an Account has multiple contacts. If we select a 'talent' checbox field on one contact-1 then the user should not be able to select that 'talent' checkbox field on another contact-2 it should throw an error message before saving the record and also when we edit the record. It means only once that 'talent' checkbox field should be able to check on any one Contact. 
How can I acheive this, please help me with sample code.
  • August 06, 2019
  • Like
  • 0
Hi,
I have a requirement that from Opportunity (i.e. create Order and Order Line Items from Opportunity, whenever product is added in Opportunityline item product should be created in orderItem and whenever product is deleted in Opportunityline item product should be deleted in orderItem). As per my code order and orderitems were creating but when ever I edit the Opportunity orderitems are creating duplicate times.
public class example {
    
    public static void CreatingOrders(List<Opportunity> newlist){
        set<Id> oppId = new set<Id>();
        for(Opportunity opp : newList){
            oppId.add(opp.id);    
        }
        List<Opportunity> oppList = [select id,name,StageName,Contract_number__c,ContractId,Accountid,Pricebook2Id, (select Status,Account.name,enddate from Orders)
                                     from Opportunity where Id =: oppId];
          
        List<Order> insertorders = new List<Order>();
        
        for(Opportunity opp1 : oppList){
            
            if (opp1.Orders.size()>0){
                
            } 
            else if(opp1.StageName == 'Closed-Won') {
                Order ordr =new Order();
                ordr.AccountId = opp1.AccountId;
                ordr.OpportunityId = opp1.id;
                ordr.Status = 'Draft';
                ordr.EffectiveDate = system.today();
                ordr.Pricebook2Id = opp1.Pricebook2Id;
          
              ordr.ContractId = opp1.ContractId; 
                insertorders.add(ordr);
            }
        }
        insert insertorders;
       
    }
    
    public static void CreatingOrderlineitems(List<Opportunity> newlist1)
    {
        set<Id> oppId = new set<Id>();
        for(Opportunity opp : newList1){
            oppId.add(opp.id);
        }
       
        
        List<Order> ordrList  = [select Status,Account.name,enddate,Pricebook2Id,OpportunityId,Opportunity.name,Opportunity.stagename,
                                 (select UnitPrice,PricebookEntryId,Description,Quantity, Discount_Percentage__c, One_Time__c,
                                   Integration_Key_Product__c from OrderItems) from Order where Opportunityid =: oppId];
        

        Set<Id> opportunityIds = new Set<Id>();
        
        List<Order> orderList = new List<Order>();
        
        for(Order o : ordrList)
        {
            if(o.Opportunityid != NULL)
            {
                opportunityIds.add(o.Opportunityid);
                orderList.add(o);
            }
        }
        
        Map<Id, Opportunity> oppsWithLineItems = new Map<Id, Opportunity>([SELECT Id, Pricebook2Id, (SELECT Description,Id,ListPrice,Name,OpportunityId,
                                                                                                     Product2Id,ProductCode,Quantity,TotalPrice,UnitPrice,PricebookEntryId,
                                                                                                     Discount_Percentage__c, One_time_applicable_formula__c,Integration_Key_Product__c 
                                                                                                     FROM OpportunityLineItems) from Opportunity WHERE Id IN :opportunityIds]); 
        if(opportunityIds.size() > 0)
        
        {
            
            List<OrderItem> InsertorderItems = new List<OrderItem>();
            List<Order>  upordrList = new List<Order>();
            for(Order o : ordrList)
            {
                
                for(OrderItem ordItem : o.OrderItems){

                Opportunity oppWithLineItem = oppsWithLineItems.get(o.Opportunityid);
                
                for(OpportunityLineItem oli : oppWithLineItem.OpportunityLineItems)
                {
                    
                    InsertorderItems.add(new OrderItem(OrderId=o.Id,UnitPrice=oli.UnitPrice,PricebookEntryId = oli.PricebookEntryId,Description = oli.Description,
                                                          Quantity =oli.Quantity, Discount_Percentage__c = oli.Discount_Percentage__c,
                                                             One_Time__c  = oli.One_time_applicable_formula__c));
                
                }
            }
           }
              insert InsertorderItems;
        }
    }
}
  • July 09, 2019
  • Like
  • 0

I have a rquirement that, by clickin on a custom button on Contract object  standard recordtypes like OP1,OP2,OP3 page selection should be opened. If we select OP1 recordtype from that picklist  related OP1 page record should be opened and vise versa. How can i acheive this,please help me, I'm new to coding.
  • July 05, 2019
  • Like
  • 0
Hi all,
1.When Order is created, copy the OpportunityLineItem
2.When OpportunityLineItems are changed (added/updated/deleted), resync to OrderItem (presumably once Opportunity is closed, this can't happen)
But when i edit and save the record duplicate orderitems are creating, my requirement is to create only once, if the new product is added on the opportunity then it only that product should be added in the Orderitem. can anyone help me.Thanks in advance
trigger creatingMenuDetails on Order (after insert, after update)
{
    // Get all related opportunities from orders
    Set<Id> opportunityIds = new Set<Id>();
    List<Order> orderList = new List<Order>();
    for(Order o : Trigger.new)
    {
        if(o.Opportunity__c != NULL)
        {
            opportunityIds.add(o.Opportunity__c);
            orderList.add(o);
        }
    }

    // Query for all opportunities with their related opportunity line items
    Map<Id, Opportunity> oppsWithLineItems = new Map<Id, Opportunity>([SELECT Id,Pricebook2Id, (SELECT Description,Id,ListPrice,Name,OpportunityId,Product2Id,ProductCode,Quantity,TotalPrice,UnitPrice FROM OpportunityLineItem) WHERE Id IN :opportunityIds]);
   List<Order>  updateorderList = new List<Order>();
    if(opportunityIds.size() > 0)
    {
        // Loop through orders
        List<OrderItem> orderItemsForInsert = new List<OrderItem>();
        for(Order o : ordersList)
        {
              o.Pricebook2Id = oppsWithLineItems.get(o.OpportunityId).pricebook2Id;
            // For each order get the related opportunity and line items, loop through the line items and add a new order line item to the order line item list for each matching opportunity line item
            Opportunity oppWithLineItem = oppsWithLineItems.get(o.Opportunity__c);
            for(OpportunityLineItem oli : oppWithLineItem.OpportunityLineItems)
            {
                orderItemsForInsert.add(new OrderItem(AvailableQuantity=Quantity,OrderId=o.Id,etc,etc,etc));
            }
        }
          update updateorderList;
        // If we have order line items, insert data
        if(orderItemsForInsert.size() > 0)
        {
            insert orderItemsForInsert;
        }
    }
}
  • June 11, 2019
  • Like
  • 0

I am trying to create orderitems from OpportunityLine items and also creating order on Opportunity. But I am getting the following error
Error: execution of AfterUpdate caused by: System.TypeException: Invalid id value for this SObject type: 00kq0000008mWXjAAM: Class.Autocreation .CreatingOrders:
at this particular line [ordr1.Id = oli.Id;]
Which Id needs to be take, I don't understand Can anyone help me.Thanks inadvance

public static void CreatingOrders(List<Opportunity> newlist){
      set<Id> oppId = new set<Id>();
    for(Opportunity opp : newList){
        oppId.add(opp.id); //Adding Opportunity's to Set.    
         }
    List<Opportunity> oppList = [select id,name,StageName,Accountid, (select Status,Account.name,enddate from Orders)
                                 from Opportunity where Id =: oppId];

     List<OpportunityLineItem> oppList1 = [SELECT id,Quantity,Product2Id,
                                  UnitPrice,Description, TotalPrice,PricebookEntry.Name, PricebookEntry.Product2.Family,
                                  OpportunityId FROM OpportunityLineItem where OpportunityId =: oppId];



    List<Order> insrtordrs = new List<Order>();
    List<OrderItem> insrtordrs1 = new List<OrderItem>();

    for(Opportunity opp1 : oppList){
        for(OpportunityLineItem oli : oppList1 ){  
        if (opp1.Orders.size()>0){
            system.debug('Orders exists*******************' +opp1.Orders);

        } 
        else if(opp1.StageName == 'Closed-Won') {
          Order ordr =new Order();
          ordr.AccountId = opp1.AccountId;
          ordr.OpportunityId = opp1.id;
          ordr.Status = 'Draft';
          ordr.EffectiveDate = system.today();
          //ordr.ContractId = opp1.ContractId; 
          insrtordrs .add(ordr);

            OrderItem ordr1 =new OrderItem();
            ordr1.Id = oli.Id;
            ordr1.PricebookEntryId = oli.PricebookEntryId;
            ordr1.UnitPrice        = oli.UnitPrice;
            ordr1.Description      = oli.Description;
            ordr1.Quantity         = oli.Quantity;
            insrtordrs1 .add(ordr1);  

        }   
       }
    }
    insert insrtordrs ;
    insert insrtordrs1 ;

 }
  • June 04, 2019
  • Like
  • 0
Hi everyone!
              Need help, to capture failed records in batch class.Below  is my code, i am able to capture sucessfull records but unable to capture failed records.
global class updateOppSendPIQReport implements Database.Batchable<SObject>{
    
    global Set<Id> failureIdsSet;

    
    global Database.QueryLocator start(Database.BatchableContext BC)
    { 
        //Fetch records after opportunity stage is set to PIQ Complete
        return Database.getQueryLocator('SELECT ID, StageName__c, SendPIQReport__c, Opportunity__r.id FROM PIQ_Response__c where StageName__c = \'PIQ Complete\' or StageName__c = \'50-PIQ Complete\' ');
              
    }
    
    global void execute(Database.BatchableContext BC, List<PIQ_Response__c> scope){
        
        failureIdsSet = new Set<Id>();

        List<PIQ_Response__c> updatepiq = new List<PIQ_Response__c>();
        for(PIQ_Response__c piq :  scope){
            if(piq.SendPIQReport__c == False && piq.StageName__c == 'PIQ Complete'){
                
                String [] emailList = new List<String>();
                Set<Id> opId = new Set<Id>();
                
                opId.add(piq.Opportunity__r.id);
                //Fetch Opportunity Record
                Opportunity op = [select id, name, AccountID from Opportunity where Id=:opId];
                
                // DML statement
                Database.SaveResult[] srList = Database.update(scope, false);
                
                // Iterate through each returned result
                for (Database.SaveResult sr : srList) {
                    if (sr.isSuccess()) {
                        // Operation was successful, so get the ID of the record that was processed
                        System.debug('Successfull records****************************: ' + sr.getId());
                    }
                    else {
                        // Operation failed, so get all errors                
                        for(Database.Error err : sr.getErrors()) {
                            System.debug('The following error has occurred.');                    
                            System.debug(err.getStatusCode() + ': ' + err.getMessage());
                            System.debug('failed records**************************: ' + err.getFields());
                        }
                    }
                }
                //Fetch Email id of Account Manager
                List<AccountTeamMember> teamList = [ SELECT ID, TeamMemberRole,
                                                    User.Email
                                                    FROM AccountTeamMember
                                                    WHERE AccountID = :op.AccountID 
                                                    AND TeamMemberRole = 'Account Manager'];
                for(AccountTeamMember a1: teamList){
                    emailList.add(a1.User.Email);
                }
                //Fetch Email id of Sales Coordinator
                List<AccountTeamMember> teamList2 = [ SELECT ID, TeamMemberRole,
                                                     User.Email
                                                     FROM AccountTeamMember
                                                     WHERE AccountID = :op.AccountID 
                                                     AND TeamMemberRole = 'Sales Coordinator'];
                for(AccountTeamMember a2: teamList2){
                    emailList.add(a2.User.Email);
                }  
                 List<CustomUsers__c> cu1 = [select UserEmails__c from CustomUsers__c];
                
               
                for(CustomUsers__c u1:cu1){
                     list<string> templist = u1.UserEmails__c.split(',');
                    emailList.addAll(templist);
                     //emailList.add(u1.UserEmails__c); 
                                         system.debug('EmailList'+emailList);
                                     }
                
                String [] emailList2 = new List<String>();
                for (Integer i = 0; i<emailList.size(); i++) {
                    emailList2.add(emailList[i]);
                     system.debug('EmailList**'+emailList2);
                } 
                PIQCOntroller.sendPDf(piq.Id, emailList2);
                piq.SendPIQReport__c = True;
                updatepiq.add(piq);
            } 
        }
        update updatepiq;
        system.debug('updatepiq*******************'+updatepiq);
    }
    
    global void finish(Database.BatchableContext BC)
    {
    }
}
  • May 28, 2019
  • Like
  • 0
Hi,I have an Apex class in which custom settings are used and I am unable cover the code coverage. I am using another apex class testclass so that my actual apex class code coverage increased to 48% only. I am unable increase the code coverage to 75% Please anyone help me out. Thanks in advance

Apex Class:
public class InstallationHelper {

 private static Case_Installation_Settings__c settings;

    public static void markUnitComplete( List<Installation__c> newInstalls, Map<Id, Installation__c> oldInstalls)
    {
        
        Set<Id> completedInstallUnitIds = new Set<Id>();
        List<Unit__c> updateUnits = new List<Unit__c>();

        if ( settings == null ) settings = Case_Installation_Settings__c.getInstance();


        if ( newInstalls != null && newInstalls.size() > 0 )
        {
            for ( Installation__c inst : newInstalls )
            {
                Installation__c oldInst;
                if (oldInstalls != null && oldInstalls.containsKey(inst.Id))
                {
                    oldInst = oldInstalls.get(inst.Id);
                }

                if ( DisplayUtils.hasChanged(oldInst, inst, 'Status__c') && inst.Mark_Unit_Complete__c )
                {
                    if ( inst.Unit__c != null )
                    {
                        completedInstallUnitIds.add( inst.Unit__c );
                    }
                }
            }
            List<Unit__c> unitList =  [SELECT id, name, status__c FROM Unit__c WHERE Id IN :completedInstallUnitIds];
           
            if ( completedInstallUnitIds != null && completedInstallUnitIds.size() > 0 )
            {
                for ( Unit__c u :unitList)
                {
                    u.Status__c = settings.Unit_Installed_Status_Name__c;
                    updateUnits.add( u );
                }
            }

            if ( updateUnits != null && updateUnits.size() > 0 )
            {
                update updateUnits;
                
            }
            
        }
    }
    
      public static void updateScheduleIds(list<Installation__c> newList, map<id,Installation__c> oldlist)
    {
        set<id> accountids = new set<id>();
        map<id,Installation__c> compInst = new map<id,Installation__c>();
        list<Installation__c> updateInstallations = new list<Installation__c>();
        List<Installation__c> insList = [Select id,Site__c,After_PSA_Schedule_created__c FROM Installation__c WHERE Site__c IN:accountids];
        for(Installation__c inst : newList)
        {
            if(inst.Monitoring_hours_changed__c == false && oldlist.get(inst.id).Monitoring_hours_changed__c== true)
            {
                accountids.add(inst.Site__c);
                compInst.put(inst.Site__c,inst);
            }
            else if(inst.After_PSA_Schedule_created__c == true && oldlist.get(inst.id).After_PSA_Schedule_created__c == false)
            {
                accountids.add(inst.Site__c);
                compInst.put(inst.Site__c,inst);
            }
            if(!accountids.isEmpty())
            {
                for(Installation__c ins : insList)
                {
                    if(compInst.get(ins.Site__c).id != ins.id)
                    {
                        Installation__c temp = compInst.get(ins.Site__c);
                        ins.Monday_ScheduleID__c = temp.Monday_ScheduleID__c;
                        ins.Tuesday_ScheduleID__c = temp.Tuesday_ScheduleID__c;
                        ins.Wednesday_ScheduleID__c = temp.Wednesday_ScheduleID__c;
                        ins.Thursday_ScheduleID__c = temp.Thursday_ScheduleID__c;
                        ins.Friday_ScheduleID__c = temp.Friday_ScheduleID__c;
                        ins.Saturday_ScheduleID__c = temp.Saturday_ScheduleID__c;
                        ins.Sunday_ScheduleID__c = temp.Sunday_ScheduleID__c;
                        updateInstallations.add(ins);
                    }
                    else if(ins.After_PSA_Schedule_created__c == true && compInst.get(ins.Site__c).id == ins.id)
                    {
                        ins.After_PSA_Schedule_created__c = false;
                        updateInstallations.add(ins);
                    }
                }
            }
        }
        
        if(!updateInstallations.isEmpty())
            update updateInstallations;
    }

}

Test Class:
@isTest
public with sharing class VFC_MonitoringHours_Ext_Test {
    @TestSetup 
    public static void setupData() {
                  
           
            Account a = new Account();
            a.Name = 'SGI Test One';
            a.Type = 'Customer';
            a.Channel__c = 'Reseller';
            a.Activity_Email__c = 'nopetest@test.com';
            a.RecordType = new RecordType( Name = 'Site' );
            insert a;
            
                    
            
            Contact cnt = new Contact();
            cnt.FirstName = 'Test';
            cnt.LastName = 'Contact';
            cnt.AccountID = a.ID;
            insert cnt;
            
            Opportunity o = new Opportunity();
            o.AccountID = a.ID;
            o.Name = 'SGI Test 1';
            o.StageName = 'Discovery'; // '40-Contracts Signed';
            o.CloseDate = Date.today();
            o.Contract_Expiration_Date__c = Date.today();
            o.RecordTypeId = '012o0000000pmDS';
            o.Billing_Schedule__c = 'Monthly';
            o.Payment_Terms__c = 'NET 15';
            o.PiQ_Contact__c = cnt.ID;
            o.Opp_is_Approved_for_Quote__c = true;
            
            insert o;
            
            Case ca = new Case();
            ca.Type ='Account Change';
            ca.Status ='01-New';
            ca.Subject ='test new';
            ca.Description = 'new Description';
            ca.AccountId= a.id;
            ca.ContactId = cnt.id;  
            insert ca;
            
            Installation__c inst = new Installation__c();
            inst.Name__c ='instal';
            inst.Status__c = '0-New';
            inst.Monitoring_Service__c = 'Live';   
            inst.Site__c = a.Id;
            inst.prior_status__c = 'Suspend';
            inst.prior_monitoring_service__c = 'Client';
            inst.Install_Case__c = ca.id;
            inst.Monitoring_hours_changed__c = true;
            inst.Opportunity__c = o.id;       
            insert inst; 
            inst.Monitoring_hours_changed__c = false;

            o.StageName = 'Installed';
            update o;
         
        }
    }
    }
  • April 01, 2019
  • Like
  • 0
Hi!
I have a master detail relationsip between Installation__c and Account. and ralation field between Installation__c  & Account is Site__c(API name).
I have a picklist (Time Zone) value on Account and Installation__c that are identical.
There are 5 values for the picklist.

Whenever the picklist value changes on Installation__c , I want to update the picklist value on Account  by using apex code only. But i'm getting null value at  insert accountstoUpdate; line.
Can anyone help, thanks in advance.

My apex class:
public class AccountTimeZoneUpdate {
       public static void accountTimeZone(List<Installation__c> newlist){ 
         set<Id> insId = new set<Id>();
        for(Installation__c inst : newList){
            insId.add(inst.id); 
        } 
     List<Installation__c> instList = [select id,Time_Zone__c Name from Installation__c];
          system.debug('installation list:'+instList);
           
           List<Account> accList = [select id,Time_Zone__c,name from  Account where Time_Zone__c =: null];
           
               system.debug('installation list:'+instList);
           List<Account> accountstoUpdate = new List<Account>();
          
           for(Installation__c insVar:instList){
               for(Account a: accList){
         //  Account acc = new Account();
              if(insVar.Time_Zone__c != null && insVar.Time_Zone__c != '') {
                   a.Time_Zone__c = insVar.Time_Zone__c;
                   accountstoUpdate.add(a);
              }
         }  
     }
            insert accountstoUpdate;
           system.debug('accountstoUpdate time:'+accountstoUpdate);
  }
}

My trigger:
trigger InstallationTrigger on Installation__c (after insert, after update) {
       if (Trigger.isAfter && (Trigger.isInsert || Trigger.isUpdate)){
            AccountTimeZoneUpdate.accountTimeZone(trigger.new);
        }
    
  • February 26, 2019
  • Like
  • 0
Hi, 
 I,m unable to get code coverage for sending emailnotification. can anyone help me. Thanks in advance

public class NotificationEmail {
    
     public static void sendNotificationEmail(List<Account> newList2){
          
        map<id,set<string>> AccRecp = new map<id,set<string>>();
       
         for(Account acc2 : newList2)
        {
            if(acc2.Activity_Email__c != null && acc2.Activity_Email__c != '' && acc2.Status__c == true )
            {
                set<string> emailids = new set<string>();
             
                list<string> templist = acc2.Activity_Email__c.split(',');
               
                emailids.addALL(templist);
              
                AccRecp.put(acc2.id,emailids);
               
            }
             
        }
         if(!AccRecp.isEmpty())
        {
            EmailTemplate et = [ Select Body, HtmlValue, Id, Name, Subject from EmailTemplate  where Name='Post Suspension' Limit 1];
            List<Messaging.SingleEmailMessage> theEmails = new list<Messaging.SingleEmailMessage>();
             for(Account ac: newList2)
            {
                if(AccRecp.containsKey(ac.id))
                {
                    set<string> temp = AccRecp.get(ac.Id);
                   
                    list<string> emaillist= new list<string>();
                     emaillist.add(label.Account_team);
                    emaillist.addAll(temp);
                    string body = et.Body;
                    
                    OrgWideEmailAddress[] ar = [select Id,Address from OrgWideEmailAddress where Address = 'abc@company.com' ];
                    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                    mail.setToAddresses(emaillist);
                    mail.setSubject(' Notice of Suspension-' +' '+ ac.Name);
                    mail.setOrgWideEmailAddressId(ar.get(0).id);
                    mail.setPlainTextBody(body);
                    theEmails.add(mail);
                    
                }
            }
        
              if(!theEmails.isEmpty())
            {
                list<Messaging.Email> allMails = new list<Messaging.Email>();
                for( Integer j = 0; j < theEmails.size(); j++ ){
                    allMails.add(theEmails.get(j));
                }
                if(!allMails.isempty())
                    
                {
                    Messaging.SendEmailResult[] results = Messaging.sendEmail( allMails,false );
                    
                    if (results[0].isSuccess()) {
                        
                        
                        system.debug('The email was sent successfully.');
                     } else {
                         system.debug('The email failed to send: '+results[0].getErrors());
                     }
                }
            }
        }
    }
  • February 19, 2019
  • Like
  • 0
Hi!
 I wrote a  before trigger when a Checkbox is CHECKED in an Account object it should print an error message on Case object when certain criteria met. But whatever the method in my class is not invoking when the trigger fires. Can anyone help?

Apex class
    public class updatemonitoringservice{
     public static Boolean caseValidation(List<Account> accountList){
        set<Id> accId = new set<Id>();
        for(Account acc : accountList){
            accId.add(acc.id); //Adding accountId's to Set.    
             }
        List<Account> accList = [select id, Name, Suspend__c,(select id,RecordTypeId, RecordType.Name from Cases) from Account where Id=:accId];
          map<Id,List<Case>> mapInst = new map<Id,List<Case>>();
        for(Account accVar : accList){
            mapInst.put(accVar.Id,accVar.Cases); 
        }
        List<Case> csList = new List<Case>();
         for(Account a : accList){
                                       
           if(a.Suspend__c) 
              {
            
                system.debug('a.Suspend__c::'+a.Suspend__c);
               csList.addAll(mapInst.get(a.Id));  
               
            }
         }
        List<Case> caseError = new List<Case>();
        Boolean hadErrors = false;
        for(Case caseVar:csList){
            if(caseVar.RecordType.Name  != 'Accounting_Request' && caseVar.RecordType.Name  == 'Service_Request')
                  
            {
                caseVar.Type = 'Removal';   
                
            } 
            else
            {
                caseVar.addError('Account is currently Suspended, please contact Collections / CEM for more information');
                 hadErrors = true;
            }
        }
       return hadErrors;
    }
   }

trigger
trigger UpdateMonitoringtrigger on Account (before insert) {
updatemonitoringservice.caseValidation(trigger.new);
   }


    
  • January 29, 2019
  • Like
  • 0
Hi all,
How to fetch records between StartDateTime and EndDateTime including StartDateTime and EndDateTime records by comparing with Activity date
StartDateTime : datatype( Date/Time)
EndDateTime   :datatype( Date/Time)
Activity date :datatype( Date/Time)


 My query:
List<Event> eventList = [select  WhatId, Subject, ActivityDate, StartDateTime, EndDateTime from Event where WhatId= :accountId and ActivityDate <= StartDateTime between  EndDateTime <= ActivityDate ];

Can anyone please help me with right query
  • September 10, 2019
  • Like
  • 0
Hi experts,
Can we  bypass a trigger when submitting the custom VF page?
  • August 20, 2019
  • Like
  • 0
I have a requirement that for an account there should be unique email id for every related contact. But in my code it is not working as per the requirement, it is checking all the contacts irrespective of Account. 
But I need to check only Account related contacts email id's.Here is my code please help me where I am doing wrong.

trigger ContactTrigger on Contact (before insert,before update)
 {
   
  set<ID> accId = new set<ID>();
   list<string> ContactEmails=new list<string>();
    for(Contact conVar:trigger.new)
    {
        ContactEmails.add(conVar.email);
        accId.add(conVar.AccountId);
    }
    
    system.debug('ContactEmails ************' +ContactEmails);
    
    list<Contact> listOfDuplicateContacts=[select id,email,Account.ID from Contact where email in :ContactEmails AND AccountID IN : accId];
      system.debug('listOfDuplicateContacts ************' +listOfDuplicateContacts);
    
    for(Contact con:trigger.new)
    {
        if(trigger.isInsert){
        if(listOfDuplicateContacts.size()!=0)
        {
            con.addError('Contact email already exists with this name');
        }
        }
        if(trigger.isUpdate)
        {
           for(Contact oldContact :trigger.old)
           {
               if(con.Email!=oldContact.Email && listOfDuplicateContacts.size()!=0)
               {
                   con.addError('Contact email already exists with this name');
               }
           }
        }
    }
}
  • August 12, 2019
  • Like
  • 0

I have a rquirement that, by clickin on a custom button on Contract object  standard recordtypes like OP1,OP2,OP3 page selection should be opened. If we select OP1 recordtype from that picklist  related OP1 page record should be opened and vise versa. How can i acheive this,please help me, I'm new to coding.
  • July 05, 2019
  • Like
  • 0
Hi all,
1.When Order is created, copy the OpportunityLineItem
2.When OpportunityLineItems are changed (added/updated/deleted), resync to OrderItem (presumably once Opportunity is closed, this can't happen)
But when i edit and save the record duplicate orderitems are creating, my requirement is to create only once, if the new product is added on the opportunity then it only that product should be added in the Orderitem. can anyone help me.Thanks in advance
trigger creatingMenuDetails on Order (after insert, after update)
{
    // Get all related opportunities from orders
    Set<Id> opportunityIds = new Set<Id>();
    List<Order> orderList = new List<Order>();
    for(Order o : Trigger.new)
    {
        if(o.Opportunity__c != NULL)
        {
            opportunityIds.add(o.Opportunity__c);
            orderList.add(o);
        }
    }

    // Query for all opportunities with their related opportunity line items
    Map<Id, Opportunity> oppsWithLineItems = new Map<Id, Opportunity>([SELECT Id,Pricebook2Id, (SELECT Description,Id,ListPrice,Name,OpportunityId,Product2Id,ProductCode,Quantity,TotalPrice,UnitPrice FROM OpportunityLineItem) WHERE Id IN :opportunityIds]);
   List<Order>  updateorderList = new List<Order>();
    if(opportunityIds.size() > 0)
    {
        // Loop through orders
        List<OrderItem> orderItemsForInsert = new List<OrderItem>();
        for(Order o : ordersList)
        {
              o.Pricebook2Id = oppsWithLineItems.get(o.OpportunityId).pricebook2Id;
            // For each order get the related opportunity and line items, loop through the line items and add a new order line item to the order line item list for each matching opportunity line item
            Opportunity oppWithLineItem = oppsWithLineItems.get(o.Opportunity__c);
            for(OpportunityLineItem oli : oppWithLineItem.OpportunityLineItems)
            {
                orderItemsForInsert.add(new OrderItem(AvailableQuantity=Quantity,OrderId=o.Id,etc,etc,etc));
            }
        }
          update updateorderList;
        // If we have order line items, insert data
        if(orderItemsForInsert.size() > 0)
        {
            insert orderItemsForInsert;
        }
    }
}
  • June 11, 2019
  • Like
  • 0

I am trying to create orderitems from OpportunityLine items and also creating order on Opportunity. But I am getting the following error
Error: execution of AfterUpdate caused by: System.TypeException: Invalid id value for this SObject type: 00kq0000008mWXjAAM: Class.Autocreation .CreatingOrders:
at this particular line [ordr1.Id = oli.Id;]
Which Id needs to be take, I don't understand Can anyone help me.Thanks inadvance

public static void CreatingOrders(List<Opportunity> newlist){
      set<Id> oppId = new set<Id>();
    for(Opportunity opp : newList){
        oppId.add(opp.id); //Adding Opportunity's to Set.    
         }
    List<Opportunity> oppList = [select id,name,StageName,Accountid, (select Status,Account.name,enddate from Orders)
                                 from Opportunity where Id =: oppId];

     List<OpportunityLineItem> oppList1 = [SELECT id,Quantity,Product2Id,
                                  UnitPrice,Description, TotalPrice,PricebookEntry.Name, PricebookEntry.Product2.Family,
                                  OpportunityId FROM OpportunityLineItem where OpportunityId =: oppId];



    List<Order> insrtordrs = new List<Order>();
    List<OrderItem> insrtordrs1 = new List<OrderItem>();

    for(Opportunity opp1 : oppList){
        for(OpportunityLineItem oli : oppList1 ){  
        if (opp1.Orders.size()>0){
            system.debug('Orders exists*******************' +opp1.Orders);

        } 
        else if(opp1.StageName == 'Closed-Won') {
          Order ordr =new Order();
          ordr.AccountId = opp1.AccountId;
          ordr.OpportunityId = opp1.id;
          ordr.Status = 'Draft';
          ordr.EffectiveDate = system.today();
          //ordr.ContractId = opp1.ContractId; 
          insrtordrs .add(ordr);

            OrderItem ordr1 =new OrderItem();
            ordr1.Id = oli.Id;
            ordr1.PricebookEntryId = oli.PricebookEntryId;
            ordr1.UnitPrice        = oli.UnitPrice;
            ordr1.Description      = oli.Description;
            ordr1.Quantity         = oli.Quantity;
            insrtordrs1 .add(ordr1);  

        }   
       }
    }
    insert insrtordrs ;
    insert insrtordrs1 ;

 }
  • June 04, 2019
  • Like
  • 0
Hi everyone!
              Need help, to capture failed records in batch class.Below  is my code, i am able to capture sucessfull records but unable to capture failed records.
global class updateOppSendPIQReport implements Database.Batchable<SObject>{
    
    global Set<Id> failureIdsSet;

    
    global Database.QueryLocator start(Database.BatchableContext BC)
    { 
        //Fetch records after opportunity stage is set to PIQ Complete
        return Database.getQueryLocator('SELECT ID, StageName__c, SendPIQReport__c, Opportunity__r.id FROM PIQ_Response__c where StageName__c = \'PIQ Complete\' or StageName__c = \'50-PIQ Complete\' ');
              
    }
    
    global void execute(Database.BatchableContext BC, List<PIQ_Response__c> scope){
        
        failureIdsSet = new Set<Id>();

        List<PIQ_Response__c> updatepiq = new List<PIQ_Response__c>();
        for(PIQ_Response__c piq :  scope){
            if(piq.SendPIQReport__c == False && piq.StageName__c == 'PIQ Complete'){
                
                String [] emailList = new List<String>();
                Set<Id> opId = new Set<Id>();
                
                opId.add(piq.Opportunity__r.id);
                //Fetch Opportunity Record
                Opportunity op = [select id, name, AccountID from Opportunity where Id=:opId];
                
                // DML statement
                Database.SaveResult[] srList = Database.update(scope, false);
                
                // Iterate through each returned result
                for (Database.SaveResult sr : srList) {
                    if (sr.isSuccess()) {
                        // Operation was successful, so get the ID of the record that was processed
                        System.debug('Successfull records****************************: ' + sr.getId());
                    }
                    else {
                        // Operation failed, so get all errors                
                        for(Database.Error err : sr.getErrors()) {
                            System.debug('The following error has occurred.');                    
                            System.debug(err.getStatusCode() + ': ' + err.getMessage());
                            System.debug('failed records**************************: ' + err.getFields());
                        }
                    }
                }
                //Fetch Email id of Account Manager
                List<AccountTeamMember> teamList = [ SELECT ID, TeamMemberRole,
                                                    User.Email
                                                    FROM AccountTeamMember
                                                    WHERE AccountID = :op.AccountID 
                                                    AND TeamMemberRole = 'Account Manager'];
                for(AccountTeamMember a1: teamList){
                    emailList.add(a1.User.Email);
                }
                //Fetch Email id of Sales Coordinator
                List<AccountTeamMember> teamList2 = [ SELECT ID, TeamMemberRole,
                                                     User.Email
                                                     FROM AccountTeamMember
                                                     WHERE AccountID = :op.AccountID 
                                                     AND TeamMemberRole = 'Sales Coordinator'];
                for(AccountTeamMember a2: teamList2){
                    emailList.add(a2.User.Email);
                }  
                 List<CustomUsers__c> cu1 = [select UserEmails__c from CustomUsers__c];
                
               
                for(CustomUsers__c u1:cu1){
                     list<string> templist = u1.UserEmails__c.split(',');
                    emailList.addAll(templist);
                     //emailList.add(u1.UserEmails__c); 
                                         system.debug('EmailList'+emailList);
                                     }
                
                String [] emailList2 = new List<String>();
                for (Integer i = 0; i<emailList.size(); i++) {
                    emailList2.add(emailList[i]);
                     system.debug('EmailList**'+emailList2);
                } 
                PIQCOntroller.sendPDf(piq.Id, emailList2);
                piq.SendPIQReport__c = True;
                updatepiq.add(piq);
            } 
        }
        update updatepiq;
        system.debug('updatepiq*******************'+updatepiq);
    }
    
    global void finish(Database.BatchableContext BC)
    {
    }
}
  • May 28, 2019
  • Like
  • 0
Hi,I have an Apex class in which custom settings are used and I am unable cover the code coverage. I am using another apex class testclass so that my actual apex class code coverage increased to 48% only. I am unable increase the code coverage to 75% Please anyone help me out. Thanks in advance

Apex Class:
public class InstallationHelper {

 private static Case_Installation_Settings__c settings;

    public static void markUnitComplete( List<Installation__c> newInstalls, Map<Id, Installation__c> oldInstalls)
    {
        
        Set<Id> completedInstallUnitIds = new Set<Id>();
        List<Unit__c> updateUnits = new List<Unit__c>();

        if ( settings == null ) settings = Case_Installation_Settings__c.getInstance();


        if ( newInstalls != null && newInstalls.size() > 0 )
        {
            for ( Installation__c inst : newInstalls )
            {
                Installation__c oldInst;
                if (oldInstalls != null && oldInstalls.containsKey(inst.Id))
                {
                    oldInst = oldInstalls.get(inst.Id);
                }

                if ( DisplayUtils.hasChanged(oldInst, inst, 'Status__c') && inst.Mark_Unit_Complete__c )
                {
                    if ( inst.Unit__c != null )
                    {
                        completedInstallUnitIds.add( inst.Unit__c );
                    }
                }
            }
            List<Unit__c> unitList =  [SELECT id, name, status__c FROM Unit__c WHERE Id IN :completedInstallUnitIds];
           
            if ( completedInstallUnitIds != null && completedInstallUnitIds.size() > 0 )
            {
                for ( Unit__c u :unitList)
                {
                    u.Status__c = settings.Unit_Installed_Status_Name__c;
                    updateUnits.add( u );
                }
            }

            if ( updateUnits != null && updateUnits.size() > 0 )
            {
                update updateUnits;
                
            }
            
        }
    }
    
      public static void updateScheduleIds(list<Installation__c> newList, map<id,Installation__c> oldlist)
    {
        set<id> accountids = new set<id>();
        map<id,Installation__c> compInst = new map<id,Installation__c>();
        list<Installation__c> updateInstallations = new list<Installation__c>();
        List<Installation__c> insList = [Select id,Site__c,After_PSA_Schedule_created__c FROM Installation__c WHERE Site__c IN:accountids];
        for(Installation__c inst : newList)
        {
            if(inst.Monitoring_hours_changed__c == false && oldlist.get(inst.id).Monitoring_hours_changed__c== true)
            {
                accountids.add(inst.Site__c);
                compInst.put(inst.Site__c,inst);
            }
            else if(inst.After_PSA_Schedule_created__c == true && oldlist.get(inst.id).After_PSA_Schedule_created__c == false)
            {
                accountids.add(inst.Site__c);
                compInst.put(inst.Site__c,inst);
            }
            if(!accountids.isEmpty())
            {
                for(Installation__c ins : insList)
                {
                    if(compInst.get(ins.Site__c).id != ins.id)
                    {
                        Installation__c temp = compInst.get(ins.Site__c);
                        ins.Monday_ScheduleID__c = temp.Monday_ScheduleID__c;
                        ins.Tuesday_ScheduleID__c = temp.Tuesday_ScheduleID__c;
                        ins.Wednesday_ScheduleID__c = temp.Wednesday_ScheduleID__c;
                        ins.Thursday_ScheduleID__c = temp.Thursday_ScheduleID__c;
                        ins.Friday_ScheduleID__c = temp.Friday_ScheduleID__c;
                        ins.Saturday_ScheduleID__c = temp.Saturday_ScheduleID__c;
                        ins.Sunday_ScheduleID__c = temp.Sunday_ScheduleID__c;
                        updateInstallations.add(ins);
                    }
                    else if(ins.After_PSA_Schedule_created__c == true && compInst.get(ins.Site__c).id == ins.id)
                    {
                        ins.After_PSA_Schedule_created__c = false;
                        updateInstallations.add(ins);
                    }
                }
            }
        }
        
        if(!updateInstallations.isEmpty())
            update updateInstallations;
    }

}

Test Class:
@isTest
public with sharing class VFC_MonitoringHours_Ext_Test {
    @TestSetup 
    public static void setupData() {
                  
           
            Account a = new Account();
            a.Name = 'SGI Test One';
            a.Type = 'Customer';
            a.Channel__c = 'Reseller';
            a.Activity_Email__c = 'nopetest@test.com';
            a.RecordType = new RecordType( Name = 'Site' );
            insert a;
            
                    
            
            Contact cnt = new Contact();
            cnt.FirstName = 'Test';
            cnt.LastName = 'Contact';
            cnt.AccountID = a.ID;
            insert cnt;
            
            Opportunity o = new Opportunity();
            o.AccountID = a.ID;
            o.Name = 'SGI Test 1';
            o.StageName = 'Discovery'; // '40-Contracts Signed';
            o.CloseDate = Date.today();
            o.Contract_Expiration_Date__c = Date.today();
            o.RecordTypeId = '012o0000000pmDS';
            o.Billing_Schedule__c = 'Monthly';
            o.Payment_Terms__c = 'NET 15';
            o.PiQ_Contact__c = cnt.ID;
            o.Opp_is_Approved_for_Quote__c = true;
            
            insert o;
            
            Case ca = new Case();
            ca.Type ='Account Change';
            ca.Status ='01-New';
            ca.Subject ='test new';
            ca.Description = 'new Description';
            ca.AccountId= a.id;
            ca.ContactId = cnt.id;  
            insert ca;
            
            Installation__c inst = new Installation__c();
            inst.Name__c ='instal';
            inst.Status__c = '0-New';
            inst.Monitoring_Service__c = 'Live';   
            inst.Site__c = a.Id;
            inst.prior_status__c = 'Suspend';
            inst.prior_monitoring_service__c = 'Client';
            inst.Install_Case__c = ca.id;
            inst.Monitoring_hours_changed__c = true;
            inst.Opportunity__c = o.id;       
            insert inst; 
            inst.Monitoring_hours_changed__c = false;

            o.StageName = 'Installed';
            update o;
         
        }
    }
    }
  • April 01, 2019
  • Like
  • 0
Hi!
I have a master detail relationsip between Installation__c and Account. and ralation field between Installation__c  & Account is Site__c(API name).
I have a picklist (Time Zone) value on Account and Installation__c that are identical.
There are 5 values for the picklist.

Whenever the picklist value changes on Installation__c , I want to update the picklist value on Account  by using apex code only. But i'm getting null value at  insert accountstoUpdate; line.
Can anyone help, thanks in advance.

My apex class:
public class AccountTimeZoneUpdate {
       public static void accountTimeZone(List<Installation__c> newlist){ 
         set<Id> insId = new set<Id>();
        for(Installation__c inst : newList){
            insId.add(inst.id); 
        } 
     List<Installation__c> instList = [select id,Time_Zone__c Name from Installation__c];
          system.debug('installation list:'+instList);
           
           List<Account> accList = [select id,Time_Zone__c,name from  Account where Time_Zone__c =: null];
           
               system.debug('installation list:'+instList);
           List<Account> accountstoUpdate = new List<Account>();
          
           for(Installation__c insVar:instList){
               for(Account a: accList){
         //  Account acc = new Account();
              if(insVar.Time_Zone__c != null && insVar.Time_Zone__c != '') {
                   a.Time_Zone__c = insVar.Time_Zone__c;
                   accountstoUpdate.add(a);
              }
         }  
     }
            insert accountstoUpdate;
           system.debug('accountstoUpdate time:'+accountstoUpdate);
  }
}

My trigger:
trigger InstallationTrigger on Installation__c (after insert, after update) {
       if (Trigger.isAfter && (Trigger.isInsert || Trigger.isUpdate)){
            AccountTimeZoneUpdate.accountTimeZone(trigger.new);
        }
    
  • February 26, 2019
  • Like
  • 0
Hi, 
 I,m unable to get code coverage for sending emailnotification. can anyone help me. Thanks in advance

public class NotificationEmail {
    
     public static void sendNotificationEmail(List<Account> newList2){
          
        map<id,set<string>> AccRecp = new map<id,set<string>>();
       
         for(Account acc2 : newList2)
        {
            if(acc2.Activity_Email__c != null && acc2.Activity_Email__c != '' && acc2.Status__c == true )
            {
                set<string> emailids = new set<string>();
             
                list<string> templist = acc2.Activity_Email__c.split(',');
               
                emailids.addALL(templist);
              
                AccRecp.put(acc2.id,emailids);
               
            }
             
        }
         if(!AccRecp.isEmpty())
        {
            EmailTemplate et = [ Select Body, HtmlValue, Id, Name, Subject from EmailTemplate  where Name='Post Suspension' Limit 1];
            List<Messaging.SingleEmailMessage> theEmails = new list<Messaging.SingleEmailMessage>();
             for(Account ac: newList2)
            {
                if(AccRecp.containsKey(ac.id))
                {
                    set<string> temp = AccRecp.get(ac.Id);
                   
                    list<string> emaillist= new list<string>();
                     emaillist.add(label.Account_team);
                    emaillist.addAll(temp);
                    string body = et.Body;
                    
                    OrgWideEmailAddress[] ar = [select Id,Address from OrgWideEmailAddress where Address = 'abc@company.com' ];
                    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                    mail.setToAddresses(emaillist);
                    mail.setSubject(' Notice of Suspension-' +' '+ ac.Name);
                    mail.setOrgWideEmailAddressId(ar.get(0).id);
                    mail.setPlainTextBody(body);
                    theEmails.add(mail);
                    
                }
            }
        
              if(!theEmails.isEmpty())
            {
                list<Messaging.Email> allMails = new list<Messaging.Email>();
                for( Integer j = 0; j < theEmails.size(); j++ ){
                    allMails.add(theEmails.get(j));
                }
                if(!allMails.isempty())
                    
                {
                    Messaging.SendEmailResult[] results = Messaging.sendEmail( allMails,false );
                    
                    if (results[0].isSuccess()) {
                        
                        
                        system.debug('The email was sent successfully.');
                     } else {
                         system.debug('The email failed to send: '+results[0].getErrors());
                     }
                }
            }
        }
    }
  • February 19, 2019
  • Like
  • 0
Hi,
  I have an  Apex class, While writing the test class I'm able to get the code coverage only 47%. But I was stuck at  this point only
Please, anyone, help on this.
  
My Apex Class
public class updatemonitoringservice{
    public static void UpdateMonitoring(List<Account> newlist){
        //Get list of Account records.        
system.debug('inside helper');        
    set<Id> accId = new set<Id>();
        for(Account acc : newList){
            accId.add(acc.id); //Adding accountId's to Set.      
             }
    List<Account> accList = [select id, Name, Suspend__c,(select id,Status__c,prior_status__c,
                         prior_monitoring_service__c,Monitoring_Service__c from Installations__r) from Account where Id=:accId]; //Fetch Account related Installations.
      map<Id,List<Installation__c>> mapInst = new map<Id,List<Installation__c>>();
        for(Account accVar : accList){
            mapInst.put(accVar.Id,accVar.Installations__r); // addAll Id's & installations to the Map.
        }
  system.debug('mapInst::'+mapInst);
       List<Installation__c> updateInst = new List<Installation__c>();
      List<Installation__c> upInstallation = new List<Installation__c>();
      
        for(Account a : accList){
                                       
           if(a.Suspend__c)
              {
            
                system.debug('a.Suspend__c::'+a.Suspend__c);
               updateInst.addAll(mapInst.get(a.Id));  // get Id's and add to updateInst list.
               
            }
        
           if(!a.Suspend__c)
            {
                system.debug('a.Suspend__c::'+a.Suspend__c);
                upInstallation.addALL(mapInst.get(a.Id)); // get Id's and add to upInstallation list.
            } 
        }
        List<Installation__c> installationsToUpdate = new List<Installation__c>(); //List for updating the record.      
        
        for(Installation__c instVar:updateInst) //if Suspend equals to true update status and monitoring service values & 
                                                // capture old values in prior_status__c and prior_monitoring_service__c.
        {
            system.debug('inside true');
            system.debug('prior_monitoring_service__c::'+instVar.prior_monitoring_service__c);
            system.debug('monitoring_service__c::'+instVar.Monitoring_Service__c);
            
          system.debug('************************');
           system.debug('prior_status__c::'+instVar.prior_status__c);
           system.debug('Status__c::'+instVar.Status__c);
            if(instVar.Status__c !='5-Removed' && instVar.Status__c !='6-Canceled' && instVar.Status__c !='Swapped-Out' 
               && instVar.Status__c !='Abandoned'){
                 
             if(instVar.Status__c !='Suspend')
                instVar.prior_status__c = instVar.Status__c;
               
           // if(instVar.Monitoring_Service__c != 'Client')             
                instVar.prior_monitoring_service__c = instVar.Monitoring_Service__c;          
           
            instVar.Status__c = 'Suspend';
            instVar.Monitoring_Service__c = 'Client';
            installationsToUpdate.add(instVar);
        
          }
        }
        for(Installation__c instVar : upInstallation) //if Suspend equals to false revert old values in status and monitoring fields.
        {
            system.debug('inside false');
            boolean isRemovePriorChanged = true;
            if(instVar.Status__c !='5-Removed' && instVar.Status__c !='6-Canceled' && instVar.Status__c !='Swapped-Out' 
               && instVar.Status__c !='Abandoned'){
              if(instVar.prior_status__c != null && instVar.prior_monitoring_service__c !=null){
                       
                   
                instVar.Status__c =  instVar.prior_status__c ;
                instVar.Monitoring_Service__c = instVar.prior_monitoring_service__c;
                  
            if(isRemovePriorChanged && instVar.Status__c != NULL && instVar.Monitoring_Service__c != NULL)
            {
                instVar.prior_status__c = NULL;
                instVar.prior_monitoring_service__c = NULL;
                system.debug('Priorstatus value::'+instVar.prior_status__c);
                system.debug('Priormoniotoring service value::'+instVar.prior_monitoring_service__c);
            }          
            installationsToUpdate.add(instVar);
          }
         }
        } 
        update installationsToUpdate;    
 }  
}

My Test Class
@isTest
public class updatemonitoringtestclass {
    public static testMethod void testing(){    
      List<Account> acc = new List<Account>();
        Account a1 = new Account();
        a1.Name = 'test';
        a1.Type = 'Prospect';
        a1.Channel__c = 'Direct';
         a1.Suspend__c = true;
        acc.add(a1);
        insert acc;       
       
        Contact con = new Contact();
        con.LastName = 'Vgs';
        insert con;    
        
       Case ca = new Case();
        ca.Type ='Account Change';
        ca.Status ='01-New';
        ca.Subject ='test new';
        ca.Description = 'new Description';
        ca.AccountId= a1.id;
        ca.ContactId = con.id;  
        insert ca;
        
       Opportunity opp = new Opportunity();
        opp.Name = 'test1';
        opp.Type = 'Existing Business';
        opp.CloseDate = system.today();
        opp.StageName = '01-Discovery';
        opp.Prospect_Level__c = 'A';
        opp.LeadSource = 'web';
        opp.AccountId = a1.id; 
        insert opp;
        
       List<Installation__c> instList = new List<Installation__c>();
       Installation__c inst = new Installation__c();
        inst.Name__c ='instal';
        inst.Status__c = 'Suspend';
        inst.Monitoring_Service__c = 'Client';   
         inst.Site__c = a1.id;
        inst.prior_status__c = '0-New';
        inst.prior_monitoring_service__c = 'Live';
        inst.Install_Case__c = ca.id;
         inst.Opportunity__c = opp.id;
        instList.add(inst);
        insert inst;      
        
       a1.Suspend__c = true ;
       update acc;   
        List<Installation__c> instal = [select id,Status__c,prior_status__c,
                         prior_monitoring_service__c,Monitoring_Service__c from Installation__c where Id=:instList];
        for(Installation__c ins : instal){
            System.assertEquals('Suspend',ins.Status__c);
            System.assertEquals('Client',ins.Monitoring_Service__c);
          //  system.assertEquals(ins.Monitoring_Service__c,ins.prior_monitoring_service__c);
           // system.assertEquals(ins.Status__c,ins.prior_status__c);
            a1.Suspend__c=false;
            update acc;
   
                    }
        }     
    }
  • January 29, 2019
  • Like
  • 0
@RestResource(urlMapping='/installs/*')
global class InstallRestAPIs {   
    @HttpGet
    global static Installation__c getInstall( ){
        Installation__c instl;
        try{
               RestRequest req= RestContext.request;
               String accountId= req.requestURI.substring(req.requestURI.lastindexOf('/')+1);
               system.debug('sfAccountId: '+ accountId);
               instl = [select Time_Zone__c from Installation__c where id= :accountId and status__c = 'Installed'];               
           }catch(Exception e){
               system.debug('Error in fetching Account'+e.getMessage());
           }
           return instl;
    }
}

Can anyone help? Thanks in advance
  • January 23, 2019
  • Like
  • 0