0

I am pretty new to salesforce development and was assigned a task to mirror a long text field from a parent object to a child object. I tried using a formula but I guess you can't use a long text field in a formula. What would be the best way to mirror all of the long text fields on a parent object, to a child object. I tried to write a trigger but I received an error that I couldn't store a value in the long text field of the child object. Is there a better or different way I should be doing this. Here's the code for my trigger,

trigger updateField on Object_1(after insert, after update)
{

   for(Object_1 a : Trigger.new)
   {
     if(a.Description != Object_2__C.Description_Mirror__c)

     {

       Object_2__C.Description_Mirror__c  = a.Description; 

     }

   }
}

1 Answer 1

1

I'm going to assume that Object_1 is your parent object and Object_2 is your child object, and that you haven't made any changes to the code of this trigger other than altering the object names. If that's the case, the issue lies here:

 if(a.Description != Object_2__C.Description_Mirror__c) {
   Object_2__C.Description_Mirror__c  = a.Description; 

Both occurrences of Object_2__C.Description_Mirror__c are references to the schema_: the definition of the field, not to the storage for the field on some specific record of Object_2__c.

To achieve this objective effectively, you'll need to query for child objects associated with each of the parent objects (preferably, each of the parent objects whose Description has changed) and then copy the value from the associated parents to the children. There's multiple ways to do this, but they all follow the general "collect-filter-query-update" pattern:

  1. Collect information about desired records and filter based on criteria.
  2. Query for desired records.
  3. Collect updated records and perform a single bulkified update.

A loose pseudocode sketch of the pattern applied to this trigger could be something like this.

Create a Set<Id> variable
for (each record in Trigger.new) {
    Check if Description is changed
    If it is, add record Id to set variable
}

Query for all parent records whose Ids are in Set, using a Parent-Child SOQL query to get their children as well.

Create a List<Object_2__c> variable

for (each record in query results) {
    for (each child of this record) {
        if (this record's Description_Mirror__c != parent's Description) {
            Update this record and add to list variable
        }
    }
}

update list of records

Using this pattern ensures that you only affect records that require changes, minimizing your use of DML and SOQL resources.

You must log in to answer this question.

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