function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
BobBob 

Custom Object Trigger Doesn't Work Correctly with Data loader or API

I have a trigger for two custom objects (Extended_Warranty__c & Unit__c) that works perfectly within SFDC. The trigger's function is to find the Order_No__c and Product_Code__c field on the Unit__c object and match it to the Ext_Warranty__c and Product_Code__c fields on the Extended_Warranty__c object. This work perfectly when i edit records within salesforce, but when i tried updating records from the Data Loader or new units are pushed to SFDC via API. Not all of the records are assigned to the correct Order_No__c - Extended_Warranty__c. I was wondering if anyone has heard of this issue. Any help would be greatly appreciated. 
trigger TriggerUpdateUnitExtWarranty on Unit__c (before insert, before update) {
  
  // Step 1: Create a set of all extended warranties of Units to query
  Set<String> extwrnty = new Set<String>();
  
  for (Unit__c newUnit : Trigger.new) {
    if (newUnit.Order_No__c != null) {
      extwrnty.add(newUnit.Order_No__c);    }
  }

  // Step 2: Query for all the Units in Step 1
  List<Extended_Warranty__c> potentialproduct = [SELECT Id, Name,Product_Code__c FROM Extended_Warranty__c
                                 WHERE  Name IN :extwrnty];

  // Step 3: Make a Map that lets you search for units by extended warranty
  Map<String, Extended_Warranty__c> ewrntyMap = new Map<String, Extended_Warranty__c>();
  for (Extended_Warranty__c w : potentialproduct) {
    ewrntyMap.put(w.Product_Code__c, w);
  }

  // Step 4: Get the matching extended warranty in the Map by extended warranty!
  for (Unit__c newUnit : Trigger.new) {
    
    if (newUnit.Ext_Warranty__c == null) {
      Extended_Warranty__c ordnm = ewrntyMap.get(newUnit.Product_Code__c);

  //ordnm is the name of the extended warranty record that is associated with the unit.      
    if (ordnm != null) {
      newUnit.Ext_Warranty__c  = ordnm.Id;
      }
     
    }
  }

}
Mahesh DMahesh D
Hi Bob,

Please make sure that the existing data in Extended Warranty object is proper.

For example:

If you have Extended Warranty :
Prod Code       Name
1                       ABC
1                       BCA

When you try from SFDC it will work properly because you will get only one name and it gets the right one but when you do it form DL where it conatins multiple records and it may populate wrongly.

Please check the data and make sure that Prod Code is unique for every Order Number.

Regards,
Mahesh
BobBob
Thanks I figured it out. I removed the If statement in the  set collection type and it works perfectly. Thanks again