1

I can't see why I'm getting this error. I'm using a VF page in the edit mode of a record. I am attempting to create a select list with a query in the controller. When the user chooses something for the Vendor__c the selection/option list shows all the record names available from the Vendor_Product__c child object. That is working properly. The list is produced, and the chosen selections are put into the selectList 'names'. on the Visual Force page. Upon saving I would like to put those values into a text field (Products_Affected3__c).

But when I save I get this error : "System.DmlException: Insert failed. First exception on row 0 with id a7w560000004CAMAA2; first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id]"

I don't understand why I'm getting this. I can't figure out where I am specifying the ID.

Here is my controller :

public class MycontrollerSFDC
{
    String policyid;
    public Policy_Profile__c policy{get;set;}
    public string relatedVendor{get;set;}
    public List<String> names{get;set;} // As multi select, that's why changes from string to list
    public string vendorid{get;set;}
    public string selectedvendorid{get;set;}
    public Name policynew{get;set;}

    public SelectOption[] SelectedProducts { get; set; }

    public MycontrollerSFDC(apexpages.standardcontroller controller)
    {
        policy = new Policy_Profile__c();
        policyid=system.currentpagereference().getparameters().get('id');

        if(policyid!=null)
        {
            policy=[select Vendor__c,Products_Affected3__c from Policy_Profile__c  where id =:policyid];
            relatedVendor=Policy.Vendor__c;
        }
    }

    public pageReference execute()
    {
        vendorid=policy.Vendor__c;
        System.debug('########'+vendorid);
        return null;
    }

    public list<selectoption> getitems()
    {
        List<selectoption> options= new list<selectoption>();
        SelectedProducts = new List<SelectOption>();
        if(vendorid != null)
        {
            Vendor_Profile__c a =[select name, ( Select Id, Name from Vendor_Products__r) from Vendor_Profile__c where id =:vendorid]; //Query the Products for the chosen Vendor
            for(Vendor_Product__c s : a.Vendor_Products__r)
            {
                options.add(new SelectOption(s.name,s.name)); 
            }
        }
        else
            options.add(new SelectOption('','None'));

        return options;
    }

    public void save()
    {
        System.debug('********************************' + names);

        // Added for multi select
        String products = '';

        for( String str : names )
        {
            products += products + ';';
        }

        products = products.subString( 0, products.length() - 1 );
        policy.Products_Affected3__c=products;
        // Added for multi select
        insert policy;

        policy=new Policy_Profile__c  ();
        System.debug('********************************' + policy);
    }
}

The Visual Force page which uses it is this :

<apex:page standardcontroller="Policy_Profile__c" extensions="MycontrollerSFDC">
<apex:messages />
    <apex:sectionheader title="{!$ObjectType.Policy_Profile__c.label} Edit" subtitle="{!IF(ISNULL(Policy_Profile__c.Name), 'New Policy Profile',Policy_Profile__c.Name)}"/>
    <apex:form >
        <apex:pageblock mode="edit" title="{!$ObjectType.Policy_Profile__c.label} Edit">
            <apex:pageblockbuttons >
                <apex:commandbutton value="Save" action="{!Save}"/>
                <apex:commandbutton value="Cancel" action="{!Cancel}"/>
            </apex:pageblockbuttons>

            <!-- **********   [Record Type : Master ]   **********  -->
            <apex:outputpanel id="ProductsDetails" >
                <apex:pageblocksection title="Information" showheader="true" columns="2">
                    <apex:inputfield value="{!Policy_Profile__c.Name}" required="true"/>
                    <apex:outputfield value="{!Policy_Profile__c.OwnerId}"/>
                    <!--<apex:inputfield value="{!Policy_Profile__c.Vendor__c}" required="false"/>-->
                    <apex:pageblocksectionitem />

                    <apex:pageblocksectionitem />
                </apex:pageblocksection>

                  <apex:pageblocksection columns="2">

               <apex:inputfield value="{!policy.Vendor__c}" required="false" >
               <apex:actionSupport event="onchange" action="{!execute}"             
                    rerender="ProductsDetails,SelectedProducts,ProductsAffected" immediate="false" /> 
              </apex:inputfield>
             <apex:inputfield value="{!Policy_Profile__c.Products_Affected3__c}" required="false"/>
         </apex:pageblocksection>

         <apex:pageBlockSection title="Products" id="SelectedProducts">

              <apex:pageBlockSectionItem >  
                <apex:outputLabel >Press Ctrl to select multiple subs:</apex:outputLabel>  
                    <apex:selectList value="{!names}" multiselect="true" size="6">
                    <apex:actionSupport event="onclick" action="{!execute}"             
                        reRender="field"/>
                    <apex:selectOptions value="{!items}"/>
                        </apex:selectList> 
                </apex:pageBlockSectionItem> 

             <apex:pageBlockSectionItem >  
                <apex:outputLabel >Products Selected:</apex:outputLabel> 
                <apex:outputtext value="{!names}" id="field"/> 
             </apex:pageBlockSectionItem> 
         </apex:pageBlockSection>

            </apex:outputpanel>
        </apex:pageblock>
    </apex:form>

</apex:page>

Can anybody give me some input on this ? Thank you very much.

3
  • 2
    try to replace insert policy with upsert policy as suggested by @kurunve
    – San
    Aug 12, 2015 at 19:04
  • It worked - but I still don't see where I was naming the ID. Was the code somehow making it save twice or something weird like that ?
    – Zoom_v
    Aug 12, 2015 at 19:45
  • 2
    You are initializing policy in constructor where ID is assigned and later on save same object is being used for insert.
    – San
    Aug 12, 2015 at 20:12

1 Answer 1

1

It seems that you are trying to insert a record with provided ID, that is impossible because record is created already.

Probably you need to update it - use update statement instead of insert.

In case if you are not sure if record exists - use upsert (it works as update for record with given id and as insert for record with missing id in general).

Here you can read more about upsert: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_database.htm#apex_System_Database_upsert_2

1
  • kurunve - Thank you very much for your input. The Upsert did the trick. But for some reason it's not saving the selections into the Products_Affected3__c field. I've debugged and the 'products' variable isn't being populated. Any idea why that might be ?
    – Zoom_v
    Aug 12, 2015 at 19:36

You must log in to answer this question.

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