trigger purchaseinventorytrigger on KBT_Purchase_History__c (after insert ,after update) {     for (KBT_Purchase_History__c ph: Trigger.New) {         System.debug('Trigger.New List' + Trigger.New);          List&lt;KBT_Inventory_Stock__c&gt; currentstock =new List&lt;KBT_Inventory_Stock__c&gt;();         currentstock = [SELECT Id,KBT_Products__c,Name__c,Name,Next_stock_Expected_Date__c,Stock__c FROM KBT_Inventory_Stock__c];         System.debug('The Current stock is' + currentstock);         KBT_Inventory_Stock__c s= New KBT_Inventory_Stock__c();         ph.ProductId__c=s.KBT_products__c;         s.stock__c=s.Stock__c-ph.Purchased_Quantity__c;         if (s.Stock__c==0){             s.Stock__c.addError('out of stock ');         }     } }
120553
I am creating a cross-objects trigger that whenever a new opportunity is opened, the trigger goes to check whether the company has sold the same product to the customer before; if so, the type of the opportunity will be 'Existing', otherwise it will be 'New'.  trigger InOfficeOp on Opportunity (after insert, after update) {      Set&lt;Id&gt; account_id = new Set&lt;Id&gt;();     List&lt;Id&gt; opp_id = new List&lt;Id&gt;();     for (Opportunity opp: Trigger.new){         if(opp.HasOpportunityLineItem){                         account_id.add(opp.AccountId);             opp_id.add(opp.Id);         }      }       Map&lt;Id, List&lt;Asset&gt;&gt; acc_asset_map = new Map&lt;Id, List&lt;Asset&gt;&gt;();     Map&lt;Id, List&lt;OpportunityLineItem&gt;&gt; opp_prod_map = new Map&lt;Id, List&lt;OpportunityLineItem&gt;&gt;();      for(Asset ast: [SELECT  Product2Id, AccountId FROM Asset WHERE AccountId IN: account_id]) {         if(acc_asset_map!=null &amp;&amp; acc_asset_map.containsKey(ast.Product2Id)) {             List&lt;Asset&gt; asset_List = acc_asset_map.get(ast.Product2Id);             asset_List.add(ast);             acc_asset_map.put(ast.Product2Id,asset_List);         }         else {             acc_asset_map.put(ast.Product2Id, new List&lt;Asset&gt;{ast});             }     }      for (OpportunityLineItem oli: [SELECT Product2Id, OpportunityId FROM OpportunityLineItem WHERE OpportunityId IN: opp_id]){         if(opp_prod_map!=null &amp;&amp; opp_prod_map.containsKey(oli.Product2Id)){             List&lt;OpportunityLineItem&gt; oppLineItem_Recd = opp_prod_map.get(oli.Product2Id);             oppLineItem_Recd.add(oli);             opp_prod_map.put(oli.Product2Id, oppLineItem_Recd);                 }         else {             opp_prod_map.put(oli.Product2Id, new List&lt;OpportunityLineItem&gt;{oli});          }     }     Id op;     for(Id prodId: acc_asset_map.keyset()){         if(opp_prod_map!= null &amp;&amp; opp_prod_map.containsKey(prodId)) {             for(OpportunityLineItem oppLine_Recd:opp_prod_map.get(prodId)) {                 op = oppLine_Recd.OpportunityId;             }         }     }     for(Opportunity o:Trigger.new){         if(o.Id == op){             o.Type = 'Existing_Business';         }         else{             o.Type = 'New_Business';         }     }     }   The above is my trigger code.  And here is my test:  @isTest private class OppTriggerTest{     static void PopulateExtensiontest()      {         Date closeDt = Date.Today();         date myDate = date.today();          Account a2 = new Account(Name='icrm test acc');         insert a2;          Opportunity oppr = new Opportunity(Name='testing DIE 6/4/2017', AccountId = a2.Id,StageName='Prodpecting',  CloseDate = Date.Today());         insert oppr;          Pricebook2 pb22 = new Pricebook2(Name='testDIE');         insert pb22;          Product2 pro2 = new Product2(Name='BXCD', isActive=true);         insert pro2;          PricebookEntry pbe2 =new  PricebookEntry(unitprice=0.01,Product2Id=pro2.Id, Pricebook2Id=Test.getStandardPricebookId(), isActive=true, UseStandardPrice=false);          insert pbe2;          OpportunityLineItem OPplineitem2 = new OpportunityLineItem (Quantity=2, OpportunityId=oppr.Id, UnitPrice=0.01, PriceBookEntryId =pbe2.Id);         insert OPplineitem2;          update oppr;     } }   And I got the error message after I exceture the test:     System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, InOfficeOp: execution of AfterInsert caused by: System.FinalException: Record is read-only   Trigger.InOfficeOp: line 51, column 1: []   I don't quite understand what does the message mean. Could anyone please help me what does the error mean? Is my test wrong?
93357
My Trigger will send an email anytime one account has 7 cases created within 8 days. Towards the bottom in my Else block, I am trying to access fields in my first SOQL statement. I have tried many ways and read many help pages. Help with the syntax for the line: message.PlainTextBody = 'Account name: ' + cl.get('name') + ' has ' + (Integer)cl.get('co') + ' cases opened in the last 8 days.';`  is greatly appreciated.  List&lt;AggregateResult&gt; AggregateResultList = [SELECT AccountId, Account.Name name, COUNT(Id) co                                          FROM Case                                          WHERE CreatedDate = LAST_N_DAYS:8                                          GROUP BY AccountId, Account.Name                                          HAVING COUNT(Id)  &gt;= 7];                           Set&lt;Id&gt; AcctIds = new Set&lt;Id&gt;();                 for(AggregateResult aggr: AggregateResultList){                      Id accId = (Id)aggr.get('AccountId');                         AcctIds.add(accId);                 }                  List&lt;Case&gt; caseList = [SELECT Id, AccountId, Account.Name,Parent_Project_if_applicable__r.Implementation_status__c,                                                 Parent_Project_if_applicable__r.PM_Implementation_Status__c,                                                  Parent_Project_if_applicable__r.RCM_Implementation_Status__c                                            FROM Case                                        WHERE AccountId IN :AcctIds];             Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();             for(Case cl:caseList){                   if(cl.Parent_Project_if_applicable__r.Implementation_status__c == 'Live - Closed Project'){                             //Private method *** getAddresses() *** retrieves email address from Customer_Success_Managers Public Group                              message.toAddresses  = getAddresses();                            }                         else{                                message.toAddresses = new String[] { Parent_Project_if_applicable__r.Client_Advisor_Email__c  };                          }                     message.Subject = 'Subject Test Message';                     message.PlainTextBody = 'Account name: ' + cl.get('name') + ' has ' + (Integer)cl.get('co') + ' cases opened in the last 8 days.';                     Messaging.SingleEmailMessage[] messages =   new List&lt;Messaging.SingleEmailMessage&gt; {message};                     Messaging.SendEmailResult[] results = Messaging.sendEmail(messages);             } private List&lt;String&gt; getAddresses(){ List&lt;User&gt; UserList =         [SELECT id, name, email         FROM User          WHERE id          IN (SELECT userorgroupid              FROM groupmember             WHERE group.name = 'Customer Success Managers')];  List&lt;String&gt; emailString = new List&lt;String&gt;();  for(User u: UserList){     emailstring.add(u.email); }    return (emailString); }
56441
I am currently programming a trigger on Opportunities.   I created a test class for this and in my Sandbox I created an account, contact and opportunity. When I try to reference them   Opportunity Opp = [SELECT id from Opportunity where name = 'Test1'];    and then start my   Test.startTest();         Opp.StageName = 'PO in (100%)';          update Opp;         Test.stopTest();   It just errors and shows that Opp returns 0 rows. However when I paste my first bit of code in 'Execute Anonymous' it returns a row and the correct info.   Does this mean I have to create an account, contact, quote and all necessary fields in my test class?
113469
The objective is to have assignment rules fired on a Lead record creation. It seems the rule can be assigned only when using "update" DML in an "after insert" trigger. Why does another DML must be executed after insert to have lead assignment rule assigned?   //Does not work trigger LeadTrigger on Lead (before insert) {         for (Lead l : Trigger.new) {                 Database.DMLOptions dmo = new Database.DMLOptions();         dmo.assignmentRuleHeader.useDefaultRule = true;         so.setOptions(dmo);     } }   //Works: Records must be *updated* in after insert trigger in order to have the rule assigned trigger LeadTrigger on Lead (after insert) {     List&lt;Lead&gt; ls = new List&lt;Lead&gt;();      for (Lead l : Trigger.new) {         ls.add(new Lead(id = l.id));     }      Database.DMLOptions dmo = new Database.DMLOptions();     dmo.assignmentRuleHeader.useDefaultRule = true;     Database.update(ls, dmo); }   Moreover, testing of the rule assignment fails even though the rule has been assigned to the Lead. We cannot test assignment rule outcome (ownerId=defaultQueueId for example) since the rule will change on PROD eventually.  //Test method failing for a lead *having* rule assigned:     public static void assertDefaultAssignmentRules(SObject sobj) {     Database.DMLOptions dmo = sobj.getOptions();      System.assertNotEquals(null, dmo, 'DMLOption is null');     System.assert(dmo.assignmentRuleHeader.useDefaultRule, dmo); }
123683
Let us assume there is a listed company x. Currently it has 100 shares issued to trade in free float market. Current price of stock is let say 10. Now please let me know if I purchase one share of company x at the market price of 10. How it will effect the stock price. And please add and exemplify some other scenarios whichever you find good to explain more. For more information let say promoters of the company holds 100 shares with them like 50% of the company is with promoters and the other half is with people who invest or trade in that company. If I've missed to tell or assume any other vital info. needed please assume it yourself while mentioning it. Thank You
16290
This is a canonical question and answer developed by the community to help address common questions. If you've been directed here, or your question has been closed as a duplicate, please look through the resources here and use them to shape more specific questions. To browse all canonical questions and answers, navigate to the  tag. This question and answer is owned by the community! If you can improve it and make it more useful, you're welcome to edit it. I am building a trigger, a unit test, or other Apex code. I'm working with sObject records, and trying to access related record information. For example, I might have a structure like this: Account a = new Account(Name = 'Test'); insert a;  Opportunity o = new Opportunity(Name = 'Donation', AccountId = a.Id); insert o;  System.assertEquals(o.Account.Name, 'Test', 'Correct Account associated'); // Assertion fails!  Or, in a trigger, I might be aiming for something like this: trigger ContactTrigger on Contact (after insert) {     for (Contact c : Trigger.new) {         if (c.Account.Name == 'Test') {             // Take some action here         }      } }  Why doesn't this work? Why am I getting null values, or NullPointerExceptions?
16473
Consider the class below that represents a Broker:  public class Broker {     public string Name = string.Empty;     public int Weight = 0;      public Broker(string n, int w)     {         this.Name = n;         this.Weight = w;     } }   I'd like to randomly select a Broker from an array, taking into account their weights.  What do you think of the code below?  class Program     {         private static Random _rnd = new Random();          public static Broker GetBroker(List&lt;Broker&gt; brokers, int totalWeight)         {             // totalWeight is the sum of all brokers' weight              int randomNumber = _rnd.Next(0, totalWeight);              Broker selectedBroker = null;             foreach (Broker broker in brokers)             {                 if (randomNumber &lt;= broker.Weight)                 {                     selectedBroker = broker;                     break;                 }                  randomNumber = randomNumber - broker.Weight;             }              return selectedBroker;         }           static void Main(string[] args)         {             List&lt;Broker&gt; brokers = new List&lt;Broker&gt;();             brokers.Add(new Broker("A", 10));             brokers.Add(new Broker("B", 20));             brokers.Add(new Broker("C", 20));             brokers.Add(new Broker("D", 10));              // total the weigth             int totalWeight = 0;             foreach (Broker broker in brokers)             {                 totalWeight += broker.Weight;             }              while (true)             {                 Dictionary&lt;string, int&gt; result = new Dictionary&lt;string, int&gt;();                  Broker selectedBroker = null;                  for (int i = 0; i &lt; 1000; i++)                 {                     selectedBroker = GetBroker(brokers, totalWeight);                     if (selectedBroker != null)                     {                         if (result.ContainsKey(selectedBroker.Name))                         {                             result[selectedBroker.Name] = result[selectedBroker.Name] + 1;                         }                         else                         {                             result.Add(selectedBroker.Name, 1);                         }                     }                 }                   Console.WriteLine("A\t\t" + result["A"]);                 Console.WriteLine("B\t\t" + result["B"]);                 Console.WriteLine("C\t\t" + result["C"]);                 Console.WriteLine("D\t\t" + result["D"]);                  result.Clear();                 Console.WriteLine();                 Console.ReadLine();             }         }     }   I'm not so confident. When I run this, Broker A always gets more hits than Broker D, and they have the same weight.  Is there a more accurate algorithm?  Thanks!
26345
I am trying to Clone a lead when certain condition is arrived using before trigger but i am not able to see cloned record.   for( Lead ld : Trigger.new ) {                          if(ld.Integration_Source__c == 'Hubspot' &amp;&amp; Trigger.isUpdate){         Lead LeadBeforeUpd = Trigger.oldMap.get( ld.Id );         if(ld.Program__c != LeadBeforeUpd.Program__c ){            Lead ClonedLead = new Lead();            ClonedLead = LeadBeforeUpd.clone(false, false, false, false);         }     }  }
121895
I have a trigger and a class that seem to be causing an insert fail in Dataloader.  I am trying to insert 200 records to see if an error is generated before moving these to production. I'm just inserting the mandatory fields such as Name, Owner, Market, Customer_Success_Manager__c, and Business Unit.   Each time I get an error:     UpdateCSMTeam:execution of AfterInsertcaused by: System.DmlException:   Insert failed. First exception on row 0 with id01MJ0000009gXthMAE;   first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an   insert call: [Id]Class.UpdateCSM.updateTeamMem . I've listed the class   and trigger below.   APEX CLASS  public class UpdateCSM {             public static void updateTeamMember(List&lt;Account&gt; accounts) {                     List&lt;AccountShare&gt; ashareLIST = new List&lt;AccountShare&gt;();                     List&lt;AccountTeamMember&gt; ATM = new List&lt;AccountTeamMember&gt;();                    Set&lt;String&gt; rmMember = new Set&lt;String&gt;();                     Map&lt;ID, ID&gt; acctToBRepMap = new Map&lt;ID, ID&gt;();                      for(Account a:accounts){                              AccountShare caSharingRule = new AccountShare();                                caSharingRule.AccountId = a.Id;                                caSharingRule.OpportunityAccessLevel = 'Edit';                                caSharingRule.CaseAccessLevel = 'Edit';                                caSharingRule.AccountAccessLevel = 'Edit';                                caSharingRule.UserOrGroupId = a.Customer_Success_Manager__c;                                ashareLIST.add(caSharingRule);                                    if(a.Customer_Success_Manager__c!= null){                                   AccountTeamMember Teammemberad=new AccountTeamMember();                 Teammemberad.AccountId=a.id;                 Teammemberad.UserId=a.Customer_Success_Manager__c;                 Teammemberad.TeamMemberRole = 'Customer Success Manager';                                   ATM.add(Teammemberad);                             if(!ATM.isEmpty()){                                    insert ATM;                                              insert ashareLIST;                                                         if(a.Customer_Success_Manager__c==null){                                            list&lt;AccountTeamMember&gt; ratm = [SELECT UserId                                                                             FROM AccountTeamMember                                                                             WHERE (TeamMemberRole = 'Customer Success Manager')                                                          AND AccountId =:a.id];                                             if(ratm.size()&gt;0)                                                 delete ratm;                                        }                                    }                                 }                            }                         }                    } ...   APEX TRIGGER  trigger UpdateCSMTeam on Account (After update, After insert){         UpdateCSM.updateTeamMember(trigger.new); }
99911
I wrote the following trigger and I'm getting the error :     Illegal assignment from Schema.SObjectField to String   But I don't know how to fix it. I wrote a similar trigger before and didn't have any issues.   trigger AccountDuplicates on Account (before insert, before update) {  for (Account myaccount : Trigger.new) {         List &lt;Account&gt; dupes = [SELECT Name FROM Account WHERE Name = :(myaccount.Name)];          if (dupes.size() &gt; 0) {            myaccount.Duplicate_Account__c = Account.name;         }     } }   The purpose of the trigger - when a new account is created that matches the name of an existing account, put the existing account's name into the "Duplicate Account" field.
108575
If I have a trigger before the update on a table, how can I throw an error that prevents the update on that table?
16527
A general question asked from time to time on stack exchange is question of trigger bulkification.  Therefore I have 2 questions:   Which best practices are you using? What is the best way to handle updates of more than 200 records? (In case of more than 200 records the trigger is executed more than once.)
34471
What is wrong in the below trigger syntax, I am getting this error An unexpected token "INT" was found following " DECLARE NULL_ROW_ID".  Expected tokens may include:  "END-OF-STATEMENT".. SQLCODE=-104, SQLSTATE=42601, DRIVER=3.68.61  CREATE TABLE A (     A_ID INT NOT NUll,     A_CODE VARCHAR(100) NOT NULL,     PRIMARY KEY(A_ID) );  CREATE TABLE B (     B_ID INT NOT NUll,     B_CODE VARCHAR(100) NOT NULL,     A_ID INT,     PRIMARY KEY (B_ID),     FOREIGN KEY (A_ID) REFERENCES A (A_ID)  );  CREATE OR REPLACE TRIGGER B_TRIGGER AFTER UPDATE OF A_ID ON B REFERENCING NEW AS N OLD AS O FOR EACH ROW     WHEN (N.A_ID IS NULL)     BEGIN ATOMIC         DECLARE NULL_ROW_ID INT;         SET NULL_ROW_ID = (SELECT A_ID FROM A WHERE A_CODE = 'Custom Null String');         IF NULL_ROW_ID IS NULL THEN             SIGNAL SQLSTATE '70000' SET MESSAGE_TEXT = 'Custom Null String row not found.';         END IF;     SET N.A_ID = NULL_ROW_ID;     END @   It's on DB2 Express-C 10.5
16323
Software Name: Oracle SQL Developer Version 17.2.0.188  I have three tables: orders, order_details, and products.  I wanted to run a query to update units_in_stock in the products table based on quantity in order_details, where the associated orders row has been marked as shipped, and has a shipping date.  Here's what I tried:  UPDATE Products SET (Products.Unit_In_Stock = Products.Unit_In_Stock - Order_Details.Quantity) INNER JOIN (     Orders INNER JOIN Order_Details ON Orders.Order_ID = Order_Details.Order_ID     ) ON Products.Product_ID = Order_Details.Product_ID WHERE (         ((Orders.Shipped_Date) IS NOT NULL)         AND ((Orders.This_Order_Was_Shipped) = "YES")         );   When I run this, I get:  Error at Command Line : 1 Column : 45   Line 1, Column 45 is the equal sign in the very first statement that said  Products.Unit_In_Stock = Products.Unit_In_Stock - Order_Details.Quantity   Can you help me get this working?
90062
I have Opportunity-lookup field on Opportunity (self),  Scenario:   Opportunity A if select Opportunity B using lookup then Opportunity B's same lookup field automatically populate with Opportunity A.   I tried to achieve this using trigger - before insert/update but its failing as:  System.DmlException: Update failed. First exception on row 0 with id 006G000000DHaBlIAL; first error: SELF_REFERENCE_FROM_TRIGGER, Object (id = 006G000000DHaBl) is currently in trigger Oppy_before_INSUPD, therefore it cannot recursively update itself: []
105078
Does anyone know how SQL Server determines the order triggers (of same type, i.e. before triggers) are executed.  And is there any way of changing this so that I can specify the order I want.  If not, why not.  Thanks.
46169
I'm getting an error INACTIVE_OWNER_OR_USER, operation performed with inactive user, and I have been doing a lot of research and the cause that I have found for this is its attempting to assign a my lead to inactive user.  So I understand that part I think the issue is now I don't actually know how to fix it, I didn't write this trigger/test class and I'm not sure how to go forward.  Do I need to create a new Test User?  I've never worked on the Lead object before..  Edit** I added IsActive = True the trigger user query, no luck.  Edit** I just went talking to anyone that might have an idea about UserTypes, and they have no idea what UserType = 'PowerPartner' is.  So I changed it to a different UserType.. didn't work  Edit**  I'm nuking this trigger, I have to re write it..  Test Class  @isTest private class PartnerLeadShare_test { static testMethod void myUnitTest1() { List&lt;Lead&gt; leadList = new List&lt;Lead&gt;(); List&lt;LeadShare&gt; leadShareList = new list&lt;LeadShare&gt;();   Lead ld = new Lead(); ld.lastName = 'Tester';//=/ ld.Company = 'MyCompany'; ld.Status = 'Open'; ld.Program_EAU__c ='11'; insert ld; system.debug('ld****' +ld);  GroupMember groupMemberStore = [select GroupId,UserOrGroupId from GroupMember limit 1];  LeadShare ls = new LeadShare();  ls.LeadId = ld.id; ls.UserOrGroupId = groupMemberStore.UserOrGroupId ; ls.LeadAccessLevel = 'Edit'; leadShareList.add(ls);   if(leadShareList.size()&gt;0){     system.debug('INSIDE LEADSHARE LIST.');      insert leadShareList;  }  } }   Don't know this will help but here is my trigger..  trigger PartnerLeadShare on Lead (after insert,after update) {  Map&lt;id,User&gt;PartnerUsermap = new Map&lt;id,user&gt;([select id,UserType from user where      UserType = 'PowerPartner' and IsActive = True] );    List&lt;GroupMember&gt;GroupMemberList = new List&lt;GroupMember&gt;([select GroupId,UserOrGroupId   from GroupMember]);   System.debug('PartnerUsermap ===  '  +PartnerUsermap); System.debug('GroupMemberList    '+GroupMemberList );  List&lt;LeadShare&gt; leadShareList = new list&lt;LeadShare&gt;();    if(!PartnerUsermap.isEmpty()){ for(Lead ld: trigger.new){      for(GroupMember grpmem : GroupMemberList){         if(grpmem.UserOrGroupId == ld.CreatedById){               LeadShare ldShare = new LeadShare (LeadId = ld.id,UserOrGroupId = grpmem.GroupId,LeadAccessLevel = 'Edit');              leadShareList.add(ldShare );         }     } } } if(!leadShareList.isEmpty()){ Database.SaveResult[] lsr = Database.insert(leadShareList,false);            Integer i=0; for(Database.SaveResult sr : lsr){     if(!sr.isSuccess()){     Database.Error err = sr.getErrors()[0];              if(!(err.getStatusCode() == StatusCode.FIELD_FILTER_VALIDATION_EXCEPTION                                              &amp;&amp;  err.getMessage().contains('AccessLevel'))){                  trigger.newMap.get(leadShareList[i].LeadId).                   addError(                    'Unable to grant sharing access due to following exception: '                    + err.getMessage());             }     }    i++; } }