• rajat Maheshwari 6
  • SMARTIE
  • 873 Points
  • Member since 2017

  • Chatter
    Feed
  • 27
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 3
    Questions
  • 264
    Replies
I am getting the above error when running a flow to update records In an object.  The same object has a trigger that updates whenever a record is udated.  Is there a work around for this limit issue in this particular instance? I have a couple of flows that will need to update records on this object but the trigger is getting in the way.  thank you
trigger ServiceBillingsTrigger on Service_Billings__c (after delete, after insert, after update) {
 
  Map<String,Special_Services_Sched__c> spcMap = new Map<String,Special_Services_Sched__c>();
  List<Special_Services_Sched__c> spcList = new List<Special_Services_Sched__c>();

  Map<String,Account> acctMap = new Map<String,Account>();
  List<Account> acctList = new List<Account>();
  
  final Product2 prod = [Select Id, Name From Product2 Where RecordTypeId = '012A0000000IqewIAC' And Name = 'JC' LIMIT 1][0];
  final RecordType inSpecsRt = [Select Id From RecordType WHERE SobjectType='Special_Services_Sched__c' AND Name='Specs' LIMIT 1];
  
  if (trigger.isDelete)
  {
      for (Service_Billings__c s : trigger.old) 
      {
      if(s.Cleaner__c != null)
      {
        if(!acctMap.containsKey(s.Cleaner__c))
        {
          Account clnrAcct = new Account(Id=s.Cleaner__c);
          clnrAcct.Active_Service__c = [Select count() 
                          From Service_Billings__c 
                          Where Active__c=true 
                          And Cleaner__c=:s.Cleaner__c];
          AggregateResult[] groupedResults = [Select SUM(Cleaner_Price__c) 
                          From Service_Billings__c 
                          Where Active__c=true 
                          And Cleaner__c=:s.Cleaner__c];
          clnrAcct.Services_Total__c = Double.valueOf(groupedResults[0].get('expr0'));

          acctMap.put(s.Cleaner__c,clnrAcct);
        }
      }

      if(s.Customer__c != null)
      {
        if(!acctMap.containsKey(s.Customer__c))
        {
          Account custAcct = new Account(Id=s.Customer__c);
          custAcct.Active_Service__c = [Select count() 
                          From Service_Billings__c 
                          Where Active__c=true 
                          And Customer__c=:s.Customer__c];
          AggregateResult[] groupedResults = [Select SUM(Customer_Price__c) 
                          From Service_Billings__c 
                          Where Active__c=true 
                          And Customer__c=:s.Customer__c];
          custAcct.Services_Total__c = Double.valueOf(groupedResults[0].get('expr0'));

          acctMap.put(s.Customer__c,custAcct);
        }
        if(s.Active__c)
        {
          if(s.Service__c == prod.Id)
          {
            for(Special_Services_Sched__c spc : [Select Id 
                                From Special_Services_Sched__c 
                                Where Active__c=true 
                                  And RecordTypeId =:inSpecsRt.Id
                                  And Customer__c=:s.Customer__c])
            {
              if(spcMap.containsKey(spc.Id))
                spcMap.remove(spc.Id);
              spc.Service_Billing__c = s.Id;
              spcMap.put(spc.Id,spc);
            }
          }
        }
      } 
      }    
  } else {

    if(Trigger.isUpdate)
    {
      for(integer x = 0; x < trigger.old.size(); x++)
          {
            if(trigger.old[x].LastBilled__c != trigger.new[x].LastBilled__c)
            {
              // billing Cycle Ignore Request.
            } else {
              Service_Billings__c s = trigger.new[x];
          if(s.Cleaner__c != null)
          {
            if(!acctMap.containsKey(s.Cleaner__c))
            {
              Account clnrAcct = new Account(Id=s.Cleaner__c);
              clnrAcct.Active_Service__c = [Select count() 
                              From Service_Billings__c 
                              Where Active__c=true 
                              And Cleaner__c=:s.Cleaner__c];
              AggregateResult[] groupedResults = [Select SUM(Cleaner_Price__c) 
                              From Service_Billings__c 
                              Where Active__c=true 
                              And Cleaner__c=:s.Cleaner__c];
              clnrAcct.Services_Total__c = Double.valueOf(groupedResults[0].get('expr0'));
              
              acctMap.put(s.Cleaner__c,clnrAcct);
            }
          }
    
          if(s.Customer__c != null)
          {
            if(!acctMap.containsKey(s.Customer__c))
            {
              Account custAcct = new Account(Id=s.Customer__c);
              custAcct.Active_Service__c = [Select count() 
                              From Service_Billings__c 
                              Where Active__c=true 
                              And Customer__c=:s.Customer__c];
              AggregateResult[] groupedResults = [Select SUM(Customer_Price__c) 
                              From Service_Billings__c 
                              Where Active__c=true 
                              And Customer__c=:s.Customer__c];
              custAcct.Services_Total__c = Double.valueOf(groupedResults[0].get('expr0'));
              acctMap.put(s.Customer__c,custAcct);
            }    
            if(s.Active__c)
            {
              if(s.Service__c == prod.Id)
              {
                for(Special_Services_Sched__c spc : [Select Id 
                                    From Special_Services_Sched__c 
                                    Where Active__c=true 
                                      And RecordTypeId =:inSpecsRt.Id
                                      And Customer__c=:s.Customer__c])
                {
                  if(spcMap.containsKey(spc.Id))
                    spcMap.remove(spc.Id);
                  spc.Service_Billing__c = s.Id;
                  spcMap.put(spc.Id,spc);
                }
              }
            }
          } 
        }
          }
    }

    if(Trigger.isInsert)
    {    
        for (Service_Billings__c s : trigger.new) 
        {
        if(s.Cleaner__c != null)
        {
          if(!acctMap.containsKey(s.Cleaner__c))
          {
            Account clnrAcct = new Account(Id=s.Cleaner__c);
            clnrAcct.Active_Service__c = [Select count() 
                            From Service_Billings__c 
                            Where Active__c=true 
                            And Cleaner__c=:s.Cleaner__c];
  
            AggregateResult[] groupedResults = [Select SUM(Cleaner_Price__c) 
                            From Service_Billings__c 
                            Where Active__c=true 
                            And Cleaner__c=:s.Cleaner__c];
            clnrAcct.Services_Total__c = Double.valueOf(groupedResults[0].get('expr0'));

            acctMap.put(s.Cleaner__c,clnrAcct);
          }
        }
  
        if(s.Customer__c != null)
        {
          if(!acctMap.containsKey(s.Customer__c))
          {
            Account custAcct = new Account(Id=s.Customer__c);
            custAcct.Active_Service__c = [Select count() 
                            From Service_Billings__c 
                            Where Active__c=true 
                            And Customer__c=:s.Customer__c];
            AggregateResult[] groupedResults = [Select SUM(Customer_Price__c) 
                            From Service_Billings__c 
                            Where Active__c=true 
                            And Customer__c=:s.Customer__c];
            custAcct.Services_Total__c = Double.valueOf(groupedResults[0].get('expr0'));
            acctMap.put(s.Customer__c,custAcct);
          }  
          if(s.Active__c)
          {
            if(s.Service__c == prod.Id)
            {
              for(Special_Services_Sched__c spc : [Select Id 
                                  From Special_Services_Sched__c 
                                  Where Active__c=true 
                                    And RecordTypeId =:inSpecsRt.Id
                                    And Customer__c=:s.Customer__c])
              {
                if(spcMap.containsKey(spc.Id))
                  spcMap.remove(spc.Id);
                spc.Service_Billing__c = s.Id;
                spcMap.put(spc.Id,spc);
              }
            }
          }
        } 
        }
    }
    }
   
     if(!acctMap.isEmpty())
       acctList.addAll(acctMap.values());
    if(acctList.size() > 0)
      update(acctList);
      
    if(!spcMap.isEmpty())
      spcList.addAll(spcMap.values());
  if(spcList.size() > 0)
    update(spcList);
}

 
I have trouble comparing old and new Account OwnerID. I see an error message saying  "Error: Compile Error: Invalid field OwnerId for SObject User at line 13 column 46". Below is my code. Please assist.
 
trigger ContactOwnerID on Account (After Insert, After Update) {

List<Account>AccList = new List<Account>();
Map<id,user>OldUserMap = new Map<id,user>();
Map<id,user>NewUserMap = new Map<id,user>();
List<Contact>ConList = new List<Contact>();
List<Contact>UpdatedConList = new List<Contact>();
List<Contact>FinalConList = new List<Contact>();



For(Account A:Trigger.new){
If(A.OwnerId != Null && OldUserMap.get(A.id).OwnerId != NewUserMap.get(A.id).OwnerId){
AccList.add(A);
}
If(!AccList.isEmpty()){
ConList =[Select id, OwnerId, AccountId from Contact where AccountId =: AccList];
}
}
If(!ConList.isEmpty()){
For(Contact c:UpdatedConList){
c.OwnerId = c.account.ownerid;
FinalConList.add(c);
}
}
If(!FinalConList.isEmpty()){
Update FinalConList;
}
}

 
Hey, I was given this code to update a date field every night and it works great in my sandbox. But the code they gave me to use for Test Class is not working and giving me errors.

I really need to get this code into production ASAP.

Scheduler Class that's working in my Sandbox;

global class SchedulerToUpdateDate implements Schedulable {
List<Grad_Employment_Detail__c> allRec = new List<Grad_Employment_Detail__c>();
List<Grad_Employment_Detail__c> toUpdate = new List<Grad_Employment_Detail__c>();
    global void  execute(SchedulableContext sc){
        allRec = [select id, current_Date__c from Grad_Employment_Detail__c];
        for(Grad_Employment_Detail__c ge: allRec){
            ge.current_Date__c = date.today();
            toUpdate.add(ge);
        }
        update toUpdate;
    }
}

This is the Test Class that was given, it's not working and giving error. (errors) is at the botom of the code listed)

@IsTest
    public class SchedulerToUpdateDate_Test{
        public static testmethod void unitTest(){            
            Test.starttest();
            Grad_Employment_Detail__c to = new Grad_Employment_Detail__c ();
            to.current_Date__c = date.today();
            insert to;
                SchedulerToUpdateDate wau = new SchedulerToUpdateDate();
                String sch = '0  00 1 3 * ?';
                system.schedule('Test', sch, wau);
            test.stoptest();
        }
    }

The error(s) I'm getting when trying to push into production. I specified this test only;
Method Name = unitTest

