I have a VFPage with Account Fields and one Button as "Save&AddContact",
- when i click on this button Account record is inserted and current page is navigate to another page which have Contact Fields.
- The second Page have a Buttons like "Save" and "Save&New".
when i click on Save&New Button the Current Records is successfully inserted and become child for Account and need to redirect same page.
This should be process no of times based on requirement. But when i insert second contact i am getting error like "Before Insert or Upsert list must not have two identically equal elements
Error is in expression '{!insertContact}' in component in page accounttocontatdata: Class.AccountData.insertContact: line 20, column 1
here is my code
Controller:
public class AccountData{
public Account acclst {set;get;}
public contact conlst {set;get;}
public List<Contact>cons {set;get;}
public AccountData(){
acclst=new Account();
conlst=new Contact();
cons= new List<Contact>();
}
public pagereference convert(){
insert acclst;
pagereference pg=new pagereference('/apex/AccountToContatData');
return pg;
}
public PageReference insertContact(){
Account a=[select id,name from account where id=:acclst.id];
conlst.AccountId=a.id;
cons.add(conlst);
insert Cons;
PageReference pg1 = ApexPages.currentPage();
pg1.setRedirect(true);
pagereference pg=new pagereference('/apex/AccountToContatData');
return pg;
}
}
VFPage 1:
<apex:page controller="AccountData" >
<apex:sectionHeader title="Account" />
<apex:form >
<apex:pageBlock >
<apex:pageBlockSection title="Acount Details">
<apex:inputField value="{!acclst.Name}"/>
<apex:inputField value="{!acclst.phone}"/>
<apex:inputField value="{!acclst.type}"/>
<apex:inputField value="{!acclst.ShippingAddress__c}"/>
</apex:pageBlockSection>
<apex:pageBlockSection title="Additional Information">
<apex:inputField value="{!acclst.BillingCity__c}"/>
<apex:inputField value="{!acclst.BillingBranch__c}"/>
</apex:pageBlockSection>
<apex:pageBlockButtons >
<apex:commandButton value="save&AddContact" action="{!convert}"/>
</apex:pageBlockButtons>
</apex:pageBlock>
</apex:form>
</apex:page>
VfPage2:
<apex:page controller="AccountData" id="d">
<apex:sectionHeader title="AccountToContact"/>
<apex:form >
<apex:pageBlock id="o" >
<apex:pageBlockSection columns="2" >
<apex:inputField value="{!conlst.LastName}"/>
<apex:inputField value="{!conlst.FirstName}"/>
<apex:inputField value="{!conlst.Email}"/>
<apex:inputField value="{!conlst.phone}"/>
<apex:inputField value="{!conlst.Address__c}"/>
<apex:inputField value="{!conlst.Department}"/>
</apex:pageBlockSection>
<apex:pageBlockButtons location="bottom">
<apex:commandButton value="save" />
<apex:commandButton value="save&New" action="{!insertContact}" reRender="o"/>
<apex:commandButton value="Home"/>
</apex:pageBlockButtons>
</apex:pageBlock>
</apex:form>
</apex:page>