2

I have a custom save method, which saves my object and redirects me to his parent. This works fine for me and I used this kind of approach very often.

Visualforce Page:

<apex:commandButton value="Save" action="{!saveAndRedircet}"/>

Controller:

public PageReference saveAndRedirect() {
        PageReference result = null;

        try {
            upsert myObject;

            result = new PageReference('/' + myObject.mdr_Parent__c);
        }
        catch(Exception ignore) {}

        return result;
    }

Question:

Now I have found a very nasty behavior. If I hit this Save Button multiple times before I get redirected, multiple records of this new object are created. Multiple objects with the same information are prohibited and normally it is not possible to created them.

How can I prevent this behavior ? That problem doesn't exists with the default save button. I found a few Javascript hacks, but I don't like this kind of "solutions".

1

I would Agree to Lucid's solutions.

Solution1: Render the save button based on this flag i.e set a boolean variable to 'False' as soon as the function is called and render the command button based on this variable.

Solution 2: Write a select query in the function based on a unique ID in the object. If the query returns something, do not insert otherwise insert. Here's the sample code:

VF page:

<apex:commandButton value="Save" action="{!saveAndRedircet}" rendered="{!flag}"/>

Controller:

 public boolean flag{get;set;}

   public PageReference saveAndRedirect() {

     flag=false;
    PageReference result = null;

    try {
         list<MyObject__c> listMyObj = [Select <fieldNames> from MyObject__c where uniqueID=:your_unique_ID_from_VF_Page];
         if(listMyObj.size()==0)
          insert myObject;
          else
        upsert myObject;

        result = new PageReference('/' + myObject.mdr_Parent__c);
    }
    catch(Exception ignore) {}

    return result;
}

This code has both the above solutions implemented. Let me know if this works!

| improve this answer | |
0

One simple method would be to set a boolean 'pressed' to true in saveAndRedirect method, and check for it at the top of the method, only continuing if it is false. Alternately, do a SOQL query to see if your object already exists prior to upserting or utilize an externalId with your upsert so that it only updates rather than duplicating.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.