Error Message;
System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [Grad_Employment_Details__c]: [Grad_Employment_Details__c] 
Stack Trace: Class.SchedulerToUpdateDate_Test.unitTest: line 7, column 1


 
Please help, I am getting the following errors when I run the unit test:

FATAL_ERROR System.StringException: Invalid id: 
and
FATAL_ERROR External entry point

referencing the submit method in my class.

Class:
public class ContractExtension {

    //private final Hearing_Aids__c ha;

    public final Contact con;
    public List<Hearing_Aids__c> haList {get; set;}
    public List<Hearing_Aids__c> haSelectedList {get; set;}
    public List<WrapperClass> hearingAidWrappers {get; set;}
    public Boolean hearingAidSelection {get; set;}
    public Boolean productSelection {get; set;}
    public List<SelectOption> classOptions {get; set;}
    public String classSelection {get; set;}
    

    public ContractExtension(ApexPages.StandardController stdController) {
        if (!Test.isRunningTest()) { 
        stdController.addFields(new List<String>{'Account.Id','Price_Book__c'});
        hearingAidSelection = true;
        classOptions = new List<SelectOption>();
        classOptions.add(new SelectOption('Gold','Gold'));
        classOptions.add(new SelectOption('Silver','Silver'));
        classSelection = 'Gold';
        }

        //get current contact record
        con = (Contact)stdController.getRecord();
        
        haList = [  SELECT  Id, Name, Battery__c, Class__c, Contact__c, Ear__c, Has_Accessory__c, Invoice_Date__c, Quantity__c, Opportunity__c, 
                            Is_Accessory__c, Manufacturer__c, Manufacturer_Warranty_Expiration__c, Model__c, Related_Hearing_Aid__c, 
                            Serial_Number__c, Related_Hearing_Aid__r.ID, Related_Hearing_Aid__r.Name, SKU__c
                    FROM Hearing_Aids__c 
                    WHERE Contact__c = :con.ID AND Opportunity__c = null];

        hearingAidWrappers = new List<WrapperClass>();
        for(Hearing_Aids__c ha : haList){
            hearingAidWrappers.add(new WrapperClass(ha));
        }
    }

    public void hearingAidSelectionProceed(){

        hearingAidSelection = false;
        integer i = 0;
        while (i < hearingAidWrappers.size()){
            if(hearingAidWrappers[i].associateWithNewContract == false){
                hearingAidWrappers.remove(i);
            }
            i++;
        }
        productSelection = true;
        getProductOptions();
    }

    public PageReference cancel(){
        return new PageReference('/' + con.Id);
    }

    public void getProductOptions(){
        Set<String> classSet = new Set<String>();
        
        //Put each wrapperclass into the three sets
        for(WrapperClass wc : hearingAidWrappers){
            classSet.add(wc.hearingAid.Class__c);
        }

        //query for the product2 records
        List<Product2> prodList =  [SELECT Id, Name, ProductCode, Class__c, Type__c FROM Product2 WHERE Class__c IN :classSet AND Type__c = :classSelection AND isActive = true];
    
        //Organize into Map of List of Product2 records with the id being the combination of class and tier
        Map<String,List<Product2>> prodMap = new Map<String,List<Product2>>();
        for(Product2 prod : prodList){
            if(prodMap.containsKey(prod.Class__c)){
                prodMap.get(prod.Class__c).add(prod);
            } else {
                prodMap.put(prod.Class__c, new List<Product2>{prod});
            }
        }

        //Loop through each Wrapper class again and see if you can find an existing match from the product2 map.  If so, add them all as selectoptions on the wrapper class list of select options
        for(WrapperClass wc : hearingAidWrappers){
            if(prodMap.containsKey(wc.hearingAid.Class__c)){
                for(Product2 prod : prodMap.get(wc.hearingAid.Class__c)){
                    wc.productOptions.add(new SelectOption(prod.Id, prod.Name));
                }
            }
        }
    }

    //Submit
    public PageReference submit(){
        Map<Id,PricebookEntry> pricebookEntriesMap = getPricebookEntries();

        //Create new opportunity
        Opportunity opp = new Opportunity();
        opp.AccountId = con.Account.Id;
        opp.Contact__r.Id = con.Id;
        opp.Name = 'Test Opp';
        opp.StageName = 'Closed Won';
        opp.CloseDate = System.today();
        insert opp;
        //Now that it has been inserted, we are taking the auto number field and setting it as the name
        Opportunity updatedOpp = [SELECT Id, Contract__c, AccountId, Contact__c, Name, StageName, CloseDate FROM Opportunity WHERE Id = :opp.Id];
        opp.Name = updatedOpp.Contract__c;
        update opp;
    
        insert getOlisToInsert(updatedOpp, pricebookEntriesMap);

        //create contact role on opportunity to relate to contact
        OpportunityContactRole ocr = new OpportunityContactRole();
        ocr.ContactId = con.Id;
        ocr.IsPrimary = True;
        ocr.OpportunityId = opp.Id;
        insert ocr;


        //Return to the newly created opportunity
        return new PageReference('/' + opp.Id);
    }

    /**
     * Method to ge the matching pricebookentry records in order to save the correct information on the OLI
     * @return Returns a map of Id and PricebookEntry, the Id is the Product2Id
     */
    public Map<Id,PricebookEntry> getPricebookEntries(){
        Map<Id,PricebookEntry> pricebookEntriesMap = new Map<Id,PriceBookEntry>();
        
        Set<Id> prodIdSet = new Set<Id>();
        for(WrapperClass wrapper : hearingAidWrappers){
          prodIdSet.add(wrapper.selectedProduct);
        }

        Id newLeafPricebookId = [SELECT Id FROM Pricebook2 WHERE Name = 'New Leaf' LIMIT 1].Id;
        for(PricebookEntry pbe : [SELECT Id, Pricebook2Id, Product2Id, ProductCode, UnitPrice FROM PriceBookEntry WHERE isActive = true AND Product2Id IN :prodIdSet AND Pricebook2Id = :newLeafPricebookId]){
            pricebookEntriesMap.put(pbe.Product2Id, pbe);
        }

        return pricebookEntriesMap;
    }

    /**
     * Method to return all of the newly created opportunity line items and update the hearing aids
     * @param  opp                 Parent Opp
     * @param  pricebookEntriesMap Map of pricebook entries in order to 
     * @return                     List of opportunity line items to be updated.
     */


    public List<OpportunityLineItem> getOlisToInsert (Opportunity opp, Map<Id,PricebookEntry> pricebookEntriesMap){
        List<Hearing_Aids__c> hearingAidsToUpdate = new List<Hearing_Aids__c>();
        List<OpportunityLineItem> oliListToInsert = new List<OpportunityLineItem>();
        //Create new opportunity line items (each hearing aid and accessory)
        Integer i = 1;
        
        for(WrapperClass wrapper : hearingAidWrappers){
            Boolean contractAssigned = false;
            PricebookEntry pbe = priceBookEntriesMap.get(wrapper.selectedProduct);
            OpportunityLineItem oli = new OpportunityLineItem();
            oli.OpportunityId = opp.Id;
            oli.Quantity = 1;
            oli.SKU__c = wrapper.hearingAid.SKU__c;
            oli.TotalPrice = pbe.UnitPrice;
            oli.Ear__c = wrapper.hearingAid.Ear__c;
            oli.PriceBookEntryId = pbe.Id;
            oli.Contact_related__c = wrapper.hearingAid.Contact__c;
            oli.Manufacturer__c = wrapper.hearingAid.Manufacturer__c;
            oli.Model__c = wrapper.hearingAid.Model__c;
            
            //Loop through the hearing aids and give priority to left, then right, then the accessories after that
            //Note, this will not ensure that all Left ears are 1 and Right ears are 2, becuase if we have two lefts,
            //then the first would receieve 1, and the second could receive anything after that (and after a right ear too).
            //This will work properly in the normal flow.
            if(wrapper.hearingAid.Is_Accessory__c == false && wrapper.hearingAid.Ear__c == 'Left'){
                oli.Contract__c = opp.Contract__c + '-' + i;
                i++;
            } else if(wrapper.hearingAid.Is_Accessory__c == false && wrapper.hearingAid.Ear__c == 'Right'){
                oli.Contract__c = opp.Contract__c + '-' + i;
                i++;
            } else if(wrapper.hearingAid.Is_Accessory__c == true && wrapper.hearingAid.Ear__c == 'Left'){
                oli.Contract__c = opp.Contract__c + '-' + i;
                i++;
            } else if(wrapper.hearingAid.Is_Accessory__c == true && wrapper.hearingAid.Ear__c == 'Right'){
                oli.Contract__c = opp.Contract__c + '-' + i;
                i++;
            } else {
                oli.Contract__c = opp.Contract__c + '-' + i;            
                i++;
            }

            oliListToInsert.add(oli);
            
            wrapper.hearingAid.Opportunity__c = opp.Id;
            hearingAidsToUpdate.add(wrapper.hearingAid);
        }

        update hearingAidsToUpdate;
        return oliListToInsert;

    }

    //Wrapper class to hold each instance of a hearing aid conversion to an opportunity line item.  This is also where the extra variables that need to be
    //associated with the hearing aid live.
    public class wrapperClass {
        public Hearing_Aids__c hearingAid {get; set;}
        public Boolean associateWithNewContract {get; set;}
        public List<SelectOption> productOptions {get; set;}
        public String selectedProduct {get; set;}

        public wrapperClass(Hearing_Aids__c ha){
            hearingAid = ha;
            associateWithNewContract = true;
            productOptions = new List<SelectOption>();
            selectedProduct = '';
        }
    }


}

Test: @isTest(seeAllData=true)

