In general...
- Use a "Before" trigger when you want to make additional changes to the records the trigger is acting on
- Use an "After" trigger for everything else
- when you want to make changes to SObjects that aren't the one that the trigger is on (i.e. if you want to make a change to the
Account
that anOpportunity
is related to, in a trigger onOpportunity
) - if you need to change records that are not the ones going through the
trigger (e.g. you want to make a change to the Account specified in
the
ParentId
field in a trigger onAccount
) - some other scenario I'm probably forgetting
- when you want to make changes to SObjects that aren't the one that the trigger is on (i.e. if you want to make a change to the
So yes, a trigger set to run before insert
(and possibly before update
) would be appropriate here.
That said, a simple calculation like this is a perfect candidate for a before-save, record-triggered flow instead. Flows are generally quicker to develop, and don't require unit tests1 to deploy.
Do note that since the page to add OpportunityLineItems to an Opportunity is provided by Salesforce out-of-the-box, you won't be able to modify it (unless you override that button), and the calculated discount will not show up on that page (as it's only calculated after you hit one of the "save" buttons).
1: Not required, but probably still a good idea. Hhaving unit tests, and running them routinely, can help detect issues that other metadata changes can introduce. It can help detect them before your users do, which is preferable to having your users inform you.