function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Vladimir BessonovVladimir Bessonov 

trigger Apex code with button

Hello. How to trigger code with a button? 

I have HelloWorld trigger 

trigger CreateSparePart on Propulsion_part__c (before insert) {
    System.debug('Hello World!');
}

How to link it to the button on my lighting page? 
Abdul KhatriAbdul Khatri
Trigger code is not trigger direcly from a button, they trigger based on the context and for the sobject defined in the trigger definition like in your case (before insert) and Propulsion_part__c.

This mean your trigger will trigger when you insert a record for Propulsion_part__c sobject through User Interface, apex etc. In order for test you can make use of anonymous window as shown in the image below

User-added image

try insert a record like this
 
Insert new Propulsion_part__c (name = 'test', field2 = valure, .......)
once you execute the above code, you will see the log creates and you should be able to see Hello World

for the reference, check this 

https://trailhead.salesforce.com/en/content/learn/modules/apex_triggers/apex_triggers_intro 
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_triggers_context_variables.htm
https://trailhead.salesforce.com/en/content/learn/modules/developer_console

​​​​​​​Hope this help
Vladimir BessonovVladimir Bessonov
Yes. But I need it for real, not for the test.

Probably the following will work 
Create an action - update the object - propulsion 

trigger CreateSpareParts on Propulsion__c (update) {
    System.debug('Hello World!');
}

then in a class create a method that will actually insert the records I need to insert in the parent record 

I wonder if update will trigger Apex code only when button is pressed or for example you manually update the code in the record? 
Vladimir BessonovVladimir Bessonov
by the way how to trigger update in debug? 

update Propulsion__c; ?
Abdul KhatriAbdul Khatri

Hi

For updates you first identify the record like this

Propulsion__c propulsionToUpdate = new Propulsion__c(Id = <18 char id>);
update propulsionToUpdate;

please keep in mind in apex the best practise is to work in colllection like

 List<Propulsion__c> PropulsionToUpdateList = new List<Propulsion__c>();
Propulsion__c propulsionToUpdate = new Propulsion__c(Id = <18 char id>)

PropulsionToUpdateList.add(propulsionToUpdate);
Update PropulsionToUpdateList;

in trigger you have following trigger context related to insert and update
before insert
before update
after insert
after update
 

make sure you have define accordingly in trigger

please note trigger actions perform on the sobject or related object after performing DML OPERATIONS on the sobject of the trigger as describe above e