1

Requirement : create a field called 'ExternalRef' on all child objects of Opportunity Object write a trigger on Opportunity that updates the new field on all child objects of opportunity to 'Rajsheakr'+System.now();

Trigger :

Trigger RelatedObjectsFeildsUpdate on Opportunity (after update) {

Map < Id,  Opportunity > mapoppty = new Map < Id, Opportunity >();
for(Opportunity oopty : trigger.new)
    mapoppty.put(oopty.Id, oopty);


List<quote> listquote = new List<quote>();
listquote = [ select id,ExternalRef__c,Opportunity.name,Opportunity.id from quote  where Opportunity.id =: mapoppty.keySet() ];
if ( listquote.size() > 0 ) {
    for ( quote q : listquote ) {
        q.ExternalRef__c = 'raj shekar'+system.now() ;

    }
    update listquote;
}


list<payment__c> lstpymnt = new list<payment__c>();
lstpymnt = [select id,ExternalRef__c,payment__r.name from payment__c where payment__c=: mapoppty.keySet()];
system.debug('lstpymnt'+lstpymnt);
if ( lstpymnt.size() > 0 ) {
    for ( payment__C p : lstpymnt ) {
        p.ExternalRef__c = 'raj shekar'+ system.today();

    }
    update lstpymnt;
}

}

I acheived like this but i have to do it using schema and update the ExternalRef on child objects with 'raj shekar'+system.now();

is it possible to do that generically.

schema class what i think is useful : for getting related child object

 Schema.DescribeSObjectResult R = Opportunity.SObjectType.getDescribe();
 for (Schema.ChildRelationship cr: R.getChildRelationships()) 
 {
  system.debug('====child object==='+cr.getChildSObject());
 }

for getting feilds (manually giving object):

 Map<String, Schema.SObjectField> fieldsMap = 
 Schema.SObjectType.Quote.fields.getMap();

  for (Schema.SObjectField field : fieldsMap.values())
   {
  System.Debug(field.getDescribe().getName());
  }  
2

The ChildRelationship itself has these methods:

getChildSObject()
Returns the token of the child sObject on which there is a foreign key back to the parent sObject.

getField()
Returns the token of the field that has a foreign key back to the parent sObject.

getRelationshipName()
Returns the name of the relationship.

that provide enough information for you to construct the dynamic code you need:

Set<Id> oppIds = mapoppty.keySet();
DescribeSObjectResult dsr = Opportunity.SObjectType.getDescribe();
for (ChildRelationship cr : dsr.getChildRelationships()) {
    SObject[] sobs = Database.query(''
        + ' select Id, ExternalRef__c'
        + ' from ' + cr.getChildSObject()
        + ' where ' + cr.getField() + ' in :oppIds'
    );
    for (SObject sob : sobs) {
        sob.put('ExternalRef__c', 'raj shekar'+ system.today());
    }
    update sobs;
}

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.