private class ContractExtensionTest {
    static testMethod void validateOpp() {

        Test.startTest();
        
        Account acc = new Account(Name = 'TestAccount');
        insert acc;

        Contact con = new Contact(LastName='Test',AccountId=acc.ID,RecordTypeId='0127A0000008l3I',Patient_ID__c='1234');
        insert con;
        
        
        ApexPages.StandardController setCon = new ApexPages.StandardController(con); 


        Hearing_Aids__c hal = new Hearing_Aids__c(Contact__c = con.ID, Class__c = 'TIER 1 (BAS)', Ear__c = 'Left', Manufacturer__c = 'TestManu',Model__c = 'TestModel', Serial_Number__c = '12345');
        insert hal;

        Hearing_Aids__c haa = new Hearing_Aids__c(Contact__c = con.ID, Class__c = 'Accessory', Ear__c = 'Left', Manufacturer__c = 'TestManu',Model__c = 'TestModel', Serial_Number__c = '12345');
        insert haa;
        
        ContractExtension ce = new ContractExtension(setCon);
        
        ce.hearingAidSelectionProceed();
        
        ce.getProductOptions();
        
        //ce.getPricebookEntries();
        
        ce.submit();

        List<Opportunity> opp = new List<Opportunity>([SELECT AccountId FROM Opportunity WHERE Contact__c= :con.ID AND CloseDate = Today]);
        
        List<OpportunityLineItem> oli = new List<OpportunityLineItem>([SELECT ID,Manufacturer__c,Model__c,Ear__c,Contact_related__c,OpportunityId FROM OpportunityLineItem WHERE Contact_related__c= :con.ID]);

        System.debug('debug line 1 Opp: '+opp+' Oli: '+oli);
        
        
        Opportunity opp1 = opp.get(0);
        
        OpportunityLineItem oli1 = oli.get(0);

        //update opp;

        //update oli;

        update con;

        System.debug('debug line 2 Opp: '+opp+' Oli: '+oli);
                
        System.assertEquals(hal.Manufacturer__c,oli1.Manufacturer__c);
        
        System.assertEquals(hal.Model__c,oli1.Model__c);

        System.assertEquals(hal.Ear__c,oli1.Ear__c);
        
        
    }
}
Hi,
I am writing a cross object trigger. 
This is my first map: Map<Id,List<Asset>> acc_asset_map = new Map<Id,List<Asset>>();
    for(Id k:account_id){
        List<Asset> asset = new List<Asset>();
        asset = [SELECT Product2Id FROM Asset WHERE AccountId = :k];
        acc_asset_map.put(k,asset);
    }

And this is the second map:      Map<Id,List<OpportunityLineItem>> opp_prod_map = new Map<Id,List<OpportunityLineItem>>();
     for (Id i:opp_id){
         List<OpportunityLineItem> oppLineItem = new List<OpportunityLineItem>();
         oppLineItem = [SELECT Product2Id FROM OpportunityLineItem WHERE OpportunityId = :i];
         opp_prod_map.put(i,oppLineItem);
     }
I want to compare the value of my two maps. So I have a for loop go trough a list of all my AccountId. Then I get all the OpportunityId under each AccountId. With each OpportunityId, I want to check if there is any same Product2Id under my Opportunity and my Asset. Though both of the value I put in my map are 'Product2Id', they are get from different Object types. One is from Asset, and the other is from OpportunityLineItem. 
So am I on the reight direction if I want to check whether the account asset and the opporutnity under that account have the same product?
If so, is there anyway to fix this bug?
Thanks in advance!
Hi all,

Well, I'm in well over my head here :) We have a custom object on our opportunity pages called Financial Projections. This takes data from the opportunity page and performs calculations to show annual revenue and annual gross margin, and then displays them in a related list object.

The problem I've got, apart from the developer having disappeared, is that the financial projection aren't being generated properly.

Basically, if a user completes all the required fields on the opportunity and saves it, the projections will generate correctly.

However, if they don't enter all the fields but move the opp forward a stage, and at that point enter all the required fields, the financial projections doesn't trigger at all.

Finally, and confusingly, if they populate the correct fields at the start, move forward a stage, and then alter the figures, the financial projections will correctly update. 

So, it's almost as if it's a one-chance deal to the trigger the class. Can anyone help? I'll post the trigger below - the class is 650 lines long so I'm not sure an inline paste will work here.

Thanks in advance
Richard

trigger CRMS_OpportunityTrigger on Opportunity (before insert, after insert, after update, before update) 
{
    public static boolean blnUpdate = false;
    //public static integer intCount = 0;
    if(trigger.isInsert && trigger.isBefore)
    {
        CRMS_OpportunityTriggerHandler objClass = new CRMS_OpportunityTriggerHandler();
        objClass.beforeInsert(trigger.new);
    }
    if(trigger.isInsert && trigger.isAfter)
    {
        CRMS_OpportunityTriggerHandler objClass = new CRMS_OpportunityTriggerHandler();
        objClass.afterInsert(trigger.newMap);
    }
    if(trigger.isAfter && trigger.isUpdate)
    {
        //if(intCount <2)
        if(!blnUpdate)
        {
          CRMS_OpportunityTriggerHandler objClass = new CRMS_OpportunityTriggerHandler();
          objClass.afterUpdate(trigger.newMap, trigger.OldMap);
          //intCount = intCount + 1;
          blnUpdate = true;
        }
    }
    if(trigger.isUpdate && trigger.isBefore)
    {
        CRMS_OpportunityTriggerHandler objClass = new CRMS_OpportunityTriggerHandler();
        objClass.beforeUpdate(trigger.newMap, trigger.OldMap);
    }
}
error
//Trigger
trigger BlockContentLtrigger on ContentDocumentLink (before insert) 
{  
    for(ContentDocumentLink  contDocL : Trigger.new)
    {
      if (CDLHelper.isSharingAllowed(contDocL))
     {
          contDocL.addError('stop3 ');        
     }
   }  
}

//Class
public class CDLHelper {
    public static boolean isSharingAllowed(ContentDocumentLink cdl) {
        String docId = cdl.ContentDocumentId;  
        
        ContentVersion version = [select PublishStatus, FileExtension from ContentVersion where ContentDocumentId =: docId].get(0);        
       
        if (version.PublishStatus.equals('P') && (version.FileExtension != null)) {
            return false;
        }
        return true;
    }
}

 
Hello Friends,

I am trying to retrive a data from Custom Object A to Standard Object B

