You need to sign in to do that
Don't have an account?
Mathew Andresen 5
Not pulling parent object info as expected
Hi,
My first try of this didn't work, and I did a work around, but I'm really trying to understand why my first try didn't work. Basically, I'm trying to pull the Account Name from one of' it's child objects. So, I thought the syntatx should be something like sObject.Account__r.Name
My first try of this didn't work, and I did a work around, but I'm really trying to understand why my first try didn't work. Basically, I'm trying to pull the Account Name from one of' it's child objects. So, I thought the syntatx should be something like sObject.Account__r.Name
trigger TastingEvent on Tasting__c (before insert, before update) { List<Event> myEvent = new List<Event>(); User u = [Select id, FirstName from User where id =: UserInfo.getUserId() LIMIT 1]; for(Tasting__c taste:Trigger.New) { String acct = taste.Account__c; Account myAccount = [SELECT Name, Id FROM Account WHERE Id = :acct]; Event e = new Event(); // this doesn't work //e.Subject = taste.Account__r.Name; // but this does String subject = (myAccount.Name + ' ' + taste.Location__c) ; e.Subject = subject; date st = taste.Date_of_Tasting__c; DateTime dt_StartDate = datetime.newInstance(st.year(), st.month(), st.day(), 3,0,0); e.StartDateTime = dt_StartDate; datetime endDate = dt_StartDate; endDate = endDate.addHours(2); e.EndDateTime = endDate; e.OwnerId = u.Id; myEvent.add(e); System.debug(taste.Account__r.Name); } insert(myEvent); }
All Answers
There are many ways that you can do to achieve what you are trying but first things first:
1. Jane is right.
2. You definitely should avoid SOQL inside loops, this is highly important! (https://developer.salesforce.com/page/Apex_Code_Best_Practices)
You can try something like the code below, I didn't tested but this is one way. Furthermore, you can add some sort of validation to avoid nulls, etc.
Regards
Don't forget to mark your thread as 'SOLVED' with the answer that best helps you.