Hot answers tagged

11

To me, this does seem like a valid requirement. Few years back I too asked a similar question. Making context-aware application are sometimes needed. This is one such use case. Yes, You can get this done. The trick is to look in URL of the request. Everything in SF happening will have a request. So I just wrote a trigger on a Custom Object to see, if we ...


8

This pattern is likely to cause tricky-to-debug issues in the future. When your trigger is invoked via updates made in a Batch Apex class, you will get an exception stating that you've enqueued too many jobs at 2. Too many queueable jobs added to the queue: 2 As you may know, the limit per transaction is 50 (so if you're enqueuing five Queueables per ...


8

We use the object oriented approach of using non-static methods because of the massive benefits we can derive in unit testing (and potentially also in production cases, though we don't do that yet). We take a "dependency injection factory method" or "dependency injection singleton access" approach. Each of our trigger handlers provides an interface or set ...


7

If you don't care about the delete contexts, you can just do: SObjectType triggerType = trigger.new.getSObjectType(); It doesn't add much complexity, however, to use a ternary to check for the null case: SObjectType triggerType = trigger.isDelete ? trigger.old.getSObjectType() : trigger.new.getSObjectType();


7

The best place to start and learn about SOQL, SOSL and Triggers is Apex Basics & Database at trailhead. SOQL can be used in Triggers but SOSL is not. The idea to allow it has been raised away long back. You can upvote it:- Allow SOSL queries in Triggers SOSL queries are only supported in Apex classes and anonymous blocks. You cannot use a SOSL ...


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 ...


7

No, it is not technically possible. Synchronous callouts in Triggers are not allowed. There is an Idea to have Salesforce do this, but it's already a decade old, and may never be implemented. The main concern about callouts during triggers is that it will significantly increase database contention, which may cause deadlocks as the database has to hold record ...


6

AFAIK there is no way to do this without adding explicit logic. And that explicit logic is pretty ugly e.g. make the WF and PB set database data or static variables that signal they have run and then have the trigger check those. Which couples the pieces together horribly. If possible, write the trigger so it is idempotent i.e. nothing bad happens even if ...


6

Conceivably what you could do is set up a Queueable class. On the first pass through the trigger, instantiate and enqueue it, and then save that in a static variable so you know it's already been created. It will run once after all executions are done, in a separate transaction. The trouble is, once you have enqueued it, you can no longer alter any data you'...


6

You can use Sobject get and put method to your advantage. This allows you to dynamically refer and set fiels in any Salesforce Record . I would go by adding all children in a Generic List, then iterate over it and assign new recordTypeId accordingly. So my code will be like: List<Sobject> genericChildList = new List<Sobject>(); ...


6

The idea that nested for loops are bad seems to be a common one, but it is at best an overgeneralization. There are many problems for which a nested for loop is the the most idiomatic solution - iterating over nested containers, for example. Where you don't want nested for loops is when they represent a needless increase in computational complexity - taking ...


6

Apex language evolves every 4 months, with every Salesforce release. I can definitely say there would have been many bugs in v20 which have been fixed over time. Now there can be code, which relies on bug or side-effect of the bug to get things, done. Now when you increase API version the side-effect would go and in some case can break your logic. eg: ...


6

This error has to do with the trigger context, not with the literal location of the query in the source code. It looks like your query is located within a trigger handler, meaning it's executed after being called from the trigger and therefore is running in trigger context. So let's look at this query. SELECT id, Vmstar_Id__c, GSS_Duplicate_Case__c, ...


6

It only works on trigger context records, but it can be applied to those records outside of a trigger. You cannot call this method on a record which is not yet in a trigger context, then have the error carry through to the trigger context. This code won't prevent DML: Account record = new Account(); record.addError('You cannot insert this record'); insert ...


6

This is because you are using an aggregate query on Contact: for (AggregateResult ar: [Select Count(Id) ContactCount, AccountId from Contact where AccountId IN: AccountIds GROUP BY AccountId]) Once the final Contact is deleted, there's nothing to aggregate, so you will not see an AggregateResult with that Contact's AccountId and ...


6

opp.get(metaData.get(0).Opportunity_Field_Name__c) = opp.Account.get(metaData.get(0).Account_Field_Name__c); The result of opp.get() is not an lvalue; it does not represent a location to which you can assign a value on the left-hand side of an assignment statement. Put another way, it returns a value, but not a reference to the value's location. The ...


5

You appear to have a different species of lock contention than other questions we've seen recently about implicit lock contention, leading to UNABLE_TO_LOCK_ROW errors. What you have is a situation where two elements of your application are attempting to establish an explicit lock using a SOQL FOR UPDATE clause at the same time, resulting in one of the lock ...


5

It sounds like you are looking for an exit event. If doesn't exist yet, but you can vote for the idea, the description of which is pasted below: Since triggers only handle 200 records at a time, it would be convenient if we could schedule some code that runs in the same transaction as the current transaction, but after all other triggers, recursion, etc ...


5

Triggers are supposed to work that way. They do not pre-populate data on the screens but only update it during the transaction. Out of the box, you will not be able to pre-populate data. If you can create some lightning component, then you can utilize force:createRecord event here which lets you to open the standard screen for record creation with an option ...


5

Triggers don't work like that, unfortunately. Triggers are a database construct that allow you to perform work when there is a change to the database (insert, update, delete, undelete), and reading a record from a database generally doesn't cause any change. Instead, what you'll probably want to look into is including an inline visualforce page in your ...


5

If I understand your question correctly, then you actually can take your related record update logic and put it in either a before or after trigger. Salesforce's suggestion is that before triggers should be used to update data on the records taking part in the trigger (the ones stored in trigger context variables), but it's just that... a suggestion. ...


5

You're calling a method with a single Account parameter: Parent_Subtract.executeSub(acct); but this method is defined to take a List<Account> as its parameter: public static void executeSub(List<Account> scope) This method is bulkified: it is defined to run exactly one DML operation: update listforFinalUpdate; regardless of how many ...


5

Apex is superior in all three categories for maintainability, scalability, and efficiency. Flows typically take longer to edit than code, do not run efficiently, and may cause problems on bulk updates. If you're given a choice, prefer using Apex when possible. Flows are really only meant for simple logic.


5

What you have will still work because you are referring the field name here. con.fieldName__c = 'Abc'; You can additionally use Sobject.put(fieldName, value) here if you want to refer the API name as string value, as: con.put('fieldName__c', 'Abc');


5

Triggers are not classes, and you shouldn't reference them like this. You should create a separate class to store your static variable, and then reference this class in both your controller and trigger.


5

The constructor syntax is incorrect. We write constructor as a method() with no return type. public with sharing class Myfirstvfclass { public list<Account> lacc { get; set; } public Myfirstvfclass() { lacc=new list<Account> ([select id from Account]); } } You can read more about Constructors in apex here: https://...


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, ...


5

Using boolean flags is often something of a bodge. As well as stopping the undesired unlimited recursion, it can stop the logic from settling to the correct values. Best to first think through the sequence of inserts and updates and aim to eliminate the recursive cases. A simple cause of the recursion limit problem is updating the object - making a DML ...


5

If you adopt the Enterprise Patterns as defined by Andrew Fawcett, VP at SFDC and formerly CTO of FinancialForce, you will quickly realize the advantage of the underlying principle of separation of concerns into: Service layer Domain layer Selector layer Unit of Work A trigger is merely an entry point to the domain layer and typically is coded as a single ...


5

StepsAndWorkitems is not a type, it is a child relationship name for ProcessInstanceHistory, so type should be ProcessInstanceHistory and not StepsAndWorkitems. Excerpt from the salesforce documentation The nested query references StepsAndWorkitems, which is the child relationshipName for ProcessInstanceHistory in the ProcessInstance object. You ...


Only top voted, non community-wiki answers of a minimum length are eligible