for standard object i can use if function like below

 if(MoreCase.Account.Type != null && MoreCase.Account.Type != '')
            {
                if(MoreCase.Account.Type.contains('Customer')){
                    ShowCustomer = true;
                }else if(MoreCase.Account.Type.Contains('Ex-Customer')){
                    ShowExCustomer = true;

I am using Account object and type is field which standard object but for my custom object and field how would i use 

custom object  API Name - Product_Version_Master__c
field name is - Existing_Version 

how will i use this in my function?

Thanks
 
Hi All,

trigger UpdateActiveProspect on Opportunity (after insert,after update){
 list<account> ali=new list<account>();

  if(trigger.isafter && (trigger.isinsert || trigger.isupdate)){
     list<Opportunity> Opp=new list<Opportunity>();
     List<Opportunity> opp1=new List<Opportunity>();
     set<id> ids=new set<id>(); 
      for(Opportunity o:trigger.new){
       ids.add(o.accountid);
       }
     
     list<account> accli=[select id,name,Account_Status__c,Active_Prospect__c ,(select id,accountID,StageName,Contract_Expiration_Date__c from Opportunities) from account where id=:ids];
     for(account a1:accli){  
          for(Opportunity op:a1.opportunities){
            if(op.stageName=='Intro Meeting / Discovery'||op.stageName=='Relationship Building'||
                op.stageName=='Opportunity Identification'||op.stageName=='Solution/Submit RFI'||
                 op.stageName=='Solution/Submit RFP'||op.stageName=='Solution/Submit Pre-emptive Bid'||
                  op.stageName=='Presentation / Pitching'||op.stageName=='Red Zone / Awarded'){
                  
            opp.add(op);
              }
              if(op.stageName=='Win (Contract Signed)'&& op.Contract_Expiration_Date__c > System.TODAY()){
              opp1.add(op);
            }
            }
            if(opp.size()>0){
            a1.Active_Prospect__c=true;  
            }else{
        a1.Active_Prospect__c=false;

        } 
        if(opp1.Size()>0){
        a1.Account_Status__c='Active';
        }else{
        a1.Account_Status__c='Inactive';
        }
        ali.add(a1);
         
         }          
     }

   update ali;
}

Above is the Trigger. Any one can Help

Thanks In advance
  • March 15, 2017
  • Like
  • 0
Hi All , i created trigger on Opportunity to add a follow up task whenever a new opportunity is created with "StageName = Closed Won". --->

trigger ClosedOpportunityTrigger on Opportunity (after insert , after update) {

list<task> listtask = new list<task>();
for (opportunity opp : trigger.new){

if (opp.StageName == 'Closed Won'){
task NewTask = new task();
task.subject = 'Follow Up Test Task';
task.ActivityDate = system.today().addmonths(1);
task.whatid = opp.Id;
listtask.add(NewTask);
}


}
if (listtask.size()>0)
insert listtask;


}


How ever while saving the trigger i get an error : Error: Compile Error: Expression cannot be assigned at line -1 column -1

Can not seem to move past this , please help also point out if you see any rookie mistakes in the trigger code.

Thanks
Hello,

we have a scheduled apex to ensure that the project role on the contact = the role added to the opportunity.
But that the gap we have today, is that the values on the contact role under opportunity and the values in the project role field does not map. If they are same, this sync would be.

Anyone know how I would sync them. An apex trigger, workflow or formula?

Thank you.
I'm trying to create a custom link button with "execute javascript" behavior. I'm getting error on line 
var cont = records[0].top_firm__r.Coverage_Channel__c;

Coverage_Channel__c is a picklist type field. Query using dev console does not throw an error and there is a value in that field. Also, I see values by doing the console.log(records );  I'm not quite sure why it throws  error "cannot read property 'Coerage_Channel__c' of undefined "
 
{!REQUIRESCRIPT("/soap/ajax/34.0/connection.js")}

 
    var result = sforce.connection.query(
        "SELECT Name,top_firm__r.Coverage_Channel__c " + 
        "FROM Contact " + 
        "WHERE Id = '{!Contact.Id}' " 
    );

    var records = result.getArray("records");

 
    if(records.length != 0){
        var cont = records[0].top_firm__r.Coverage_Channel__c;
window.top.location.href="someting........";
        }

 
  • March 02, 2017
  • Like
  • 0
 I am calling the below class in user after insert trigger, my requirement is to findout if this is the first portal user created for an account. if so I should stamp today's date to a field say first_portal_user_created_date. I know this code is not that efficient as there is SOQL query inside the for loop. Is there a better way of doing this ?  


public class FristPortalUserCreatedDate{

      public static void updateFirstPortalUser(List<User> newUsers) {

    List<Account> AccountsToUpdate = new List<Account>();
        
            for (Integer i = 0; i < newUsers.size(); i++) {
            
                Account selectedAccount = [select id,Portal_user_created_date__c From Account where Id=:newUsers[i].AccountId];
                if(selectedAccount!= NULL &&  selectedAccount.Portal_user_created_date__c=NULL ){

            selectedAccount.Portal_user_created_date__c = system.Today();
            AccountsToUpdate.add(selectedAccount);
                    
                }
            
            }
        Update AccountsToUpdate;
      }
  
  }
I've been trying to figure this error out for a while now and it seems that I just can't figure it out. When adding an opportunitylineitem to an opportunity, I keep receiving the "Attempt to de-reference a null object" error right after the `prod.inventory_forecast__c += (oli.quantity * opps.get(oli.OpportunityId).probability);` line
trigger InventoryForecast on OpportunityLineItem (after update, after insert) {
    
    Product2[] prods;
    Product2 prod;
    
    // creates a map of opportunities
    Set<ID> oppIds = new Set<ID>();
    for(OpportunityLineItem oli : Trigger.new) {oppIds.add(oli.opportunityId);}
    Map<ID, Opportunity> opps = new Map<ID, Opportunity>([SELECT Id, Probability FROM Opportunity WHERE Id IN :oppIds]);
    
    
    // creates a map of products
    Set<ID> prodIds = new Set<ID>();
    for(OpportunityLineItem oli : Trigger.new) {prodIds.add(oli.Product2Id);}
    System.debug(prodIds);
    Map<ID, Product2> prods2 = new Map<ID, Product2>([SELECT Id, inventory_forecast__c FROM Product2 WHERE Id IN :prodIds]);
    
    
    OpportunityLineItem oldOLI, newOLI;
    Decimal diff;
    
    for(OpportunityLineItem oli : Trigger.New){
        
        if(Trigger.isInsert){
            // increase forecast by amount * opp probability
            
            prod = prods2.get(oli.Product2Id);
            System.debug(prod);
            prod.inventory_forecast__c += (oli.quantity * opps.get(oli.OpportunityId).probability);
            
            prods.add(prod);
            
        }
        /*
        if(Trigger.isUpdate){
            // increase of decrease forecast by amount
            // compare Trigger.New to Trigger.Old
        
            // use newMap and oldMap as lists may not have same records and records may not be in same order
            oldOLI = Trigger.oldMap.get(oli.Id);
            newOLI = Trigger.newMap.get(oli.Id);
            
            if(newOLI.quantity == null) {newOLI.quantity = 0;}
            if(oldOLI.quantity == null) {oldOLI.quantity = 0;}
            
            diff = (newOLI.quantity - oldOLI.quantity) * opps.get(oli.OpportunityId).probability;
            
            
            prod = prods2.get(oli.Product2Id);
            prod.inventory_forecast__c += diff;
            
            prods.add(prod);
            
        }
        */
    }
    
    update prods;

}

 
Getting a compile error - Invalid Initial Value Type List for List.  Line 14 (commented below).  In essence, I have a trigger on dsfs__DocuSign_Status__c.  dsfs__DocuSign_Status__c has a field dsfs__Case__c which is an ID of a case.  Anytime the trigger occurs, I want to set the "Status" field on the case identified by dsfs__Case__c to newStatus.  Any thoughts on what I am doing wrong?
public class DocusignStatusUtil {
    public static void updateCaseStatus (List<dsfs__DocuSign_Status__c> envelopes, String newStatus) {
        try {
                Set<Id> st_ParentId = new Set<Id>();
                 for(dsfs__DocuSign_Status__c envelopesEvaluated : envelopes)
                     {
                       st_ParentId.add(envelopesEvaluated.dsfs__Case__c);
                     }

			List<Id> relatedCasesMap;
            if(st_ParentId!=null && !st_ParentId.isEmpty())
               {
//this is where the error is
                	relatedCasesMap = new List<Id>([SELECT Id 
													FROM Case
													WHERE Id IN :st_ParentId limit 1]); 
               }
               
															 
			for (dsfs__DocuSign_Status__c envelopesEvaluated : envelopes) 
            {
               if(relatedCasesMap!=null && relatedCasesMap.containsKey(envelopesEvaluated.dsfs__Case__c))
                  {
                     
				relatedCasesMap.get(envelopesEvaluated.dsfs__Case__c).Status = newStatus;
				
		          }
             }
           

			if(relatedCasesMap!=null && relatedCasesMap.values()!=null)
			   update relatedCasesMap.values();
        
        } catch (Exception e) {
            System.debug('Issue with the Horizon Case Update: ' + e.getMessage());
        }
    }
}


 
Hi,

I creating a trigger, that when an Opportunity are closed, I get some of the data of the fields of that opportunity and send these informations to another system.
But I don't know how get theses fields with APEX.

Can someone help me?

Best Regards
Rafael


 
HI All,

i have a custom table(Social_media__C) which doesn’t have any relationship with opportunity,And i have another custom table partner__c which is related to opportunity,now when first record(on partner__c table) is created related to a opportunity,that first partner__c one of the field value we need to update into Social_media__c’s one of the field.how can we do this?

            first.Created.partner__c.value = Social_media__c.value(no lookup to opportunity)
Hi, 

I have 2 Lookup fields in object. 

I have selected values for 2 lookup fields, and saved. 

Now if i want to edit that record, at that time if i am entering same look up values(not changing lookup values) means it should display an error that "Same set of values are Entered, please change the lookup values" 

I am thinking that we can done this through trigger. 
Can any one help with this scenario.

Thanks in advance.
 
I have to custom objects 1 and 2, 1 is master object, in master object i have a pick list field, now  i want to write a trigger on child obj, when i select obj 1 through lookup from object 2, then parent obj picklist value should populate in child object text field.

Please tell me trigger code,

Thanks in advance.
 
Hello Everyone,

I am trying to create a trigger that updates a picklist field on the Account object whenever that account has a Par_Level__Line__c created for a particular family of products.  The custom object, Par_Level_Lines__c, has a lookup relationship to the Account object.  The custom field on account is named Allocation_Review_Week__c.  Here is the trigger code I have written so far:

 
trigger AllocationReviewWeek on Par_Level_Lines__c (after insert){
    List <ID> AccountsID = new List<ID>();
    for(Par_Level_Lines__c o : Trigger.new){
        if(o.Product_Family__c = 'Our Products' && Par_Level_Lines__c.Account__c.Allocation_Review_Week__c == null){
            AccountsID.add(Par_Level_Lines__c.Account__c.ID);
        }
    }
    List<Accounts> AcctUpdate = [Select id, Par_Level_Lines__c.Account__c FROM Account Where id in : AccountsID];
        for(integer i = 0 ; i < AcctUpdate.size(); i++){
            AcctUpdate[i].Par_Level_Lines__c.Account__c.Allocation_Review_Week__c = "1";
        }
        update AcctUpdate;
}

I keep hitting a compiler error on the 8th line of code.  Thanks in advance for any help.
Hi there,

Hope you are doing great !!!

Could you please help me to resolve this issue  - 

ApexTrigger get delete from "RealDesk"Managed Released Package before 7 days, that need to be undelete but when we click on undelete it giving option "The record you attempted to access has been deleted. The user who deleted this record may be able to recover it from the Recycle Bin. Deleted data is stored in the Recycle Bin for 15 days. " but those trigger Not available in Recycle Bin to recover and those are still accessible with query
"select ID,Name from ApexTrigger where Status='deleted'" 
Id Name
1 01qi0000000jWjIAAU AccountTrigger
2 01qi0000000jWjKAAU TaskTrigger
3 01qi0000000jWjOAAU ContactTrigger

we want those 3 trigger to be undelete.

Thanks
Rajat Maheshwari

 

Hi Team,

Hope you are doing great !!!!

I am stuck at issue : - 
How can I embed Google Map API in an Iframe and show multiple locations in a single map. I found one url which are only working in iframe - 

<apex:iframe src="https://www.google.com/maps/embed/v1/place?q=37.914666450521390,-121.260551330024730&zoom=13&maptype=roadmap&key=APIKEY"></apex:iframe>

but here I am facing problem like, I am only able to see for particular Lat,Long but not for multiples.Could you please help me to showing the google map for multiple lat and long using the url which will work in iframe ?

 

Thanks 

 

Hi,

I am feeling strange issue that, I have created scheduled job to run everyday at 09:00 AM to update the checkbox field on basis of pull out the records on filter criterion from salesforce database.

But Scheduled job page is showing next fire time for the job, but it stuck at queued status even it passed the date.

 

Please help me the same, 

Hi there,

Hope you are doing great !!!

Could you please help me to resolve this issue  - 

ApexTrigger get delete from "RealDesk"Managed Released Package before 7 days, that need to be undelete but when we click on undelete it giving option "The record you attempted to access has been deleted. The user who deleted this record may be able to recover it from the Recycle Bin. Deleted data is stored in the Recycle Bin for 15 days. " but those trigger Not available in Recycle Bin to recover and those are still accessible with query
"select ID,Name from ApexTrigger where Status='deleted'" 
Id Name
1 01qi0000000jWjIAAU AccountTrigger
2 01qi0000000jWjKAAU TaskTrigger
3 01qi0000000jWjOAAU ContactTrigger

we want those 3 trigger to be undelete.

Thanks
Rajat Maheshwari

 
{ "destination_addresses" : [ "Bengaluru, Karnataka, India" ], "origin_addresses" : [ "Hyderabad, Telangana, India" ], "rows" : [ { "elements" : [ { "distance" : { "text" : "576 km", "value" : 575574 }, "duration" : { "text" : "8 hours 33 mins", "value" : 30763 }, "status" : "OK" } ] } ], "status" : "OK" }


Thanks
 
I need to modify our Docusign button , but I'm not sure if it's attainable. Basically , I need the button to be inactive ( annot click) unless 2 checkbox fields on the record are True. Is it possible to add the fields above the Page Call Out?  Thanks ,I'm new to Apex.

{!REQUIRESCRIPT("/apex/dsfs__DocuSign_JavaScript")}
//* iframe check *//
function inIframe() {
try {
return window.self !== window.top;
}
catch(e) {
return true;
}
}
//* iframe check *//
//********* Option Declarations (Do not modify )*********//
var RC = '';var RSL='';var RSRO='';var RROS='';var CCRM='';var CCTM='';var CCNM='';var CRCL='';var CRL='';var OCO='';var DST='';var LA='';var CEM='';var CES='';var STB='';var SSB='';var SES='';var SEM='';var SRS='';var SCS ='';var RES='';
//*************************************************//
DST='{!Order.DocuSign_DST__c}';
CRL='{!Order.DocuSign_CRL__c}';
CCRM='Customer~Signer 1';
//********* Page Callout (Do not modify) *********//
if(inIframe()) {
window.open("{!$Site.BaseUrl}/apex/dsfs__DocuSign_CreateEnvelope?nw=1&DSEID=0&SourceID={!Order.Id}&RC="+RC+"&RSL="+RSL+"&RSRO="+RSRO+"&RROS="+RROS+"&CCRM="+CCRM+"&CCTM="+CCTM+"&CRCL="+CRCL+"&CRL="+CRL+"&OCO="+OCO+"&DST="+DST+"&CCNM="+CCNM+"&LA="+LA+"&CEM="+CEM+"&CES="+CES+"&SRS="+SRS+"&STB="+STB+"&SSB="+SSB+"&SES="+SES+"&SEM="+SEM+"&SRS="+SRS+"&SCS="+SCS+"&RES="+RES,"Popup","location=1,status=1,scrollbars=1,resizable=1,directories=1,toolbar=1,titlebar=1,width=1200");
} else {
window.location.href ="/apex/dsfs__DocuSign_CreateEnvelope?DSEID=0&SourceID={!Order.Id}&RC="+RC+"&RSL="+RSL+"&RSRO="+RSRO+"&RROS="+RROS+"&CCRM="+CCRM+"&CCTM="+CCTM+"&CRCL="+CRCL+"&CRL="+CRL+"&OCO="+OCO+"&DST="+DST+"&CCNM="+CCNM+"&LA="+LA+"&CEM="+CEM+"&CES="+CES+"&SRS="+SRS+"&STB="+STB+"&SSB="+SSB+"&SES="+SES+"&SEM="+SEM+"&SRS="+SRS+"&SCS="+SCS+"&RES="+RES;
}
//*******************************************//
Hello,
Please anyone help me to write test class for execute method and list function! Hear i am give you my full apex class..

APEX Class:
global class CopyLoginHistory  {
   

    public List <LoginHistory> getLoginHistory()
    {
            return [SELECT ApiType,
                                                    ApiVersion,
                                                    Application,
                                                    Browser,
                                                    
                                                    Id,
                                                    ClientVersion,
                                                    LoginType,
                                                    LoginUrl,
                                                    Platform,
                                                    SourceIp,
                                                    Status,
                                                    UserId
                                            FROM LoginHistory
                                            WHERE LoginTime <: System.now()
                                            limit 1000];
    }
    
    public void execute ()
    {
        List <LoginHistory> lh = new List <LoginHistory> ();
        {
            lh = [SELECT ApiType, ApiVersion, Application, Browser, Id, ClientVersion, LoginType, LoginUrl, Platform, SourceIp, Status,
                   UserId FROM LoginHistory WHERE LoginTime <: System.now() limit 1000];
            
            string APIType;
            string APIVersion;
            string App;
            string Browser;
            string ClientVersion;
            string ID1;
           // DateTime LoginTime;
            string LoginType;
            string LoginURL;
            string Platform;
            string SourceIP;
            string Status;
            string UserID;
            
            for (LoginHistory login: lh)
            {
                APIType = login.ApiType;
                APIVersion = login.ApiVersion;
                App = login.Application;
                Browser = login.Browser;
                ID1 = login.Id;
                ClientVersion = login.ClientVersion;
              //  LoginTime = login.LoginTime;
                LoginType = login.LoginType;
                LoginURL = login.LoginUrl;
                Platform = login.Platform;
                SourceIP = login.SourceIp;
                Status = login.Status;
                UserID = login.UserId;
            }
            
            if (!lh.isEmpty())
            {
                List <TrackLoginHistory__c> trl = new List <TrackLoginHistory__c> ();
                User LogUser = [SELECT id, Name, Profile.Name, CompanyName, Email, Address FROM User WHERE ID =: UserID];
                for (LoginHistory login1: lh)
                {                
                    trl.add(new TrackLoginHistory__c (ApiType__c = APIType, 
                                         ApiVersion__c = APIVersion, 
                                         Application__c = App,
                                         Browser__c = Browser, 
                                         ClientVersion__c = ClientVersion, 
                                         ID__c = ID1,
                                        // LoginTime__c = String.valueOf(LoginTime),
                                         LoginType__c = LoginType,
                                         LoginURL__c = LoginURL,
                                         Platform__c = Platform,
                                         SourceIP__c = SourceIP,
                                         Status__c = Status,
                                          UserID__c = LogUser.Name,
                                          Profile__c = LogUser.Profile.Name,
                                          Address__c = String.valueOf(LogUser.Address),
                                          Email__c    = LogUser.Email,
                                          CompanyName__c = LogUser.CompanyName
                                           ));
                                         //UserID__c = UserID ));                
                
                }
                
                insert trl;                                         
            }
        }
    }
}

Thank You!
I am getting the above error when running a flow to update records In an object.  The same object has a trigger that updates whenever a record is udated.  Is there a work around for this limit issue in this particular instance? I have a couple of flows that will need to update records on this object but the trigger is getting in the way.  thank you
trigger ServiceBillingsTrigger on Service_Billings__c (after delete, after insert, after update) {
 
  Map<String,Special_Services_Sched__c> spcMap = new Map<String,Special_Services_Sched__c>();
  List<Special_Services_Sched__c> spcList = new List<Special_Services_Sched__c>();

  Map<String,Account> acctMap = new Map<String,Account>();
  List<Account> acctList = new List<Account>();
  
  final Product2 prod = [Select Id, Name From Product2 Where RecordTypeId = '012A0000000IqewIAC' And Name = 'JC' LIMIT 1][0];
  final RecordType inSpecsRt = [Select Id From RecordType WHERE SobjectType='Special_Services_Sched__c' AND Name='Specs' LIMIT 1];
  
  if (trigger.isDelete)
  {
      for (Service_Billings__c s : trigger.old) 
      {
      if(s.Cleaner__c != null)
      {
        if(!acctMap.containsKey(s.Cleaner__c))
        {
          Account clnrAcct = new Account(Id=s.Cleaner__c);
          clnrAcct.Active_Service__c = [Select count() 
                          From Service_Billings__c 
                          Where Active__c=true 
                          And Cleaner__c=:s.Cleaner__c];
          AggregateResult[] groupedResults = [Select SUM(Cleaner_Price__c) 
                          From Service_Billings__c 
                          Where Active__c=true 
                          And Cleaner__c=:s.Cleaner__c];
          clnrAcct.Services_Total__c = Double.valueOf(groupedResults[0].get('expr0'));

          acctMap.put(s.Cleaner__c,clnrAcct);
        }
      }

      if(s.Customer__c != null)
      {
        if(!acctMap.containsKey(s.Customer__c))
        {
          Account custAcct = new Account(Id=s.Customer__c);
          custAcct.Active_Service__c = [Select count() 
                          From Service_Billings__c 
                          Where Active__c=true 
                          And Customer__c=:s.Customer__c];
          AggregateResult[] groupedResults = [Select SUM(Customer_Price__c) 
                          From Service_Billings__c 
                          Where Active__c=true 
                          And Customer__c=:s.Customer__c];
          custAcct.Services_Total__c = Double.valueOf(groupedResults[0].get('expr0'));

          acctMap.put(s.Customer__c,custAcct);
        }
        if(s.Active__c)
        {
          if(s.Service__c == prod.Id)
          {
            for(Special_Services_Sched__c spc : [Select Id 
                                From Special_Services_Sched__c 
                                Where Active__c=true 
                                  And RecordTypeId =:inSpecsRt.Id
                                  And Customer__c=:s.Customer__c])
            {
              if(spcMap.containsKey(spc.Id))
                spcMap.remove(spc.Id);
              spc.Service_Billing__c = s.Id;
              spcMap.put(spc.Id,spc);
            }
          }
        }
      } 
      }    
  } else {

    if(Trigger.isUpdate)
    {
      for(integer x = 0; x < trigger.old.size(); x++)
          {
            if(trigger.old[x].LastBilled__c != trigger.new[x].LastBilled__c)
            {
              // billing Cycle Ignore Request.
            } else {
              Service_Billings__c s = trigger.new[x];
          if(s.Cleaner__c != null)
          {
            if(!acctMap.containsKey(s.Cleaner__c))
            {
              Account clnrAcct = new Account(Id=s.Cleaner__c);
              clnrAcct.Active_Service__c = [Select count() 
                              From Service_Billings__c 
                              Where Active__c=true 
                              And Cleaner__c=:s.Cleaner__c];
              AggregateResult[] groupedResults = [Select SUM(Cleaner_Price__c) 
                              From Service_Billings__c 
                              Where Active__c=true 
                              And Cleaner__c=:s.Cleaner__c];
              clnrAcct.Services_Total__c = Double.valueOf(groupedResults[0].get('expr0'));
              
              acctMap.put(s.Cleaner__c,clnrAcct);
            }
          }
    
          if(s.Customer__c != null)
          {
            if(!acctMap.containsKey(s.Customer__c))
            {
              Account custAcct = new Account(Id=s.Customer__c);
              custAcct.Active_Service__c = [Select count() 
                              From Service_Billings__c 
                              Where Active__c=true 
                              And Customer__c=:s.Customer__c];
              AggregateResult[] groupedResults = [Select SUM(Customer_Price__c) 
                              From Service_Billings__c 
                              Where Active__c=true 
                              And Customer__c=:s.Customer__c];
              custAcct.Services_Total__c = Double.valueOf(groupedResults[0].get('expr0'));
              acctMap.put(s.Customer__c,custAcct);
            }    
            if(s.Active__c)
            {
              if(s.Service__c == prod.Id)
              {
                for(Special_Services_Sched__c spc : [Select Id 
                                    From Special_Services_Sched__c 
                                    Where Active__c=true 
                                      And RecordTypeId =:inSpecsRt.Id
                                      And Customer__c=:s.Customer__c])
                {
                  if(spcMap.containsKey(spc.Id))
                    spcMap.remove(spc.Id);
                  spc.Service_Billing__c = s.Id;
                  spcMap.put(spc.Id,spc);
                }
              }
            }
          } 
        }
          }
    }

    if(Trigger.isInsert)
    {    
        for (Service_Billings__c s : trigger.new) 
        {
        if(s.Cleaner__c != null)
        {
          if(!acctMap.containsKey(s.Cleaner__c))
          {
            Account clnrAcct = new Account(Id=s.Cleaner__c);
            clnrAcct.Active_Service__c = [Select count() 
                            From Service_Billings__c 
                            Where Active__c=true 
                            And Cleaner__c=:s.Cleaner__c];
  
            AggregateResult[] groupedResults = [Select SUM(Cleaner_Price__c) 
                            From Service_Billings__c 
                            Where Active__c=true 
                            And Cleaner__c=:s.Cleaner__c];
            clnrAcct.Services_Total__c = Double.valueOf(groupedResults[0].get('expr0'));

            acctMap.put(s.Cleaner__c,clnrAcct);
          }
        }
  
        if(s.Customer__c != null)
        {
          if(!acctMap.containsKey(s.Customer__c))
          {
            Account custAcct = new Account(Id=s.Customer__c);
            custAcct.Active_Service__c = [Select count() 
                            From Service_Billings__c 
                            Where Active__c=true 
                            And Customer__c=:s.Customer__c];
            AggregateResult[] groupedResults = [Select SUM(Customer_Price__c) 
                            From Service_Billings__c 
                            Where Active__c=true 
                            And Customer__c=:s.Customer__c];
            custAcct.Services_Total__c = Double.valueOf(groupedResults[0].get('expr0'));
            acctMap.put(s.Customer__c,custAcct);
          }  
          if(s.Active__c)
          {
            if(s.Service__c == prod.Id)
            {
              for(Special_Services_Sched__c spc : [Select Id 
                                  From Special_Services_Sched__c 
                                  Where Active__c=true 
                                    And RecordTypeId =:inSpecsRt.Id
                                    And Customer__c=:s.Customer__c])
              {
                if(spcMap.containsKey(spc.Id))
                  spcMap.remove(spc.Id);
                spc.Service_Billing__c = s.Id;
                spcMap.put(spc.Id,spc);
              }
            }
          }
        } 
        }
    }
    }
   
     if(!acctMap.isEmpty())
       acctList.addAll(acctMap.values());
    if(acctList.size() > 0)
      update(acctList);
      
    if(!spcMap.isEmpty())
      spcList.addAll(spcMap.values());
  if(spcList.size() > 0)
    update(spcList);
}

 
I am able to get an access_token passing SF via HTTP POST. Now that I have the access_token, how do I leverage in the URL to query for case numbers? I want to return "status" for a lookup on the case number that is passed to the API via the IVR. I think the base URL is incorrect for my query... 

I send the folloing to SFDC:
https://login.salesforce.com/services/oauth2/token/
grant_type=password
&client_id=xxxx
&client_secret=xxxx
&username=email@.com
&password=testpwd

and I receive the access_token successfully and I store that value in a variable
I then want to send a url query to SFDC and return all cases for a specific account ... the url that I use for that is where I am lost. What would an example be of the url for this? 

i tried http://instance.salesforce.com/sid=xxxx&case=xxxx
i get the login page for SFDC. I obviously dont understand why I cannot get beyond the access_token being granted ...

Thanks in advance for any guidance,
Patrick
 
Hi All I m getting code coveage error for following lines in test class, can you please hlep

Code Coverage
User-added image





File
Edit
Debug
Test
Workspace
Help
<
>
ProspectingStatusUpdater
TrigToValidateContactRoles
Code Coverage: None
API Version:
Go To
1
trigger TrigToValidateContactRoles on Opportunity (before insert, before update) {
2

3
List<OpportunityContactRole> conRoleList = new List<OpportunityContactRole>();
4

5
Set<Id> ownerIdSet = new Set<Id>();
6

7
for(Opportunity opp : Trigger.new){
8
ownerIdSet.add(opp.ownerId);
9
}
10

11
User loggedInUser = [Select Id, Profile.Name from User where id =: UserInfo.getUserId() limit 1];
12

13
List<User> userList = [Select Id, UserRole.Name, Profile.Name from User where id in: ownerIdSet and UserRole.Name != null];
14

15
if(Trigger.isUpdate)
16
conRoleList = [Select Id, OpportunityId from OpportunityContactRole where OpportunityId in: Trigger.newMap.keySet()];
17

18
for(Opportunity opp : Trigger.new)
19
{
20

21
boolean isVerifyRolesValidation = True;
22

23
if(loggedInUser.Profile.Name.contains('System Administrator') || loggedInUser.Profile.Name.contains('Sales - Executive') || loggedInUser.Profile.Name.contains('Sales Operations - Liz Temp'))
24
{
25
isVerifyRolesValidation = false;
26
}
27
else
28
{
29
for(User u : userList)
30
{
31
if(opp.ownerId == u.Id && u.UserRole.Name.contains('Account Management'))
32
{
33
isVerifyRolesValidation = false;
34
break;
35
}
36
}
37
}
38
if(isVerifyRolesValidation){
39

40
if(opp.Probability >= 50)
41
{
42
if(Trigger.isInsert){
43
opp.addError('Contact Roles must be entered for this Opportunity before the Stage can be changed to Proposal or higher');
44
}
45
if(Trigger.isUpdate)
46
{
47
boolean isValid = false;
48
for(OpportunityContactRole cr : conRoleList){
49
if(opp.Id == cr.OpportunityId){
50
isValid = True;
51
break;
52
}
53
}
54

55
if(!isValid){
56
opp.addError('Contact Roles must be entered for this Opportunity before the Stage can be changed to Proposal or higher');
57
}
58
}
59
}
60
}
61
}
62
}
 


 
I am trying to write a test class for a controller extension and cannot seem to get it to work I keep getting a error: "System.QueryException: List has no rows for assignment to SObject on test class" and cannot figure out why.  My controller and test class are below.

public class HardwareWoSalesOrderLineEdit {
 public HardwareWoSalesOrderLineEdit(ApexPages.StandardController controller) {
     //parent record
  this.proj =[select Sales_Order__c, Id, X2nd_Sales_Order__c From Work_Order__c Where Id = :ApexPages.currentPage().getParameters().get('id')];    
     // child records
     this.line = [ SELECT SCMC__Quantity__c, Item_Name__c,SCMC__Quantity_Shipped__c, Category__c,     SCMC__Item_Description__c, PM_Ordering_Details__c, Quantity_to_Ship__c, Remaining_Quantity__c  
      FROM SCMC__Sales_Order_Line_Item__c
      WHERE (Item_Type__c = 'Hardware'   AND SCMC__Status__c != 'Completed' AND SCMC__Status__c != 'Shipped' AND Category__c != 'Physical Install' AND SCMC__Status__c != 'Cancelled' AND SCMC__Sales_Order__c = :proj.Sales_Order__c) OR
             (Item_Type__c = 'Hardware'   AND SCMC__Status__c != 'Completed' AND SCMC__Status__c != 'Shipped' AND Category__c != 'Physical Install' AND SCMC__Status__c != 'Cancelled' AND SCMC__Sales_Order__c = :proj.X2nd_Sales_Order__c)  ORDER BY Category__c ASC   ];     
     }
    //get sales order lines                 
  public SCMC__Sales_Order_Line_Item__c[] getline() { 
  return this.line; 
 } 
    
 // save method to save changes to the sales order lines
 public pagereference saveChanges() { 
  upsert this.line;
  pageRef.setRedirect(true); 
return pageRef;
 }
    
 // class variables
public PageReference pageRef = new PageReference(ApexPages.currentPage().getUrl()); 
public Work_Order__c proj;
public SCMC__Sales_Order_Line_Item__c[] line; 

}



TEST CLASS 

@istest(seealldata=true)
public class HardwareWoSalesOrderLineEditTest{
    static testMethod void HardwareWoSalesOrderLineEditTest(){
        Test.startTest();
        SCMC__Sales_Order_Line_Item__c sol = [Select Id, SCMC__Item_Master__c, SCMC__Sales_Order__c, SCMC__Sales_Order__r.Installation__c, CreatedById,
                                              SCMC__Sales_Order__r.SCMC__Customer_Account__c
                                              from SCMC__Sales_Order_Line_Item__c where Item_Type__c = 'Hardware'   AND SCMC__Status__c != 'Completed'
                                              AND SCMC__Status__c != 'Shipped' AND Category__c != 'Physical Install' limit 1];
        system.assertnotEquals(null, sol);
        system.debug(sol.Id);
        
        
        Work_Order__c wo = new Work_Order__c(
            Account__c = sol.SCMC__Sales_Order__r.SCMC__Customer_Account__c,
            Sales_Order__c = sol.SCMC__Sales_Order__c,
            Installation__c = sol.SCMC__Sales_Order__r.Installation__c,
            Resource__c = sol.CreatedById,
            Type__c = 'Hardware Order',
            Start_Date__c = system.today(),
            Due_Date__c = system.today(),
            Confirm_address_is_correct__c = true,
            RecordTypeId = '01234000000Bmk8',
            Name = 'testwo123');{
                insert wo;}
        
        system.assertnotEquals(null, wo);
        system.debug(wo.Id);

        Work_Order__c w = [Select Id from Work_Order__c Where Name = 'testwo123' Limit 1]; 

            
        
        system.assertnotEquals(null, w);
        system.debug(w);
        Test.setCurrentPage(Page.HardwareWoSalesOrderLineEdit);
        ApexPages.Standardcontroller sc = new ApexPages.Standardcontroller(w);
        system.debug(sc);
        HardwareWoSalesOrderLineEdit myPageCon = new HardwareWoSalesOrderLineEdit(sc);
        system.debug(myPageCon);
        myPageCon.getline().add(sol);
        myPageCon.saveChanges();
        Test.stopTest();
    }      
}
I have trouble comparing old and new Account OwnerID. I see an error message saying  "Error: Compile Error: Invalid field OwnerId for SObject User at line 13 column 46". Below is my code. Please assist.
 
trigger ContactOwnerID on Account (After Insert, After Update) {

List<Account>AccList = new List<Account>();
Map<id,user>OldUserMap = new Map<id,user>();
Map<id,user>NewUserMap = new Map<id,user>();
List<Contact>ConList = new List<Contact>();
List<Contact>UpdatedConList = new List<Contact>();
List<Contact>FinalConList = new List<Contact>();



For(Account A:Trigger.new){
If(A.OwnerId != Null && OldUserMap.get(A.id).OwnerId != NewUserMap.get(A.id).OwnerId){
AccList.add(A);
}
If(!AccList.isEmpty()){
ConList =[Select id, OwnerId, AccountId from Contact where AccountId =: AccList];
}
}
If(!ConList.isEmpty()){
For(Contact c:UpdatedConList){
c.OwnerId = c.account.ownerid;
FinalConList.add(c);
}
}
If(!FinalConList.isEmpty()){
Update FinalConList;
}
}

 
Hey, I was given this code to update a date field every night and it works great in my sandbox. But the code they gave me to use for Test Class is not working and giving me errors.

I really need to get this code into production ASAP.

Scheduler Class that's working in my Sandbox;

global class SchedulerToUpdateDate implements Schedulable {
List<Grad_Employment_Detail__c> allRec = new List<Grad_Employment_Detail__c>();
List<Grad_Employment_Detail__c> toUpdate = new List<Grad_Employment_Detail__c>();
    global void  execute(SchedulableContext sc){
        allRec = [select id, current_Date__c from Grad_Employment_Detail__c];
        for(Grad_Employment_Detail__c ge: allRec){
            ge.current_Date__c = date.today();
            toUpdate.add(ge);
        }
        update toUpdate;
    }
}

This is the Test Class that was given, it's not working and giving error. (errors) is at the botom of the code listed)

@IsTest
    public class SchedulerToUpdateDate_Test{
        public static testmethod void unitTest(){            
            Test.starttest();
            Grad_Employment_Detail__c to = new Grad_Employment_Detail__c ();
            to.current_Date__c = date.today();
            insert to;
                SchedulerToUpdateDate wau = new SchedulerToUpdateDate();
                String sch = '0  00 1 3 * ?';
                system.schedule('Test', sch, wau);
            test.stoptest();
        }
    }

The error(s) I'm getting when trying to push into production. I specified this test only;
Method Name = unitTest

Error Message;
System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [Grad_Employment_Details__c]: [Grad_Employment_Details__c] 
Stack Trace: Class.SchedulerToUpdateDate_Test.unitTest: line 7, column 1


 
i have requirement where i show all recent items so i use this query on query editor SELECT Id,type, Name FROM RecentlyViewed  ORDER BY LastViewedDate DESC ] it is working fine on my org but on another org it is not showing recent view record. it showing only contact record why?
 
Hi,

I am having a trigger referred in a class which works fine , but fails in some cases , I would like to convert that class to a batch class and use it in my trigger

Kindly help me pls

 
MY TRIGGER CODE:

trigger ContractTrigger on Contract__c(After Update,After Insert) {    
    try{
        Trigger_Status__c ts = Trigger_Status__c.getValues('ContractTrigger');
        if(ts.Active__c){
            
            if(Trigger.isUpdate){

                TravelFundHandler.ValidateContractTermination(Trigger.New,Trigger.oldMap);
                ContractTriggerHandler.ContractfieldsupdateonAccount(Trigger.New, Trigger.oldMap);
                ContractTriggerHandler.contractcommencementdate(Trigger.New, Trigger.oldMap);
                ContractTriggerHandler.contractexpirydate(Trigger.New, Trigger.oldMap);
                 
            }  
            if(Trigger.isInsert){

                
                TravelFundHandler.travelFundMethod(Trigger.New,Trigger.oldMap);
              
            } 
            if(Trigger.isUpdate && TravelFundHandler.firstRun){
                TravelFundHandler.firstRun=false;
                TravelFundHandler.SignOnMethod(Trigger.New,Trigger.oldMap);
                
            }
          
           
            
        }
        
    }catch(Exception e){
        System.debug('Error Occured From Contract Trigger: '+e.getMessage());
    }
}
 
MY CLASS CODE :



public class triggerhandler{   
  
     
       public static void ContractfieldsupdateonAccount(List<Contract__c> newList, Map<Id, Contract__c> oldMap){
         
            Map<Id, Date> accMaptomaxcontractenddate = new Map<Id, Date>();
            Set<Id> accIds = new Set<Id>();
            List<Account> updateAcccontinfo = new List<Account>();
            Date d;
                
                        //Collecting the Account information from the Contract where the Status is 'Signed by Customer'
                        
                        for(Contract__c contr: newList){
        
                  if(contr.Status__c == 'Signed by Customer') 
                
                accIds.add(contr.Account__c);
                
                  System.debug('Account Ids: '+accIds);

                AggregateResult[] groupedResults = [SELECT Id,Account__c,MAX(Contract_End_Date__c)  
  FROM Contract__c where Account__c IN :accIds and Contracted__c = TRUE group by Account__c,Id ORDER BY MAX(Contract_End_Date__c) DESC NULLS LAST LIMIT 1]; 
                     // To get the Maximum contract end date of the Active (End Date > Today > Start date) Contract
            
                     for(AggregateResult ar :groupedResults){
  
  d = (Date)ar.get('expr0');
 System.debug('Maximum Contract End date: '+d);
  accMaptomaxcontractenddate.put((Id)ar.get('Account__c'),(Date)ar.get('expr0'));
  System.debug('Accmap for contracted Maximum Contract End date: : '+accMaptomaxcontractenddate);
  }
                   // To get the Account information associated to the Maximum contract end date of the Active (End Date > Today > Start date) Contract 
                   Map<id,Account> accMaptocontractfields = new Map<id,Account>();
            
                    
                   accMaptocontractfields = new Map<Id, Account>([SELECT Id, Contract_Start_Date__c, Contract_End_Date__c, Contract_Commencement_Date__c, 
                   Contract_Expiry_Date__c, No_of_Contracts__c,Qantas_Annual_Expenditure__c,Contract_Term_in_Months__c,Domestic_Annual_Share__c, International_Annual_Share__c,
                   Unit_Spend_per_term__c, Contracted__c,(SELECT Id, Contract_Start_Date__c, Contracted__c, Contract_End_Date__c, 
                   Domestic_Annual_Share__c, International_Annual_Share__c, Type__c,Qantas_Annual_Expenditure__c,Contract_Term_in_Months__c,
                   Unit_Spend_per_term__c  FROM Contracts__r where (Contract_End_Date__c = :d AND Contracted__c = TRUE) ORDER BY CreatedDate DESC NULLS LAST limit 1 ) FROM Account where Id IN : accIds ]);
                   
                  System.debug('Account map for contract end date:'+accMaptocontractfields);
                    
                     // To get the Contract associated to the Account from the map mentioned above
                  
                  Account acco = accMaptocontractfields.get(contr.Account__c);
                    
                             Date startDate,endDate;
                             Decimal domShare, intShare, unitspend,qantasannual,term;
                             String type;
                             Boolean contracted = false;
                    
                      for(Contract__c contr1 : acco.Contracts__r){
                          
                                  
                                   if(startDate == null && endDate == null){
                                        
                                        startDate = contr1.Contract_Start_Date__c;
                                        endDate = contr1.Contract_End_Date__c;
                                        domShare = contr1.Domestic_Annual_Share__c;
                                        intShare = contr1.International_Annual_Share__c;
                                        unitspend = contr1.Unit_Spend_per_term__c;
                                        qantasannual = contr1.Qantas_Annual_Expenditure__c;
                                        type = contr1.Type__c;
                                        term = contr1.Contract_Term_in_Months__c;
                                        contracted = contr1.Contracted__c;
                                        
                                    }else if(startDate.daysBetween(endDate) < contr1.Contract_Start_Date__c.daysBetween(contr1.Contract_End_Date__c)){
                                        
                                        startDate = contr1.Contract_Start_Date__c;
                                        endDate = contr1.Contract_End_Date__c;
                                        domShare = contr1.Domestic_Annual_Share__c;
                                        intShare = contr1.International_Annual_Share__c;
                                        unitspend = contr1.Unit_Spend_per_term__c;
                                        qantasannual = contr1.Qantas_Annual_Expenditure__c;
                                        type = contr1.Type__c;
                                        term = contr1.Contract_Term_in_Months__c;
                                        contracted = contr1.Contracted__c;
                                    }                                
                                 
                             }
                             
                    //Setting the Highest end date Active Contract information on Account 
                 
                    acco.Contract_Start_Date__c = startDate;
                    acco.Contract_End_Date__c = endDate;
                    acco.Domestic_Annual_Share__c =  domShare;
                    acco.International_Annual_Share__c = intShare;
                    acco.Type__c = type  ;
                    acco.Qantas_Annual_Expenditure__c = qantasannual;
                    acco.Contract_Term_in_Months__c =  term;
                    acco.Unit_Spend_per_term__c = unitspend;
                    acco.Contracted__c =    contracted;
                    
                    
                    System.debug('Account Contract Start Date: '+  acco.Contract_Start_Date__c );
                    System.debug('Account Contract End date: '+acco.Contract_End_Date__c);
                    System.debug('Contract Term in Months: '+acco.Contract_Term_in_Months__c);
                    System.debug('Units spend per term: '+acco.Unit_Spend_per_term__c);
                    System.debug('Account Contract Category: '+acco.Type__c);
                    System.debug('Forecast QF Spend: '  +acco.Qantas_Annual_Expenditure__c);
                    System.debug('Forecast QF Share (Dom) [System]: '+acco.Domestic_Annual_Share__c);
                    System.debug('Forecast QF Share (Int) [System]: '+acco.International_Annual_Share__c);
                    System.debug('Contracted:'+acco.Contracted__c);
                    
                      updateAcccontinfo.add(acco);
                    }

         
                    
            try{
          
            Database.SaveResult[] srlist = Database.Update(updateAcccontinfo, false);
                for (Database.SaveResult sr : srlist){
if (!sr.isSuccess()) {
    
    // Updation failed due to duplicate detected
    for(Database.Error duplicateError : sr.getErrors()){
        Datacloud.DuplicateResult duplicateResult = 
                  ((Database.DuplicateError)duplicateError).getDuplicateResult();
        System.debug('Duplicate records have been detected by ' + 
                  duplicateResult.getDuplicateRule());
        System.debug(duplicateResult.getErrorMessage());
    }

    // If the duplicate rule is an alert rule, we can try to bypass it
    Database.DMLOptions dml = new Database.DMLOptions(); 
    dml.DuplicateRuleHeader.AllowSave = true;
    Database.SaveResult[] sr2list = Database.Update(updateAcccontinfo, dml);
     for (Database.SaveResult sr2 : sr2list){
    if (sr2.isSuccess()) {
        System.debug('Duplicate account has been updated in Salesforce!');
    }
}
}
}
            }

catch(Exception e){
               System.debug(' Exception Occured: '+e.getMessage());
               }
        }
        
        /* This method is being used to populate the Account fields "Contract Commencement Date" of the 
      Minimum contract start date with the status "Signed by Customer" */
        
        public static void contractcommencementdate(List<Contract__c> newList, Map<Id, Contract__c> oldMap){
           
            Map<Id, Date> accMaptomincontractstartdate = new Map<Id, Date>();
            Set<Id> accoIds = new Set<Id>();
            List<Account> updateAcccommdate = new List<Account>();
            Date d;
            Date commencementDate;
            
            //Collecting the Account information from the Contract where the Status is 'Signed by Customer'
        
         for(Contract__c contr: newList){
           
         if(contr.Status__c == 'Signed by Customer' ) 
                
            accoIds.add(contr.Account__c);
    
             // To get the Minimum contract start date of the ""Signed by Customer" Contract    
             
            AggregateResult[] groupedResults = [SELECT Id,Account__c, MIN(Contract_Start_Date__c)  
  FROM Contract__c where Account__c IN :accoIds and Status__c = 'Signed by Customer' group by Account__c,Id ORDER BY MIN(Contract_Start_Date__c) ASC NULLS LAST LIMIT 1];
          
  for(AggregateResult ar : groupedResults){
      accMaptomincontractstartdate.put((Id)ar.get('Account__c'),(Date)ar.get('expr0'));
      
      System.debug('Accmap for Minimum Contract Start date: : '+accMaptomincontractstartdate);
      d=(Date)ar.get('expr0');
      System.debug('Least Commencement Date: '+d);
     }
                 
                 // To get the Account information associated to the Minimum contract start date of the "Signed by Customer" Contract
                 Map<id,Account> accMaptocommencementdate = new Map<id,Account>();
     
                     accMaptocommencementdate = new Map<Id, Account>([SELECT Id, Contract_Start_Date__c, Contract_End_Date__c, Contract_Commencement_Date__c, 
                   Contract_Expiry_Date__c, No_of_Contracts__c,Qantas_Annual_Expenditure__c,Contract_Term_in_Months__c,Domestic_Annual_Share__c, International_Annual_Share__c,
                   Unit_Spend_per_term__c, Contracted__c,(SELECT Id, Contract_Start_Date__c, Contracted__c, Contract_End_Date__c, 
                   Domestic_Annual_Share__c, International_Annual_Share__c, Type__c,Qantas_Annual_Expenditure__c,Contract_Term_in_Months__c,
                   Unit_Spend_per_term__c  FROM Contracts__r where (Contract_Start_Date__c = :d and Status__c = 'Signed by Customer')limit 1 ) FROM Account where Id IN : accoIds]);
  
   
               // To get the Contract associated to the Account from the map mentioned above
   Account accou = accMaptocommencementdate.get(contr.Account__c);
  
  for(Contract__c contr2 : accou.Contracts__r){
  commencementDate = contr2.Contract_Start_Date__c;
  }
  
  //Setting the Minimum Contract start date to the Account Contract commencement date
 
 accou.Contract_Commencement_Date__c =  commencementDate;
 
 System.debug('Account Contract Commenecement Date:'+accou.Contract_Commencement_Date__c);
     updateAcccommdate.add(accou);
      }
           
 
     
        
            try{
          
            Database.SaveResult[] srlist = Database.Update(updateAcccommdate, false);
                for (Database.SaveResult sr : srlist){
if (!sr.isSuccess()) {
    
    // Updation failed due to duplicate detected
    for(Database.Error duplicateError : sr.getErrors()){
        Datacloud.DuplicateResult duplicateResult = 
                  ((Database.DuplicateError)duplicateError).getDuplicateResult();
        System.debug('Duplicate records have been detected by ' + 
                  duplicateResult.getDuplicateRule());
        System.debug(duplicateResult.getErrorMessage());
    }

    // If the duplicate rule is an alert rule, we can try to bypass it
    Database.DMLOptions dml = new Database.DMLOptions(); 
    dml.DuplicateRuleHeader.AllowSave = true;
    Database.SaveResult[] sr2list = Database.Update(updateAcccommdate, dml);
     for (Database.SaveResult sr2 : sr2list){
    if (sr2.isSuccess()) {
        System.debug('Duplicate account has been updated in Salesforce!');
    }
}
}
}
            }

catch(Exception e){
               System.debug(' Exception Occured: '+e.getMessage());
               }
        }
        
        
         public static void contractexpirydate(List<Contract__c> newList, Map<Id, Contract__c> oldMap){
         
          Map<Id, Date> accMaptomaxcontractexpdate = new Map<Id, Date>();
          Set<Id> accIds = new Set<Id>();
          List<Account> updateAccexpdate = new List<Account>();
          Date d;
          Date expiryDate;
        
                //Collecting the Account information from the Contract where the Status is 'Signed by Customer'
                for(Contract__c contr: newList){
                   
                if(contr.Status__c == 'Signed by Customer' ) 
                
                accIds.add(contr.Account__c);
          
                
        
            // To get the Maximum contract end date of the ""Signed by Customer" Contract

          AggregateResult[] groupedResults =  [SELECT Id,Account__c, MAX(Contract_End_Date__c)
  FROM Contract__c where Account__c IN :accIds and Status__c = 'Signed by Customer' group by Account__c,Id Order by MAX(Contract_End_Date__c) DESC NULLS LAST LIMIT 1];         
            
                     for(AggregateResult ar : groupedResults){
      accMaptomaxcontractexpdate.put((Id)ar.get('Account__c'),(Date)ar.get('expr0'));
      
        System.debug('Accmap for Maximum Contract End date: : '+accMaptomaxcontractexpdate);
        
      d=(Date)ar.get('expr0');
      
      System.debug('Highest Expiry Date: '+d);
      
  }
  
  // To get the Account information associated to the Maximum contract end date of the ""Signed by Customer" Contract
  
   Map<id,Account> accMaptoExpirydate = new Map<id,Account>();
   
          accMaptoExpirydate = new Map<Id, Account>([SELECT Id, Contract_Start_Date__c, Contract_End_Date__c, Contract_Commencement_Date__c, 
                   Contract_Expiry_Date__c, No_of_Contracts__c,Qantas_Annual_Expenditure__c,Contract_Term_in_Months__c,Domestic_Annual_Share__c, International_Annual_Share__c,
                   Unit_Spend_per_term__c, Contracted__c, Account_Contract_No__c,(SELECT Id, Contract_Start_Date__c, Contracted__c, Contract_End_Date__c, 
                   Domestic_Annual_Share__c, International_Annual_Share__c, Type__c,Qantas_Annual_Expenditure__c,Contract_Term_in_Months__c,
                   Unit_Spend_per_term__c,Contract_Number__c FROM Contracts__r where (Contract_End_Date__c = :d and Status__c = 'Signed by Customer')ORDER BY CreatedDate DESC NULLS LAST limit 1) FROM Account where Id IN : accIds ]);
  
  
  // To get the Contract associated to the Account from the map mentioned above

  
   Account accoun = accMaptoExpirydate.get(contr.Account__c);
   
   String Accconno;
   
     for(Contract__c contr2 : accoun.Contracts__r){
         Accconno = contr2.Contract_Number__c;
  expiryDate = contr2.Contract_End_Date__c;
  }
  
    //Setting the Maximum Contract end date to the Account Contract commencement date
   
   accoun.Contract_Expiry_Date__c = expiryDate;
   accoun.Account_Contract_No__c = Accconno;
 
System.debug('Account Contract Expiry Date:'+ accoun.Contract_Expiry_Date__c);
System.debug('Account Contract No: '+  accoun.Account_Contract_No__c);
 updateAccexpdate.add(accoun);
      
        }
        

       
            try{
          
            Database.SaveResult[] srlist = Database.Update(updateAccexpdate, false);
                for (Database.SaveResult sr : srlist){
if (!sr.isSuccess()) {
    
    // Updation failed due to duplicate detected
    for(Database.Error duplicateError : sr.getErrors()){
        Datacloud.DuplicateResult duplicateResult = 
                  ((Database.DuplicateError)duplicateError).getDuplicateResult();
        System.debug('Duplicate records have been detected by ' + 
                  duplicateResult.getDuplicateRule());
        System.debug(duplicateResult.getErrorMessage());
    }

 
    Database.DMLOptions dml = new Database.DMLOptions(); 
    dml.DuplicateRuleHeader.AllowSave = true;
    Database.SaveResult[] sr2list = Database.Update(updateAccexpdate, dml);
     for (Database.SaveResult sr2 : sr2list){
    if (sr2.isSuccess()) {
        System.debug('Duplicate account has been updated in Salesforce!');
    }
}
}
}
            }

catch(Exception e){
               System.debug(' Exception Occured: '+e.getMessage());
               }
        }
        
    }

Kindly help me pls

Thanks in advance

Hi all,

We are currently using the email to case functionality within our business and have a customer at the moment who is sending us multiple cases per day that we simply need to log and report on. The problem is that they auto generate their emails from their system and as such hold all the detail in the email body. These generally are like:

Patient Name:
Address:
Town:
Post Code:

etc

I was wondering if i could use a workflow or trigger to automatically take this data out of the email body and populate some custom fields?

Any help or direction would be greatly appreciated

I know almost nothing about Apex and looking for help. I know for this use case I will need a Trigger, however. 

Here's the use case: 

My company has 8 oven slots(manufacturing), and 2 cycle AM and PM for a total of 16 total usable slots(8 each cycle). I need to measure the success rate of each slot during the AM and PM based on the # of orders gone into the specific slot. 


Here is how i've set it up thus far: 
I have a child related list (Audits__c) to a master (Order_Summary__c). Each "audit" record has a field "AM Oven Slot__c" and "PM Oven Slot__c" both are ranged 1-8 in a picklist, and finally there is a "Outcome_Result__c" picklist field with "Good" and "Fail" 

I have already used 16/25 rollup summaries to count the # of line items that go into each tray in the AM and PM, respectively. 

Now, I need a Trigger to COUNT the number of "Good" Outcome_Result__c for each respective tray # and update the respective number field. 
For example, it will SUM the # of "good" outcome results for Tray 1, and then insert that number into "Total Successful outcomes AM Tray 1" 

I think I need to do a BEFORE trigger since I don't need to utilize the record ID, and a list?? 

Help? 

Hi Salesforce gurus,

I am looking to extract the description of Custom fields of a/multiple object from the org.
basically i am trying to get a spreadsheet with the object name, field name and Description of the field.

I tried the below but have reached a dead end
>Getdescribe Apex calls - the Description is missing from the .getdescribe call
>Tried using the metadata API from this link :https://salesforce.stackexchange.com/questions/141251/query-name-help-text-description-of-custom-fields-in-a-custom-object  - but the api was not installed completely as it faced more than 30000 in apex code for 5-6 classes.
>querying the Field Definition object from workbench - again this object omits the Description field in the object
>inlineHelpText field is useless, as the field havent been used in the org like the description Text box of custom fields.

Any idea where the Description for a custom field is stored ,there has to be some metadata object or any other way to get the description.

Thanks in Advance.
 
  • April 20, 2017
  • Like
  • 0
I am new to wave analytics ,
How to bind two datasets in a single dashboards