1

I have a method that creates an invoice, in addition, I have another object that I use to store whether the invoice has been created. I have an issue when executing my method in the anonymous apex console. The issue is that when executing multiple (clicking multiple) times my method in the console apex will create multiple invoices. This should not happen because this extra object that I have to check whether the invoice is created is updated inside the method.

class MyClass {
    public void createInvoice(){
        if(!Util.isInvoiceInserted()){
            Util.setInvoiceStateToInserted(true);

            new Invoice__c invoice = new Invoice__c()

            insert invoice;
        }

    }
}

class Util(){
    static Booelan isInvoiceInserted(){
        InvoiceLog__c invoiceLog = [SELECT isInvoiceCreated__c FROM InvoiceLog__c LIMIT 1];

        return invoiceLog.isInvoiceCreated__c;
    }

    static void setInvoiceStateToInserted(Booelan value){
        InvoiceLog__c invoiceLog = new InvoiceLog__c(isInvoiceCreated__c = value);

        update invoiceLog;
    }
}

How can I just run my method once even if I execute my method multiple times in the anonymous console?

4
  • Can you show us the two relevant methods of the Util class? Jun 1, 2018 at 19:09
  • It sounds like you essentially have a race condition on Util.isInvoiceInserted(). That makes me think this is kind of an x-y problem and you could potentially redesign the whole process, but you'd need to share some more detail on what this is aiming to do.
    – David Reed
    Jun 1, 2018 at 19:14
  • The code you edited in will not compile or run, for several reasons.
    – David Reed
    Jun 1, 2018 at 19:19
  • It is an example, my issue is that the method will read an old value so will execute multiple times. Jun 1, 2018 at 19:30

1 Answer 1

2

You need to wait for the database to settle via record locking:

InvoiceLog__c invoiceLog = [SELECT isInvoiceCreated__c 
                            FROM InvoiceLog__c 
                            LIMIT 1 
                            FOR UPDATE];

Note that if there are no records, this throws an exception, so you might want to make it a list:

InvoiceLog__c[] invoiceLog = [SELECT isInvoiceCreated__c 
                            FROM InvoiceLog__c 
                            LIMIT 1 
                            FOR UPDATE];
return !invoiceLog.isEmpty() && invoiceLog[0].isInvoiceCreated__c;
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .