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
DJ 367DJ 367 

First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [Name]: [Name]

Hi All,

I have done a simple code however when I am runnung my test class I am getting error. 

Apex code:

public class AccountSaveCont{
    public Account acc{get;set;}
    
    public AccountSaveCont(){
       acc = new Account();
    }
    
    public void save1(){
        insert acc;
    }
}

Vf Page:

<apex:page controller="AccountSaveCont">
    <apex:form >
        <apex:pageBlock title="My Content" mode="edit">
            <apex:pageBlockButtons >
                <apex:commandButton action="{!save1}" value="Save"/>
            </apex:pageBlockButtons>
            <apex:pageBlockSection title="My Content Section" columns="2">
                <apex:inputField value="{!acc.name}"/>
                <apex:inputField value="{!acc.site}"/>
                <apex:inputField value="{!acc.type}"/>
                <apex:inputField value="{!acc.accountNumber}"/>
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Test Class:

@isTest(seeAllData = true)
public class AccountSaveContTest{

    public static testMethod void AccountInsert(){
    
        Account a = new Account(Name='test', phone = '1234567890');
        a.Name= 'DineshTesting1';
        insert a;
      
      PageReference pr= Page.AccountSave; 
      Test.setCurrentPage(pr);
      
    AccountSaveCont m = new AccountSaveCont();
        m.save1();
    }
}
 
Best Answer chosen by DJ 367
Kai Herng LauKai Herng Lau
Hi,

Your problem is because in the test class you didn't assign the account value back to the controller. So what my suggestion is

@isTest(seeAllData = true)
public class AccountSaveContTest{

    public static testMethod void AccountInsert(){
    
        Account a = new Account(Name='test', phone = '1234567890');
        a.Name= 'DineshTesting1';
        //insert a;
        
        PageReference pr= Page.SaveAcc; 
        Test.setCurrentPage(pr);
        
        AccountSaveCont m = new AccountSaveCont();
        m.acc = a;
        m.save1();
    }
}

Please see the highlighted part. Another thing is it will be good to use 'seeAllData = false' during testing.

All Answers

Kai Herng LauKai Herng Lau
Hi,

Your problem is because in the test class you didn't assign the account value back to the controller. So what my suggestion is

@isTest(seeAllData = true)
public class AccountSaveContTest{

    public static testMethod void AccountInsert(){
    
        Account a = new Account(Name='test', phone = '1234567890');
        a.Name= 'DineshTesting1';
        //insert a;
        
        PageReference pr= Page.SaveAcc; 
        Test.setCurrentPage(pr);
        
        AccountSaveCont m = new AccountSaveCont();
        m.acc = a;
        m.save1();
    }
}

Please see the highlighted part. Another thing is it will be good to use 'seeAllData = false' during testing.
This was selected as the best answer
DJ 367DJ 367
Hi Kai Herng Lau, Thank you so much for your time and reply. It is working perfectly fine. I think DML statement can only be used in case of Trigger not for class. Am I correct? Best regards, Dj
DJ 367DJ 367
Hi Kai herng lau,

Now I am writing for updating account . I have written test class , can you please help me to correct my code.

Apex code:
public class UpdateAccount{
    public Account acc{get;set;}
    
    public UpdateAccount(){
       acc =   [select id,name,site,type, Account Number from Account where id =: apexPages.currentPage().getParameter().get('id')];
    }
    
    public void save2(){
        Update acc;
    }
}
Vf Page:
<apex:page controller="UpdateAccount">
    <apex:form >
        <apex:pageBlock title="My Content" mode="edit">
            <apex:pageBlockButtons >
                <apex:commandButton action="{!save2}" value="Save"/>
            </apex:pageBlockButtons>
            <apex:pageBlockSection title="My Content Section" columns="2">
                <apex:inputField value="{!acc.name}"/>
                <apex:inputField value="{!acc.site}"/>
                <apex:inputField value="{!acc.type}"/>
                <apex:inputField value="{!acc.accountNumber}"/>
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>
Test Class:
@isTest(seeAllData = false)
public class UpdateAccountTest{
    public static testMethod void UpdateAccountTestM(){
    
        Account Ua = new Account(Name='test',           phone = '1234567890');
      
      PageReference pr= page.UpdateAccount;
      Test.setCurrentPage(pr);
      
   UpdateAccount m = new UpdateAccount();
        M.acc=Ua;
         M.name= 'sample';
        m.save2();
    }
}
Kai Herng LauKai Herng Lau
Hi,

This is my understanding of your code:

Apex class - Some syntax error(underline)
public class UpdateAccount{
    public Account acc{get;set;}
    
    public UpdateAccount(){
        acc = [select id, name, site, type, AccountNumber from Account where id =: ApexPages.currentPage().getParameters().get('id')];
    }
    
    public void save2(){
        Update acc;
    }
}

Visualforce page - remain unchange

Apex Text class - 
@isTest(seeAllData = false)
public class UpdateAccountTest{
    public static testMethod void UpdateAccountTestM(){
    
        Account Ua = new Account(Name='test', phone = '1234567890');
        insert Ua; //You need to save this account record first to get the Account Id
        
        PageReference pr = page.UpdateAccount;
        Test.setCurrentPageReference(pr); 
        System.currentPageReference().getParameters().put('id', Ua.Id); //Assign the Account Id to current URL
        
        UpdateAccount m = new UpdateAccount();
        M.acc=Ua;
        M.acc.name= 'sample'; //M is just refer to the Constuctor, you need to point to the account object
        
        m.save2();
    }
}

Hope my understand is correct to your code is correct.
 
DJ 367DJ 367
Hi Kai Herng Lau,

Thanks for you reply. solution worked.
Now I am combining Save,Update and Delete action in once VF page. Update and delete is working fine but Save is throwing error as below

System.DmlException: Insert failed. First exception on row 0 with id 0012800001Wr1wcAAB; first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id]
Error is in expression '{!SaveAc}' in component <apex:commandButton> in page accsaveupdatdel: Class.AccountSaveUpdateDel.SaveAc: line 15, column 1
Class.AccountSaveUpdateDel.SaveAc: line 15, column 1

My code is here.
<apex:page controller="AccountSaveUpdateDel">
    <apex:form >
        <apex:pageBlock title="My Content" mode="edit">
            <apex:pageBlockButtons >
                <apex:commandButton action="{!SaveAc}" value="Save"/>
                <apex:commandButton action="{!UpdateAc}" value="Update"/>
                <apex:commandButton action="{!DelAc}" value="Delete"/>
            </apex:pageBlockButtons>
            <apex:pageBlockSection title="My Content Section" columns="2">
                <apex:inputField value="{!acc.name}"/>
                <apex:inputField value="{!acc.site}"/>
                <apex:inputField value="{!acc.type}"/>
                <apex:inputField value="{!acc.accountNumber}"/>
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>
 
public class AccountSaveUpdateDel {

    public Account acc {get;set;}
    
  public AccountSaveUpdateDel(){
      acc = new account();
      acc =[SELECT Id, Name, Site,AccountNumber,Type FROM Account  WHERE Id = :ApexPages.currentPage().getParameters().get('id')];
    }
    
    public void UpdateAc(){
        update acc;
    }
    
    public void SaveAc(){
         insert acc;
    }
    
    public void DelAc(){
        Delete acc;
    }
}

Can you please help me to fix this. Many thanks.

Regards,
Dj​
Kai Herng LauKai Herng Lau
Hi Dj,

This is what I'm thinking
 
public class AccountSaveUpdateDel {

    public Account acc {get;set;}
    
    public AccountSaveUpdateDel(){
        if(ApexPages.currentPage().getParameters().get('id') != null){
            acc =[SELECT Id, Name, Site,AccountNumber,Type FROM Account  WHERE Id = :ApexPages.currentPage().getParameters().get('id')];
        }else{
            acc = new account();
        }
    }
    
    public void UpdateAc(){
        update acc;
    }
    
    public void SaveAc(){
         insert acc;
    }
    
    public void DelAc(){
        Delete acc;
    }
}

but may I know how is the visualforce page being called? Is it from a button or from others apex code to pass in the account id into the url?
DJ 367DJ 367
Hi Kai Herng Lau,

Sorry for late reply. Thanks for your reply. given code worked. 

Many thanks.
DJ 367DJ 367
Hi Hi Kai Herng Lau,,

Can you please help me writing code for EDIT BUTTON. my code is here..
VF Page:

