You need to sign in to do that
Don't have an account?

Problem inserting datas
Hello.
Im new at Apex and im having this problem.
I need to get an list of an object populated with Apex Data Loader and now im trying to get some fields and save into another object.
Something like it
public void createClienteCustom(){ List<Carga_Inicial__c> cargaInicial = [Select c.uf__c, c.municipio__c, c.dataCadastro__c, c.cnpjCpf__c, c.cliente__c, c.campoLivre__c, c.campoLivreAlt__c From Carga_Inicial__c c]; Cliente__c cli = new Cliente__c(); for(Carga_Inicial__c carga: cargaInicial){ cli.cnpjCpf__c = carga.cnpjCpf__c, cli.cliente__c = carga.cliente__c, cli.campoLivre__c = carga.campoLivre__c, cli.campoLivreAlt__c = carga.campoLivreAlt__c, cli.dataCadastro__c = carga.dataCadastro__c, cli.municipio__c = carga.municipio__c, cli.uf__c = carga.uf__c insert cli; } }
Im getting the following message
System.DmlException: Insert failed. First exception on row 0 with id a0AA0000002tPi0MAE; first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id]
What can i do to solve it?
Tks for all community
Actually whats happening is you declared cli variable and you are using the same cli variable inside the for loop for all the iteration in the for loop.
Below is the code change which i did.
All Answers
You need to change it to create a new instance of Cliente__c for each carga_inicaial__c, add these to a list<Cliente__c> and then process the insert outside the for loop.
Suggest you read up on Governor Limits
Actually whats happening is you declared cli variable and you are using the same cli variable inside the for loop for all the iteration in the for loop.
Below is the code change which i did.
Very Thanks Imran!
Its works Perfectly. And now i understande the flow of the method right.
Tks for all