Stack Exchange Network

Stack Exchange network consists of 175 Q&A communities including Stack Overflow, the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Visit Stack Exchange

New answers tagged

0

The best approach to this would be, in my opinion, to create a hidden field to store the Id of the account on the top of the hierarchy, and fill it with a trigger, process or workflow rule. Scenario 1: Top account is created Child account is created, but parent account is not related yet. User remembers that the accounts are related, and fills the "parent ...


3

Yes, you can consider your code bulkified. You have only 1 SOQL outside of loop. You don't have any DMLs I don't see any method invocations with potentials DML/SOQL. You iterate over trigger.new collection But I would give a few pieces of advice on how you can improve your code. I'll mostly reference Salesforce docs, but still. Rename your Trigger to ...


2

You have to perform update crList DML in order to persist your changes when (a) working outside of a before context or (b) working on queried sObjects, rather than those accessed directly via Trigger.new. Both are the case here. Additional notes: You do not need this loop at all: for(Call_Report__c cr : trigger.new){ It's costing you needless, ...


3

Yes, in an after update trigger, you'd need a DML operation. However, this will cause an infinite loop. Instead, do this logic in a before update trigger: trigger Call_Report_AfterUpdate on Call_Report__c (before update) { Map<Id, AggregateResult> tasks = new Map<Id, AggregateResult>([ SELECT COUNT(Id) sum, WhatId Id FROM Task WHERE WhatId ...


5

Ideally for such kind of requirements, it would be better if you can build the logic in before update event rather than after update event, in which case, there won't be any need to handle the recursion and you won't need to write the DML (update) statement as well which would make this the safest approach. If you still want to go with after update event, ...


3

As oposed to BEFORE triggers, changes made to trigger.new don't persist in Database. That's because in before context, there's still a dml operation to be made, before doing it, we alter the contents of the records in trigger.new and when the dml operation is done the new values are already there. But after the dml is done, there no dml to be made so you ...


1

I am working on a similar issue I found alot of help and a solution to this using the following website https://jdspaceit.wordpress.com/2016/01/13/traversing-through-an-accounts-hierarchy-in-apex/ //find highest parent account from a child public id findTopLevelParent(account a) { Boolean isTopLevelAccount = false; account acct = new account(); ...


1

@DavidReed has a pretty clever answer but is not necessarily a guarantee of success without more knowledge of which specific Accounts and their Opportunities incur the CPU time restriction I'm going to offer two suggestions Option1 Data Loader (The tried and true) I get the impression that this task you have is a relatively infrequent event. If so, use ...


0

I've been using a lot of System.debugs and unit tests. Not into the Log Replay Debugger idea even though it is better than what I am doing right now. I don't know how they could create an actual debugger other than creating a Cloud Code Editor.


4

The CPU time limit is a cumulative limit across the whole transaction. Essentially, what is happening is that your Flow, plus your Process invocations, plus the NPSP triggers that are run consequent upon the updates you are making, are taking too long to execute in a single transaction (10 seconds of CPU time). Because the CPU time limit is a cumulative ...


3

Yes, we can add more complicated logic in a trigger. Traditionally, we offload the trigger logic in to a "trigger handler" class, as demonstrated in this answer. However, to keep things simple, this is how we'd add the new logic to your trigger: trigger AutoConvert on Lead (before insert, after insert) { switch on Trigger.operationType { when ...


1

I would not do business logic inside a trigger, hand that off to a "Handler" class. That being said you don't have many options here other than to query for it, which happens to be on most organizations largest datasets. Trigger AutoConvert on Lead (after insert) { LeadStatus convertStatus = [ select MasterLabel from LeadStatus ...


0

The repeated: event AfterUpdate Contact trigger event AfterUpdate Account trigger in the stack trace suggests you also have a trigger on Account that updates Contact as well as the trigger you have posted on Contact that updates Account. This causes a never-ending loop. One way to break that is to be more selective e.g. only update the Account when the ...


2

The ChildRelationship itself has these methods: getChildSObject() Returns the token of the child sObject on which there is a foreign key back to the parent sObject. getField() Returns the token of the field that has a foreign key back to the parent sObject. getRelationshipName() Returns the name of the relationship. that provide enough ...


0

Use workflow if you need to do the below: 1- send outbound message without coding 2- need to update the same record fields or parent record fields (one level only) 3- need to create tasks (not other objects) 4- when you dont care about the order of the workflows user process when: 1- you need to preform it with order 2- when you need to send approval ...


0

Addition to PartOfTheOhana points. Salesforce encourages "no code only click" slogan and emphasizes to use workflow or process builder first then if requirement is not achievable then use trigger. For your use case, we can use workflow/PB to update field instead of trigger. But there may be performance issue in some complex org where each workflow field ...


2

Process builders are meant to replace workflow rules. They aren't meant to replace triggers. Workflows vs. PB Process Builder lets you automate more things. Process Builder lets you control the order of your criteria. Process Builder lets you access fields on every related record. Process Builder is the future. Here is a trailhead with ...


0

I'm not sure this will work, but you may be able to override the standard detail page of the Lead object with a Visualforce page to get the desired functionality. You can have a condition in the controller extension which checks for existence of the dml errors through the use of ApexPages.getMessages(). If the error is present, render the custom error page....


1

That's not how the relationship between front end and back end functionality works on Salesforce. A trigger is invoked when some DML event occurs to change a record. The source of that event could be a Visualforce or Lightning session, interaction with a standard UI page, a Batch or Scheduled or Queueable or Future Apex call with no associated UI context, ...


2

By far the simplest way to have a field on Contact that reflects the value of a field in Account is to make the Contact field a formula field that automatically presents the value from the Account field.


2

The cleanest way to generate JSON in Apex code is to use the JSON Class and that now includes this method: public static String serialize(Object objectToSerialize, Boolean suppressApexObjectNulls) that will not serialize null values when suppressApexObjectNulls is set to true. PS If the source of the data is an SObject (or some other sort of map where ...


2

Your code is a bit hard to follow: always worth stating what you are aiming to do in the question in words and also explaining exactly what has gone wrong. Here are some general suggestions that may help: A benefit of using a handler class is that you can break pieces of logic out into separate methods so what is going on is made clearer. Don't declare all ...


7

The savepoint specifies the point to roll back to. All DML that occurs between setting the savepoint and performing the rollback is included in the rollback. If you did an update someAccount; inside your try block, you'd see the effect of that DML operation be rolled back. But that doesn't include the trigger event that started the whole process. The DML ...


0

As others have said, there are better approaches on the platform to do this. You want to get the count of records, and then convert the count to a string. Lastly, it looks like you want to pad with 0's. I think this ought to do the trick: Integer count = [SELECT count() FROM Account]; Integer maxDigits = 10; String countStr = String.valueOf(count); String ...


1

This sounds like a perfect use case for batch apex You can create a batch class that loops through all your contacts and populates the fields based on the logic you define. To run the batch, you have two options: Run in manually through the developer console using anonymous apex (which is a way of calling apex on the fly) Create a scheduled class that can ...


2

Your trigger will fail any time there is more than one OpportunityTeamMember on a record. It'll update the Opportunity.Opportunity_Shared__c field to false even when there is still an OpportunityTeamMember present other than the one deleted. You'd need to perform a query before you decide which records to update. One approach would run roughly like this: ...


2

There are a few things you need to correct in your code:- You are doing Soql query inside for loop. There is a governor limit that enforces a maximum number of SOQL Queries and if a query is inside a FOR loop, that governor limit is reached inefficiently and unnecessarily. If a query is inside a FOR loop, a query will be executed for each iteration of the ...


3

Your trigger is creating a second record rather than updating the first record. You'd want to change your code as follows: trigger HandleTrigger on Input__c (before insert) { for(Input__c record: Trigger.new) { record.YourEmail__c = 'tringtrigger@gmail.com'; } } Recursion blocking is not necessary in this case.


2

When deploying via a change set, dependencies are not automatically checked. It is important to make sure you're not missing any fields, objects, labels, etc that are dependencies for the classes to deploy, otherwise they will fail to compile, and this can cause cascading errors. It's important that you read all the deployment errors to make sure you're not ...


1

To start with, the createJob method is being called as though it were static, when it is in fact an instance method. There won't be different compilers on the sandbox and the prod org, so they can't be identical.


0

you should pass invalid values for PF event via case. please try below code and let me know if you get any issue . @isTest public class ExampleTestClass { @testSetup static void setup(){ Case testcase = new Case(Subject ='Test'); insert testcase; } @isTest static void testClassforExample(){ List<Case> lsttestcases = [SELECT Id,...


2

At times, things go wrong with test coverage calculation of test classes resulting in this behavior. Salesforce help now has a nice knowledge article: Eliminate bad code coverage data for Apex classes, quoting the information for reference: Issue: There may be times where we see a different code coverage value than the actual value. This might be ...


0

in your Test Class had couple of issues. your actual classpublishCaseUpdateNotifications method expects list so you should pass Lis<Case> instead of case your actual class method using saved list of cases not just instance of case. 3.your actual class method publishCaseUpdateNotifications returns nothing(void) but you added list<Case_Updated__e>...


0

It would also be best if you're going to include a System.DmlException e to catch all of the error the you encounter(including validation rule) Then you can include the following to output the error that you got String S1 = e.getMessage(); S1 = S1.substringBetween('FIELD_CUSTOM_VALIDATION_EXCEPTION, ' , ': ['); ApexPages.addMessage(...


2

You seem to have not initialized the accountId which is used in your SOQL as below to fetch the Contacts and thus you are not getting any results. ID accountId; // this is not assigned to the intended account's id List<Contact> contacts = new List<Contact>( [SELECT Id, Name,Do_Not_Delete__c FROM Contact WHERE ...


1

It's possible, but you have a couple of issues with your trigger. Apex Issues ID accountId; This variable is uninitialized, so it defaults to null. List<Contact> contacts = new List<Contact>([SELECT Id, Name,Do_Not_Delete__c FROM Contact WHERE AccountId = :accountId]); Then, this query is locating Contacts whose Account is ... null. That's ...


2

When we deploy any Trigger or Apex class you have to add all the components viz., Objects, ApexClass, etc., those are being referred in the Trigger/Apex class. Use View and Add Dependent Components to a Change Set in such scenarios to include all dependent components while deploying a particular component. In this case, while deploying the Trigger, you will ...


1

With a trigger involved, the addError() method of the SObject class is what you're looking for. You'll want to call that on the SObject instance(s) contained in the trigger context variables.


0

Looks like either something is querying the SObject in question (my guess being s2cor__Sage_INV_Trade_Document__c) and not also querying the field (which appears to actually be a relationship, s2cor__Sage_INV_Trade_Document_Type__r.s2cor__Use_Company_Shipping__c), or your class there isn't filling it out, with s2cor__Sage_INV_Trade_Document_Type__c only ...


0

Validation rules cannot examine "sibling" records - other records of the same object that are not related to one another directly. They also cannot perform summarization of data across multiple records. The only way you'd be able to have this summarized data available for a Validation Rule would be if all of your Users had a lookup to a single record (say "...


0

I've achieved what I wanted but not in the way I wanted to. I've taken inspiration from the answer to the question already linked in my question. I took the following steps: Select all the records in ProcessInstanceWorkItem related to the given approval process. The standard object ProcessInstanceWorkItem contains all the info about a pending approval ...


1

You cannot. Triggers fire only upon changes to the object type to which they are assigned; that is trigger MyTrigger on Account (before update) { will only ever run on changes to the Account record. While those changes may be fired indirectly through sequences of events that start with a child record update, via automation, other Apex code, or roll-up ...


2

You need to perform a DML operation for the changes to stick. That means that your code needs to keep track of the records in order to update them: Contact[] contacts = [SELECT Name, (SELECT id FROM Opportunities) FROM Contact]; for(Contact c: contacts) { c.of_Loans__c = c.Opportunities.size()+''; System.debug(c.Name + ' number of loans after: ' + c....


0

Files are uploaded before being attached to the Comment. You would have to prevent all file uploads. Otherwise a user could upload a file, then copy a link and insert it into the comment body. Why do you want to prevent file uploads in comments?


2

As per my understanding, you want all event records whose Type is not set, to be created with Type as Meeting. This can be done by setting the default value to Meeting on the Type picklist field. If you still want to do it by trigger, then this is how your trigger should be trigger FieldUpdaterofEvent on Event (before insert,before update) { for(...


2

The mg.setToaddress() method expects a parameter of type List<String> as you already know. And your mail variable is already of type List<String>. So you don't need to insert it inside a new array of type String. The right code is: mg.setToaddress(mail);


1

As multiselect picklist fields are stored as semi colon separated values, you will have to follow below steps to add/remove values to/from it. Split the values by semi colon and convert the string into List Add/Remove the element to/from the list Convert the list back to semi colon separated values using String.Join method This is how your code should look ...


1

You have to split your multi-picklist value into List of string and iterate over it and do your execution(adding a value or removing it). To split a multi-picklist value, In your case use like this:- List<String> listofmultipicklisValues= String.valueOf(newAccountValue.StopCom__c).split(';'); To iterate over the string, A sample one would be like ...


1

If you will be using this class as trigger handler, then you can access the context variables inside your handler class as well. You can call your method based on the context variables if(Trigger.isInsert){ callMethodOne(); } else if (Trigger.isUpdate){ callMethodTwo(); } Likewise, you can use rest other context variables as well in your handler ...


0

Killed two birds with one stone. Ended up being able to get this to work while also adding a layer of validation to pick the correct contact if the emails matched: trigger ContactUpdate on Coaching_Survey__c (before insert, before update) { for(Coaching_Survey__c survey : Trigger.new){ List<Contact> c = [SELECT id FROM Contact WHERE ...


Top 50 recent answers are included