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

Creating new record with Apex Trigger

I have a custom object called Charter with a lookup relationship with accounts. I have created an apex trigger in opportunity to create Charter records. I am not getting any errors with the trigger but the records are also not created.

Does anyone knows why is this happening or is what I am trying to do even possible?
Alex TennantAlex Tennant
It is definately possible. Are you able to provide your code so that we can see where you are going wrong?
The first and most importnat thing is check you trigger is it executing or not on events in which you are expecting it.

Use System.debugs to identify what going on. Also, in system debugd check if any DML in happenning or not.
Clay AshworthClay Ashworth
Usually when I find something like this with a trigger I have written it is generally attributable to one of three conditions.

1. My opening IF statement is excluding the records for which I want to trigger to fire on.
2. When creating related objects make sure the trigger is firing after insert.
3. Make sure you are including all required fields for the related objects being created.
Thank you everyone. I was able to get this going but I have a follow up question. How do I get the ID of the record that was just created?
Alex TennantAlex Tennant
When you perform an insert the Id field is automatically populated for you. You will need to re-query the object to get the values of any formula fields or fields that have been updated by workflow rules.

Account a = new Account();
insert a;

// The Id field is now populated

// Do something with a.Id, such as query for updated fields
a = [SELECT FormulaField__c FROM Account WHERE Id = :a.Id];

Thank you Alex, I had to make few changes but it is working now.