+ Start a Discussion

How to clone a record of standard objects record with specific fields (not all the fields that comes when cloned)

I have a scenario like,i would like clone a record of standard object but i dont want all the fields to be come in through cloning, i want to choose specific fields from the record and clone,how could i achieve this,

your answers and suggestions will be highly appreciated,
You can create new object of the same type as your standard obj and add each field by hand:
//standard account obj we want to clone
Account accToClone = [SELECT Name, SomeOtherField FROM Account Limit 1];

//new account obj
Account acc = new Account();
acc.Name = accToClone.Name;

Hi its not working,,could you direct me with few steps like where should i use your code and how,for example i want to clone Account record with only 3 fields those are Rating,Industry,Employees (or any custom fileds etc), apart from all the fields that a standard account have.
Do you need clone object for use somewhere in the code or you want to clone a record and keep its duplicate in database?
Another important thing, that if the field of the object is another object then with "=" we will have reference on this field, not an additional copy of this field in heap.
I mean:
Account accToClone = [SELECT Id, (SELECT Id, FROM Contacts) FROM Account];
Account acc = new Account();
acc.Contacts = accToClone.Contacts; //we will get reference on contacts list
If we need real clone, we have to create new list of contacts:
List<Contact> clonedList = new List<Contact>(accToClone.Contacts);
acc.Contacts = cloneList;
So, lets say, you need just a clone object for code(actually, when we get object from SOQL, we are getting a 'clone/copy' of the records from database, so maybe this code is not what you need):
//account obj we want to clone
Account accToClone = [SELECT Rating, Industry, (SELECT Id, FROM Employees) FROM Account LIMIT 1];

//new account obj
Account cloneAcc = new Account();
cloneAcc.Rating = accToClone.Rating;  //rating is a string right?
cloneAcc.Industry = accToClone.Industry; //industry is a string right?
List<Employee> clonedList = new List<Employee>(accToClone.Employees);
cloneAcc.Employees = clonedList; //Employees is a list of obj Employee right?