<apex:page standardController="Account" extensions="AccountSaveUpdateDel"> 
<apex:pageMessages id="ErrorMessages"/>
 <apex:form id="frm" >
        <apex:pageBlock title="My Content" mode="edit" id="blk">
            <apex:pageBlockButtons >
                <apex:commandButton Id="SaveButton" action="{!SaveAc}" value="{!$Label.EU_BUTTON_SAVE}"/>
                <apex:commandButton Id="EditButton" action="{!UpdateAc}" value="{!$Label.EU_BUTTON_EDIT}" />
                <apex:commandButton Id="DeleteButton" action="{!DelAc}" value="{!$Label.EU_BUTTON_DELETE}"/>
                <apex:commandButton Id="CancelButton" action="{!CancelAc}" value="{!$Label.EU_BUTTON_CANCEL}" immediate="true"/>
            </apex:pageBlockButtons>
            <apex:pageBlockSection title="My Content Section" columns="2">
                <apex:inputField value="{!acc.name}"/>
                <apex:inputField value="{!acc.site}"/>
                <apex:inputField value="{!acc.type}"/>
                <apex:inputField value="{!acc.accountNumber}"/>
                <apex:pageblocksectionItem >
                    <apex:outputlabel value="{!$ObjectType.Account.Fields.AccountSource.label}" />
                    <apex:outputPanel >    
                        <apex:actionRegion >
                            <apex:inputField value="{!acc.AccountSource}" required="true">
                                <apex:actionSupport event="onchange" reRender="blk1,WebSec,PhoneSec,PRSec"/>
                            </apex:inputField>
                        </apex:actionRegion>
                    </apex:outputPanel>
                </apex:pageblocksectionItem>
            </apex:pageBlockSection>
            
            <apex:pageBlock id="blk1" >
                <apex:pageBlockSection id="WebSec" rendered="{!acc.AccountSource == 'Web'}">
                    <apex:inputField value="{!acc.Web_website_URL__c}"/>
                    <apex:inputField value="{!acc.Web_Enquiry_Date__c}"/>
                    <apex:inputField value="{!acc.Web_Helpful__c}"/>
                    <apex:inputField value="{!acc.Website_Remark__c}"/>
                </apex:pageBlockSection>

                <apex:pageBlockSection id="PhoneSec" rendered="{!acc.AccountSource=='Phone Inquiry'}">
                    <apex:inputField id="PhnEnqPhn" value="{!acc.Inquiry_Phone_No__c}"/>
                    <apex:inputField id="PhnEnqNme" value="{!acc.Agent_Name__c}"/>
                    <apex:inputField id="PhnEnqDte" value="{!acc.Phone_Date__c}"/>
                    <apex:inputField id="PhnEnqRmk" value="{!acc.Phone_Remark__c}"/>
                </apex:pageBlockSection>
                
                <apex:pageBlockSection id="PRSec" rendered="{!acc.AccountSource=='Partner Referral'}">
                    <apex:inputField id="PREnqUrl" value="{!acc.PR_Name__c}"/>
                    <apex:inputField id="PREnqDate" value="{!acc.PR_Date__c}"/>
                    <apex:inputField id="PREnqEmail" value="{!acc.PR_Email__c}"/>
                    <apex:inputField id="PREnqRmk" value="{!acc.PR_Remark__c}"/>
                </apex:pageBlockSection>
             </apex:pageBlock>           
        </apex:pageBlock>
    </apex:form> 
</apex:page>
 
// Apex code

public class AccountSaveUpdateDel {

    public Account acc {get;set;}
    public boolean editMod{get;set;}
    string urld = ApexPages.currentPage().getParameters().get('id');
    
  public AccountSaveUpdateDel(ApexPages.StandardController Controller){
     editMod = false;
         if(urld != null){
            acc =[SELECT Id, Name, Site,AccountNumber,Type,AccountSource FROM Account  WHERE Id = :urld];
            //acc =[SELECT Id, Name, Site,AccountNumber,Type FROM Account  WHERE Id = :ApexPages.currentPage().getParameters().get('id')];
        }
        acc = new account();
    }
    
    public pageReference UpdateAc(){
    try{
        if(acc.id != null){
            update acc;
        }
    }catch(Exception e){
            system.debug(e);
        }
        return new pageReference('/'+acc.id);
    }
    
    public pageReference SaveAc(){
        try{
            if(acc.id == null){
                insert acc;
                
            }
            }catch(Exception e){
                system.debug(e);
            }           
         
        return new PageReference('/'+acc.id);
    }
    
    public pageReference CancelAc(){
        if(urld != null){
            return new PageReference('/'+ ApexPages.currentPage().getParameters().get('id'));   
        }
        else{
            
            return new pageReference('/'+ ApexPages.currentPage().getParameters().get('retUrl'));   
        }
        
    }

    public void EditButtonEn(){
        if((ApexPages.currentPage().getParameters().get('editMode') == null ) && ApexPages.currentPage().getParameters().get('retUrl') == null ){
            editMod = false;
        }
        else{
            editMod = true;
        }
    }
    
    public pageReference DelAc(){
    
       try{ 
           if(acc.id != null )
            Delete acc;
        }
        catch(Exception e){
            system.debug(e);
        }
         return null;
    }
}

Like if I click on EDIT Button record to be on edit mode.

Thanks in advance,
Dj
 
Kai Herng LauKai Herng Lau
Hi Dj,

I'm not sure if I understand your requirement correctly, but here is my suggestion:
 
   .....
   public pageReference UpdateAc(){
        try{
            //if(acc.id != null){
                //update acc;
            //}
            String myDomain = URL.getSalesforceBaseUrl().toExternalForm();
            String editURL = myDomain +'/'+acc.Id+'/e?retURL=%2F'+acc.Id;
            
            PageReference result_page = new PageReference(editURL);
            return result_page;
        
        }catch(Exception e){
            system.debug(e);
        }
        return new pageReference('/'+acc.id);
    }
    ......
What I'm trying to do here is redirect you back to normal salesforce edit page based on the account id passed in.

I also found another issue on your apex code line 15, this will alway return you the new account cause you didn't have an else wrapper it this is what my suggestion:
 
public AccountSaveUpdateDel(ApexPages.StandardController Controller){
        editMod = false;
        if(urld != null){
            acc =[SELECT Id, Name, Site,AccountNumber,Type,AccountSource FROM Account  WHERE Id = :urld];
            //acc =[SELECT Id, Name, Site,AccountNumber,Type FROM Account  WHERE Id = :ApexPages.currentPage().getParameters().get('id')];
        }else{
            acc = new account();
        }
    }