I am trying to implement S2S (Salesforce to salesforce) And I have written a code on Custom object called "ABC" to allow auto forwarding of records. After making the trigger active, I cannot manually create any records. Please help.  trigger SendABCToConnection on ABC__c(after insert,after update) {         PartnerNetworkConnection conn = [select Id, ConnectionStatus, ConnectionName from PartnerNetworkConnection  where ConnectionStatus = 'Accepted' and ConnectionName = 'XYZ'];         List&lt;PartnerNetworkRecordConnection&gt; recordConnectionToInsert  = new List&lt;PartnerNetworkRecordConnection&gt;  ();         for (ABC__c acc : Trigger.new){             PartnerNetworkRecordConnection newrecord = new PartnerNetworkRecordConnection();          newrecord.ConnectionId = conn.Id;         newrecord.LocalRecordId = acc.id;           newrecord.SendClosedTasks = false;         newrecord.SendOpenTasks = false;         newrecord.SendEmails = false;         recordConnectionToInsert.add(newrecord);     }     if (recordConnectionToInsert.size() &gt; 0){         System.debug('&gt;&gt;&gt; Sharing ' + recordConnectionToInsert.size() + ' records');         insert recordConnectionToInsert;     }  }   The error I am getting is :     Apex trigger SendABCToConnection caused an unexpected exception,   contact your administrator: SendABCToConnection: execution of   AfterInsert caused by: System.QueryException: List has more than 1 row   for assignment to SObject: Trigger.SendABCToConnection: line 2, column   1
31142
I am trying to write a VF page to list all the id and name columns from a custom object but found an error "List has more than 1 row" in the VF page.  Can anyone tell me what have I done wrong?  VF Page:  &lt;apex:page Controller="MP_controller" showHeader="false" sidebar="false"&gt;   &lt;apex:pageBlock&gt;      &lt;apex:pageBlockTable value="{! mp}" var="item"&gt;         &lt;apex:column value="{! item.id}"/&gt;         &lt;apex:column value="{! item.name}"/&gt;       &lt;/apex:pageBlockTable&gt;   &lt;/apex:pageBlock&gt; &lt;/apex:page&gt;   Apex controller  global with sharing class MP_controller {     public Merchant_Profile__c mp{get;set;}     public MP_controller(){         mp = [SELECT                  ID, name, Profile_account_name__c, Merchant_ID__c, Bank_Code__c, Country_Code__c,                 Currency_Code__c, Merchant_Level__c, Merchant_Type__c, MSO__c, Region__c,                 Retail_Products__c, Transaction_Mode__c, Created_Date__c, Date_Disabled__c, Date_Live__c,                 Merchant_Category_Code__c                FROM Merchant_Profile__c               WHERE Profile_Account_Name__c = '001O000000bQFnyIAG'];     } }
55792
i have scenario like write a trigger avoid insertion of records  from  data loader,only manual insertion trigger will fire?on any object     while Entering records from data loader trigger should not fire?
62103
Are there a way to add callback after the user created a record and clicked the Save button?  I am using a custom tab and custom components and open the Create a record modal window using e.force:createRecord, but I was not able to find out how to attach callback to the event.  I even found :     Currently force:createRecord event does not accept any callback method or any after save event to handle custom action. Current force:createRecord always redirects to the newly created record. But in case if you want to just close the force:createRecord popup after save and refresh some other related component using the refresh is not possible.    So, is it really impossible? If so, what are current workarounds here?
81531
We had a small widget that allowed customers to share records that were set to a private sharing model in our community. Everything was rather simple and it would simply allow them to select users that were visible via Sharing Sets and create an __Share record in APEX.  I've been reported recently that an error is thrown but only on the community side of things. Nothing seems to be working where it was working. We are using    Customer Community Plus licenses.  The error being thrown is : System.TypeException: DML operation INSERT not allowed on &lt;Object&gt;__Share which seemed to indicate access not available on the object. That seems odd because they are able to interact with the object just fine in order to create/edit/delete them.  I looked up the Sharing Model (its private both internally and externally), I looked at the profile and their access and the sharing sets in the community. Like I said, they seem to interact fine with the objects when it comes to seeing the records and their right.  Additionally, standard license users can use the component fine and also share with community users without a problem. They also see the records as expected.  Am I missing an update or something that seem to make it so this doesn't work anymore? Anyone having trouble with this or encountered the same problem?
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);         }     }  }
27765
I've been trying to leverage custom roll up functionality and found that Database methods is perfoming dml twice. First time it's inserting/updating all records and second time only ones that can be processed. Is it correct? I'm afraid that I'm missing important part in documentation     The optional allOrNone parameter specifies whether the operation allows partial success. If you specify false for this parameter and a record fails, the remainder of the DML operation can still succeed. This method returns a result object that can be used to verify which records succeeded, which failed, and why.   Since I've placed static boolean to check if trigger has been run, I'm loosing data.  If we create test based on the following    @isTest public class Test_accountTrigger {     @isTest     static void Test_saveResult() {         Account[] accts = new List&lt;Account&gt;{             new Account(Name='Account1'),             new Account()};         Database.SaveResult[] srList = Database.insert(accts, false);     } }   Given trigger will be executed twice  trigger accountTrigger on Account (before insert) {     system.debug('accountTrigger.sise: ' + trigger.new.size()); }   Debug  22:25:31.1 (362723328)|USER_DEBUG|[2]|DEBUG|accountTrigger.sise: 2 22:25:31.1 (498071498)|USER_DEBUG|[2]|DEBUG|accountTrigger.sise: 1   I'm trying to update multiple child records within ETL and inside Salesforce update correspondent Parent records with flag allOrNone set to false. If any of those fails I'm adding error to child record. Since I have static boolean check, my first attempt of updating parent records is reverted and second is never happened.
61579
We are creating custom IDs for Accounts by incrementing an integer field in a custom class. The issue is that if two or more new Accounts are created in close sequence/simultaneously the following code will assign duplicated numbers rather than an incremented number for each:  public static void SetCustomId(Account account) {            CustomObj__c customObj = CustomObj__c.getOrgDefaults();      account.CustomAccountId__c = String.valueOf(Integer.valueOf(customObj.CustomCounter__c));     customObj.CustomCounter__c = customObj.CustomCounter__c + 1;      update customObj; }   Is there a way in Apex to lock a process so that a shared resource is used sequentially? In Java, C#, C++ etc. this is pretty easily done via a critical section if it's a single process or a Mutex if multiple processes access the same resource. Is there anything like this supported in Salesforce? Solutions beside Apex code/triggers would be fine as long as they meet the spec.   EDIT:  It is important that the object creates be sequential and not generate errors due to lockouts.
66376
I have written a trigger on custom object Order_Item__c. This object has a custom field Shipping_Number__c. When the user enters value in Shipping_Number__c and clicks save, the contact lookup field will automatically populate with contact record which has same shipping number as the value entered by the user. The trigger is working fine. I am unable to get code coverage. The coverage is 0%. Any insights will be lot helpful.  Trigger:  trigger updatelookupfield on Order_Item__c (before update, before insert)  {       Set&lt;String&gt; shippingNumbers = new Set&lt;String&gt;();      for (Order_Item__c collectNumFromOrder : Trigger.new) {         shippingNumbers.add(collectNumFromOrder.Shipping_Customer_Number__c);     }        List&lt;Contact&gt; contactList = [SELECT id, Shipping_customer_number__c FROM Contact WHERE Shipping_Customer_Number__c IN :shippingNumbers];      Map&lt;String, Contact&gt; shippingNumToContactMap = new Map&lt;String, Contact&gt;();      for (Contact c : contactList) {         shippingNumToContactMap.put(c.Shipping_customer_number__c, c);     }      for (Order_Item__c o : Trigger.new) {            if (o.Shipping_Customer_Number__c != null) {             o.RSM_Shipping_Contact__c = shippingNumToContactMap.get(o.Shipping_Customer_Number__c).id;         }         else {             o.RSM_Shipping_Contact__c = null;         }      }     }    Test Class:  @isTest public class testupdatelookupfield{      Static testMethod void insertOrderItem()     {   // create and insert the contact record - this part is correct         contact c = new contact();         c.Shipping_Customer_Number__c = '0987654';         c.lastName = 'Surekha';        insert c;           // create an order item and insert it         Order_Item__c op = new Order_Item__c();          op.Name = 'Test Varun Order';         op.Shipping_Customer_Number__c = '0987654';         insert op;           system.assertequals(op.RSM_Shipping_Contact__c,c.id);     } }
78811
I added a new field on Opportunity table to keep a count of records, as well as track the updates made on that record.  This is needed for an external system we use. Opportinity table already has around 5000 records now. I would like to update the new field that I added with some sequence order initially. Say each record to have a unique sequence number like 1,2,3 etc(can't use the Id field for unique). The field "Identifier__c" was added for this purpose with data type number and unique contraint. For that I created a temporary class and trigger. But it is throwing the error.     Review all error messages below to correct your data. Apex trigger OpportunitySAPIdentifierHandler caused an unexpected exception,   contact your administrator: OpportunitySAPIdentifierHandler: execution   of BeforeUpdate caused by: System.DmlException: Update failed. First   exception on row 0 with id 006E00000038FPSIA2; first error:   CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, OpportunitySAPIdentifierHandler:   execution of BeforeUpdate caused by: System.DmlException: Update   failed. First exception on row 0 with id 006E00000038FPTIA2; first   error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY,   OpportunitySAPIdentifierHandler: execution of BeforeUpdate caused by:   System.DmlException: Update failed. First exception on row 0 with id   006E00000038FPSIA2; first error: SELF_REFERENCE_FROM_TRIGGER, Object   (id = 006E00000038FPS) is currently in trigger   OpportunitySAPIdentifierHandler, therefore it cannot recursively   update itself: [] Class.AutoNumber.OpportunityAutoNumber: line 76,   column 1 Trigger.OpportunitySAPIdentifierHandler: line 4, column 1: []   Class.AutoNumber.OpportunityAutoNumber: line 76, column 1   Trigger.OpportunitySAPIdentifierHandler: line 4, column 1: []:   Class.AutoNumber.OpportunityAutoNumber: line 76, column 1   Below is the trigger and class used.  trigger Opportuniwith sIdentifierHandler on Opportunity (before insert,before update) {          If(Trigger.isInsert || Trigger.isUpdate){             AutoNumber.OpportunityAutoNumber(Trigger.new);         }   }   The class is   public with sharing class AutoNumber {       public static void OpportunityAutoNumber (List&lt;Opportunity&gt; Opp) {          if(Trigger.isUpdate || Trigger.isInsert) {              for(Opportunity p: Opp) {                  List&lt;Opportunity&gt; oppList = new List&lt;Opportunity&gt;();                 oppList = [SELECT Id, createdDate, Identifier__c FROM Opportunity where Identifier__c = null and Id != :p.Id limit 100 FOR update];                 for (Opportunity oppL: oppList) {                      if(oppL.Identifier__c == null) {                          List&lt;Opportunity&gt; OpportunityList = new List&lt;Opportunity&gt;([select Identifier__c from Opportunity where Identifier__c != null order by Identifier__c desc limit 1]);                          if (!OpportunityList.isEmpty()) {                               Decimal maxval = OpportunityList.get(0).Identifier__c;                             oppL.Identifier__c = maxval + 1;                             update oppL;                         }                      }                     // integer currentCounter = Integer.valueOf(opp.Identifier__c);                     // oppr.Identifier__c = currentCounter + 1;                     // update oppr;                 }             }         }        }  }
34110
I received the following error:     Error: Invalid Data.    Review all error messages below to correct your data.   Apex trigger ISOTrigger caused an unexpected exception, contact your administrator: ISOTrigger: System.LimitException: Too many SOQL queries: 101   In the debug log I've found the following:  15:11:56.0 (762902111)|SOQL_EXECUTE_BEGIN|[94]|Aggregations:0|SELECT Id, OwnerId, IsRecurrence, RecurrenceActivityId FROM Task WHERE (IsClosed = FALSE AND (IsRecurrence = TRUE OR RecurrenceActivityId = '') AND AccountId = :tmpVar1) 15:11:56.0 (762942801)|EXCEPTION_THROWN|[94]|System.LimitException: Too many SOQL queries: 101 15:11:56.0 (763220286)|FATAL_ERROR|System.LimitException: Too many SOQL queries: 101  Class.AccountHandler.beforeUpdate: line 94, column 1 Class.TriggerFactory.execute: line 95, column 1 Class.TriggerFactory.createHandler: line 29, column 1 Trigger.AccountTrigger: line 3, column 1  15:11:56.0 (763234604)|FATAL_ERROR|System.LimitException: Too many SOQL queries: 101   Here is the code in method beforeUpdate and AccountHandler class:  public void beforeUpdate(SObject oldSo, SObject so) {     for(SObject bu :Trigger.new) {        Account a = (Account) bu;         List&lt;Task&gt; tasksFromDatabase = new List&lt;Task&gt; ([SELECT Id, OwnerId, IsRecurrence, RecurrenceActivityId FROM Task WHERE IsClosed=false AND (IsRecurrence = true OR RecurrenceActivityId = '') AND AccountId = :a.Id]);         String agentName = a.Agents__c;        String recruiterName = a.Recruiter__c;//TO DO ::: delete, not used         if(agentName != null) {            List&lt;ISOs__c&gt;isoName = [SELECT Name, Recruiter_ID_num__c, Active__c FROM ISOs__c WHERE Id IN (SELECT ISO_Company__c FROM Agent__c WHERE Id = :agentName)];            if(isoName.size() &gt; 0) {                if(isoName[0].Active__c == false) {                    a.ISO_Name__c.addError('The selected agent is linked to an inactive Iso');                }             a.ISO_Name__c = isoName[0].Name;            a.ISO_recruiter_id__c = IsoName[0].Recruiter_ID_num__c;            }        } else if(agentName == null) {            a.ISO_Name__c = '';            a.ISO_recruiter_id__c = '';        }         for(SObject sob :Trigger.new) {            Account ab = (Account) sob;            Account oldAB = (Account)Trigger.oldMap.get(ab.id);            if (ab.Status__c != null &amp;&amp; oldAB.Status__c!=null) {                       if(ab.Status__c != oldAB.Status__c) {                       statusmail mail = new statusmail();                    mail.setAccountInfo(ab);                    mail.SendAccountEmail();                                if(ab.Agents__c != null)                        mail.sendAgentEmail();                    if(ab.Recruiter__c != null)                        mail.sendRecruiterEmail();                }            }        }            } }   Please advise how to avoid this error?
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); }
90260
We have a workflow that creates tasks and assigns them to a specific user when an opportunity is closed. It's salesforce standard behavior that when the account owner is changed, the open tasks are also reassigned to the new account owner. I'm trying to write a trigger that:   checks if the account owner and/or task owner is changed FROM 00590000000a3xU if yes, reassign the tasks back to 00590000000a3xU only open tasks and tasks where Orb Team Task (checkbox) is true will be reassigned   I was getting all sorts of errors from the old code even after making the changes sfdcfox's pointed out. So I decided to change my approach. Here's the new and working code:  trigger AssignTaskBackToWarehouse on Account (after update){ List&lt;Task&gt;TasksToUpdate = new List&lt;Task&gt;(); Map&lt;Id,Account&gt;amap = new Map&lt;Id,Account&gt;([SELECT Id, OwnerId,(SELECT Id, Status, Warehouse_Task__c     FROM tasks     WHERE Status != 'Completed' AND     Warehouse_Task__c = true)     FROM Account     WHERE Id =: Trigger.newmap.keyset()]); for(Account a : Trigger.new){     for(Task t : amap.get(a.Id).tasks){         t.OwnerId = '00590000000XXXX';         TasksToUpdate.add(t);     }     } if(TasksToUpdate.size() &gt; 0){     update TasksToUpdate; } }
105785
Whenever an Order is inserted with Pricebook and Status of 'Activated', create a child Order_Pricebook__c record.  trigger createorderpricebook on Order (before update)  {     for(Order ce:trigger.new)     {         if(ce.status =='Activated')         {         order cf = [select id,pricebook2.id from order where id=:ce.id];         Order_Pricebook__c gh = new Order_Pricebook__c();         gh.name= 'ela';         gh.Order__c = cf.id;         gh.Price_Book__c = cf.pricebook2.id;         insert gh;         }       } }   How can I rewrite this Apex Trigger  to handle bulk operations?
82536
I am upserting list of records based on externalId as follows:  List&lt;Database.upsertResult&gt; results = Database.upsert(lstRecords, CustomObject__c.External_Id__c,true);   The results returns as follows:  (Database.UpsertResult[getErrors=();                         getId=a1k0j000000P6CmAAK;                         isCreated=true;                         isSuccess=true;],   Database.UpsertResult[getErrors=();                         getId=a1k0j000000P6CNAA0;                         isCreated=false;                         isSuccess=true;])   The first record is inserted and 2nd record is updated.  Since I am upserting based on externalId, I need to know for which ExternalId the records have been successfully inserted or updated.   doesn't expose any methods. It returns SalesforceId and NOT externalId  I need a results structure like this:  (Database.UpsertResult[getErrors=();                         getExternalId = '1234';                         getId=a1k0j000000P6CmAAK;                         isCreated=true;                         isSuccess=true;],   Database.UpsertResult[getErrors=();                         getExternalId = '1235';                         getId=a1k0j000000P6CNAA0;                         isCreated=false;                         isSuccess=true;])   What would be the best way to achieve this.
85068
In SQL Server 2012,    I create two tables TABLE1 and TABLE2 After that, I created a trigger for TABLE1 Trigger name: PUSH_TABLE2  SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO  CREATE TRIGGER [dbo].[PUSH_TABLE2]     ON [dbo].[TABLE1]     AFTER INSERT AS BEGIN     DECLARE @col1 VARCHAR(20), @col2 VARCHAR(20), @col3 VARCHAR(20)     SELECT @col1=column1, @col2=column2, @col3=column3 FROM INSERTED      SET NOCOUNT ON;      INSERT INTO [dbo].[TABLE2] VALUES (@col1, @col2, @col3);  END  After creating the trigger PUSH_TABLE2, I test with below insert query manually on TABLE1, triggers works perfectly and its populate the data to both TABLE1 and TABLE2.  INSERT INTO TABLE1 VALUES('session1', 'value1', 'type1');  (1) rows affected.  (1) rows affected.    The problem is if the data is populated through application, it will only populate the data to TABLE1 only, seems trigger is not working. Is it because of my trigger script problem?
323
I'm having issues with creating a pretty simple test Utility Class. I want to create two records: an account and a related child contact. The error I see in the developer console is:     Variable does not exist: a.ID   My code, based on the Salesforce Apex Workbook, is as follows. I've played around with various things, but it's not working. Where am I going wrong? Thanks in advance.  @isTest public class AccountSaveTestSuite {      public static Account createOneAccount(){           Account testAccount = createAcct('ABC Computing inc.');              Contact testContact = createContact();          return testAccount;             }      // Helper methods //     //        private static Account createAcct(string accountName) {          Account a = new Account(             Name=accountName);         insert a;         return a;     }      private static Contact createContact(){         Contact c = new Contact (             FirstName = 'Jane'              , LastName = 'Smith'             , Account = a.ID); // *** Error is here ***         insert c;         return c;      }  }
854
I am trying to copy the value of user selected Status value into the standard salesforce required Company field. Now, when I try to save the record on the object since I am not entering any value in the Company field, the record is not being saved. How do I solve this kind of issue? Any leads appreciated  trigger CopyStatusToTitle on Lead (before insert, after insert) {      List&lt;Lead&gt; leadList = new List&lt;Lead&gt;();     if(Trigger.isInsert){         if(Trigger.isBefore){             //process before insert               for(Lead l : trigger.New){                 l.Company = l.Status;              }          }else if(Trigger.isAfter){             //process after insert          }       } }