Skip to main content
Hi,

I've got a trigger, where my custom object (samples__c) is pulling info from the opportunity (the parent) and then from the account (the parent of opportunity).  However, I had some difficutty getting parent object info.  I believe the query should be something like  var.opportunity__r.accountId  And this works when I do a query, but not with dot notation, and I'm not sure why.  So for example, this works in the query editor

SELECT opportunity__r.accountId FROM Samples__c

 

/* THIS SHOULD WORK

For(Samples__c samp:Trigger.new) {

sampSetId.add(samp.opportunity__r.accountId);

system.debug(sampSetId);

}

*/

Here is my final code, I did a work around with some extra maps, is this correct?  Or what am I missing?

Thanks,

trigger Samples on Samples__c (before insert) {

List<Account> acctList = new List<Account>();

Set<id> sampSetId = new Set<Id>();

Set<id> acctSetId = new Set<id>();

Map<String, Account> acctMap = new Map<String, Account>();

Map<id, ID> OppAcct = new Map <id, Id>();

Id acctId;

/* THIS SHOULD WORK

For(Samples__c samp:Trigger.new) {

sampSetId.add(samp.opportunity__r.accountId);

system.debug(sampSetId);

}

*/

// get the list of account ID's and add them to the set

For(Samples__c samp:Trigger.new) {

sampSetId.add(samp.opportunity__c);

system.debug(sampSetId);

}

List<opportunity> OppList = [SELECT accountID from opportunity WHERE id IN :sampSetId];

for (Opportunity opp: OppList) {

acctSetId.add(opp.accountId);

OppAcct.put(opp.Id, opp.accountId);

}

// query the list of accounts based on the set of account id's

acctList = [SELECT ShippingStreet, ShippingCity, ShippingState, ShippingPostalCode, Shipping_phone__c, Shipping_email__c FROM Account WHERE Id IN :acctSetId];

for (Account acct:acctList) {

acctMap.put(acct.id, acct);

}

for (Samples__c samp :Trigger.new) {

AcctId = OppAcct.get(samp.opportunity__c);

Account acct = acctMap.get(acctId);

system.debug('acct = '+acct);

if (samp.Street__c == NULL) { samp.Street__c = acct.ShippingStreet; }

if (samp.City__c == NULL ) { samp.City__c = acct.ShippingCity; }

if (samp.Zip_Code__c == NULL ) { samp.Zip_Code__c = acct.ShippingPostalCode; }

if (samp.Phone__c == NULL ) { samp.Phone__c = acct.Shipping_Phone__c; }

if (samp.email__c == NULL ) { samp.Email__c = acct.Shipping_Email__c; }

}

}

 
2 answers
  1. Aug 1, 2015, 5:56 AM
    Hi,

    This would not work because when you use reletionship in trigger you need to query the related field.

    You can write query something like this

     

    List<Samples__c> sample = [SELECT opportunity__r.accountID FROM Samples__c];

    for(Samples__c samp : sasmple){

    system.debug(samp.oppertunity__r.accountId);

    }

    Try it and let me know incase of any clarification.

     
0/9000