0

I have a requirement where I have to clone a parent Product2 to all of it's child Product2s.

I know we can achieve this by using clone() function of Product2, but I want some field values should not pass from parent Product to child products.

Is there any workaround for this requirement ?

1
  • What do you mean by clone() function on Product2 - do yo mean the Clone UI button? or the sObject class instance method clone(..)? – cropredy Feb 22 '16 at 4:44
0

@Surendranadh's answer is actually just portion of the solution.

What you can do is to create a field set that would contain all of the fields that you want to be copied over the child products.

Then you can reference the created fieldset on a trigger(assuming this is on a trigger context) to populate the selected fields on the child products.

Here's a sample snippet below that you can use to achieve this:

//Retrieve all Parent Products,
List<Product2> parentProducts = [SELECT Id, <List of Fields> FROM Product2 WHERE <Parent Products Query>];

//Retrieve created fieldset
List<Schema.FieldSetMember> productCloneFieldSet = SObjectType.Product2.FieldSets.<FieldSet_Name>.getFields();

List<String> fieldAPIs = new List<String>();
//Retrieve each Field API 
for(FieldSetMember fsm : productCloneFieldSet) {
    fieldAPIs.add(fsm.getFieldPath());
}

List<Product2> chldProdList = new List<Product2>();
for(Product2 parent: parentProducts) {
    Product2 chldProd = new Product2();
    //Iterate through field set API, then populate child fields using put
    for(String strAPI : fieldAPIs){
        chldProd.put(strAPI,parent.get(strAPI));
    }
    childInsert.add(chldProd);
}

//Insert all child product
insert chldProdList;

**NOTE: ** My code just assumes that I'll be cloning the parent product record. If the values needs to be copied over to all child product records, you need to query all of the child products first then iterate through it to populate the fields specified on your field set.

You can refer to this link on working with fieldsets : https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_dynamic_vf_field_sets.htm

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.