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
Himanshu ShekharsHimanshu Shekhars 

apex code bug

hello  everyone,
    my question is whenever i refresh the page in backend it perform DML operation(this code run beyond the concept(bug or error) so please check and comment here or there ) but when i click on save button at second time then it's showing a error message.

so link of my video is :
https://www.youtube.com/watch?v=-SlutmT3htw
<!--   VisualForcePage   -->

<apex:page Controller="AccountController" >
    <apex:form >
    <apex:pageBlock title="Account Details">
        <apex:pageBlockSection title="Details Section"    >
        <apex:inputField value="{!acc.name}" />
            <apex:inputField value="{!acc.phone}" />
            <apex:inputField value="{!acc.type}" />
            <apex:inputField value="{!acc.industry}" />
        </apex:pageBlockSection>
                <apex:pageBlockButtons >
        <apex:commandButton action="{!save}" value="save" />
        </apex:pageBlockButtons>
        </apex:pageBlock>
    </apex:form>
</apex:page>



// Controller

public class AccountController {
Account ac;
    public  AccountController(){
   ac = new Account();
    }
    public account getacc()
    {
        return ac;
    }
    public void save()
    {
insert ac;
    }
}

 
Alain CabonAlain Cabon
Hi,

You should use upsert instead of insert.
 
public void save()  {
     upsert ac;
}

Using the upsert operation, you can either insert or update an existing record in one call. 
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_dml_examples_upsert.htm