How to populate lookup field when creating a new custom object in SFDC
Asked Answered
M

2

0

I'm struggling with this situation.. I have a Standard Object in SFDC (Opportunity) that has a custom look up field pointing to the User object what I'm trying to do is populate this field with the name of the user that creates a custom object that is available in the Opportunity layout...

i.e. New GOP Checklist --- Then choose the type of checklist--- and then fill all the required fields and click save, this is pointing back to the Opportunity view. To start with is this something doable ? i know that look up fields can be tricky. and my second question is what's the best way to do this Programatically (trigger) or using the workflow and field update functionality ?

Thanks !!

trigger TR_OrderChecklist on Order_Checklist__c (before insert) {

//----------------------------------------------------------------------------------
// Function 1: Update COS Operations Attribute in Opportunity
//----------------------------------------------------------------------------------

for(Order_Checklist__c o : trigger.new){
  if(o.Opportunity__r.CARE_Operations__c == null) {
    o.Opportunity__r.CARE_Operations__c = UserInfo.getUserId();
  }
}

}

This is what they came up with. In the Standard Opportunity Object we have a lookup field tied to the user.. CARE_Operations__c.. Now what the trigger is supposed to do is the following..

1.- When creating a new GOP Checklist if the user populate a new custom lookup field in the GOP object named COSOperations_c then keep that name, 2.- If the User didn't populate the COSOperations_c field but the field in the Opp level CARE_Operations__c is populated use that name. 3.- If neither CARE_Operations_c or COSOperations_c are populated (user input) then COSOperations__c is going to be the person that just create the GOP Object.

This is what i have so far..

trigger TR_OrderChecklist on Order_Checklist__c (before insert) {
List<Opportunity> COS_Op = new List<Opportunity>();
COS_Op = [select CARE_Operations__c from Opportunity where id in (select   Opportunity__c from Order_Checklist__c where COSOperations__c != null)];
for(Order_Checklist__c OC : trigger.new) {
    if(OC.COSOperations__c != null) {
       break;}
    if(COS_Op != null){
       OC.COSOperations__c = OC.Opportunity__r.CARE_Operations__c;} 
    if(OC.COSOperations__c == null){
       OC.COSOperations__c = UserInfo.getUserId();}
}       
} 

My problem is in the second if statement.. the other 2 conditions are working properly.. ! Any ideas ? Thanks !!!

Maddox answered 29/8, 2012 at 17:41 Comment(1)
@Twanley Hi Twanley. Now the requirements are different.. Please check my question again and thanks for all your feedback.. !Maddox
S
0

My (second) take on fixing up the trigger code you posted:

trigger TR_OrderChecklist on Order_Checklist__c (after update) {
    List<Opportunity> opptsToUpdate = new List<Opportunity>();
    for(Order_Checklist__c o : trigger.new) {
        if(o.Opportunity__r.CARE_Operations__c == null) {
            o.Opportunity__r.CARE_Operations__c = UserInfo.getUserId();
            // Queue it up for one update statement later
            opptsToUpdate.add(o.Opportunity__r);
        }
    }
    // Commit any changes we've accumulated for the opportunity records
    if (opptsToUpdate.size() > 0)
        update opptsToUpdate;
}

Assuming you have Opportunity.My_User__c as lookup(User) and My_Object__c.Opportunity__c as lookup(Opportunity) this trigger is a good start:

trigger HandleMyObjectInsert on My_Object__c (before insert) {
    User actingUser = [SELECT id FROM User WHERE Id = :UserInfo.getUserId()];
    List<Opportunity> oppts = new List<Opportunity>();
    for (My_Object__c myobj : trigger.new) {
        Opportunity o = new Opportunity();
        o.Id = myobj.Opportunity__c;
        o.My_User__c = actingUser.Id;
        oppts.add(o);
    }
    update oppts;
}

For proof that Lookup(User) is really just an Id field, try out this exercise. Create a new Lookup(User) field on the Opportunity object named "My User."

  • Data Type: Lookup Relationship
  • Related To: User
  • Field Label: My User
  • Field Name: My_User (turns into My_User__c and also available through My_User__r)

From the Salesforce web page, pick an existing opportunity record and set the My User field to some random user and save the record. Now from the Developer Console, execute this anonymous APEX:

Opportunity[] oppts = [
    SELECT id, My_User__c, My_User__r.Name
    FROM Opportunity
    WHERE My_User__c != null
];
for (Opportunity o : oppts) {
    system.debug('##### Opportunity.My_User__c = ' 
        + o.My_User__c 
        + ', o.My_User__r.Name = ' 
        + o.My_User__r.Name);
}

Close the fancy log view and click the "Open Raw Log" and you'll see a line like this:

16:42:37.077 (77645000)|USER_DEBUG|[7]|DEBUG|##### Opportunity.My_User__c = 00530000000grcbAAA, o.My_User__r.Name = John Doe

See, Salesforce thinks of __c lookup fields as Id fields. In this case, it's a Foreign Key relationship to the Id of the User object. Salesforce makes you think the Name field is the Primary Key but really it's the Id field (ok I haven't actually seen Salesforce's ERD, but I'm pretty sure that's correct). Notice that you can get to the lookup object's fields through the __r construct.

Updating the field is just a matter of changing the My_User__c id:

Opportunity[] oppts = [
    SELECT id, My_User__c
    FROM Opportunity
    WHERE My_User__c != null
    LIMIT 1
];
for (Opportunity o : oppts) {
    o.My_User__c = :UserInfo.getUserId();
}
update oppts;

Or, you can get the User Id from a soql query like this:

// Let's query all users and use the 3rd one in the list (zero-index 2)
User[] users = [select id from user];
Opportunity o = new Opportunity(My_User__c = users[2].id, Name='Testing', StageName = 'Prospecting', CloseDate = System.today());
insert o;

Or, look up a user by their email address:

User[] users = [select id from user where email = '[email protected]' and IsActive = true];
if (users.size() > 0) {
    Opportunity o = new Opportunity(My_User__c = users[0].id, Name='Testing', StageName = 'Prospecting', CloseDate = System.today());
    insert o;
}

This is just a really good way to get the Id of the current user:

UserInfo.getUserId()
Sextan answered 30/8, 2012 at 4:8 Comment(10)
Hi twanley.. in this case you are assigning the ID from the SOQL statement to the o.My_User__c but how do i assign the same id value to a lookup field ?? is this doable ? if you can show me how i will really appreciate that. ! ThanksMaddox
I think if you pop the hood you'll find that Lookup fields really are Id fields. I provided a tutorial of sorts to help make that point. Happy to help if you're still stuck.Sextan
Hi Twamley... Here is the trigger that i wrote.. it doesn't work.. !! and i don't have an idea why.. ! :SMaddox
@JeyJim, sorry, but your change was rejected. Please add extra stuff you want to say either using comments, or by updating your original question. Editing other people answers to put your thoughts is not really welcome.Crucifixion
@Sextan Please check the trigger in my original question and let me know what i'm doing wrong here.. !! Thanks !!Maddox
Posted my take on fixing up your trigger. Let me know how it goes.Sextan
Hi Twamley.. I'm lost.. !!! I try to make the trigger work but i'm getting an error message that the Opportunity.id field is not Writable.. and actually that makes sense.. what i'm trying to do is update a field in the Opportunity object (the opportunity is already created) what can i do to change these 2 lines and get the current opp id Opportunity oppToUpdate = new Opportunity(); oppToUpdate.Id = o.Opportunity__c; The new Opportunity (); i think is creating a new id for it and the i'm trying to assign the reference Id the the newly created correct ? Please advise.. !! Thanks !Maddox
Sorry, it's not easy for me to test this code. I was reviewing this page and maybe all you're missing in your trigger is this line update o.Opportunity__r; I updated my trigger to a more governor limits friendly version of that.Sextan
@Twanley Hi Twanley. Now the requirements are different.. Please check my question again and thanks for all your feedback.. !Maddox
After struggling on how to use the Id of the parent opportunity i was able to accomplish was i trying too.. Thanks for all your help guys !Maddox
R
0

I am a little confused here with the requirements. Are we saying that you need to create a new Opportunity record when a record of the custom object is created?

If so yes it is possible. You can write a APEX trigger on the customer object of the type "after insert" and create a new Opportunity record and populate its fields as required.

Rhynchocephalian answered 29/8, 2012 at 19:37 Comment(1)
Hi Richard.. What I'm trying to do is as soonest i generate a New Custom Object in this case (GOP Checklist) i want to populate the name of the person that generate the GOP checklist in one Custom Field that belongs to the Opportunity Object (Lookup Field tied to the User Object) is this doable ?? Thanks !!!Maddox
S
0

My (second) take on fixing up the trigger code you posted:

trigger TR_OrderChecklist on Order_Checklist__c (after update) {
    List<Opportunity> opptsToUpdate = new List<Opportunity>();
    for(Order_Checklist__c o : trigger.new) {
        if(o.Opportunity__r.CARE_Operations__c == null) {
            o.Opportunity__r.CARE_Operations__c = UserInfo.getUserId();
            // Queue it up for one update statement later
            opptsToUpdate.add(o.Opportunity__r);
        }
    }
    // Commit any changes we've accumulated for the opportunity records
    if (opptsToUpdate.size() > 0)
        update opptsToUpdate;
}

Assuming you have Opportunity.My_User__c as lookup(User) and My_Object__c.Opportunity__c as lookup(Opportunity) this trigger is a good start:

trigger HandleMyObjectInsert on My_Object__c (before insert) {
    User actingUser = [SELECT id FROM User WHERE Id = :UserInfo.getUserId()];
    List<Opportunity> oppts = new List<Opportunity>();
    for (My_Object__c myobj : trigger.new) {
        Opportunity o = new Opportunity();
        o.Id = myobj.Opportunity__c;
        o.My_User__c = actingUser.Id;
        oppts.add(o);
    }
    update oppts;
}

For proof that Lookup(User) is really just an Id field, try out this exercise. Create a new Lookup(User) field on the Opportunity object named "My User."

  • Data Type: Lookup Relationship
  • Related To: User
  • Field Label: My User
  • Field Name: My_User (turns into My_User__c and also available through My_User__r)

From the Salesforce web page, pick an existing opportunity record and set the My User field to some random user and save the record. Now from the Developer Console, execute this anonymous APEX:

Opportunity[] oppts = [
    SELECT id, My_User__c, My_User__r.Name
    FROM Opportunity
    WHERE My_User__c != null
];
for (Opportunity o : oppts) {
    system.debug('##### Opportunity.My_User__c = ' 
        + o.My_User__c 
        + ', o.My_User__r.Name = ' 
        + o.My_User__r.Name);
}

Close the fancy log view and click the "Open Raw Log" and you'll see a line like this:

16:42:37.077 (77645000)|USER_DEBUG|[7]|DEBUG|##### Opportunity.My_User__c = 00530000000grcbAAA, o.My_User__r.Name = John Doe

See, Salesforce thinks of __c lookup fields as Id fields. In this case, it's a Foreign Key relationship to the Id of the User object. Salesforce makes you think the Name field is the Primary Key but really it's the Id field (ok I haven't actually seen Salesforce's ERD, but I'm pretty sure that's correct). Notice that you can get to the lookup object's fields through the __r construct.

Updating the field is just a matter of changing the My_User__c id:

Opportunity[] oppts = [
    SELECT id, My_User__c
    FROM Opportunity
    WHERE My_User__c != null
    LIMIT 1
];
for (Opportunity o : oppts) {
    o.My_User__c = :UserInfo.getUserId();
}
update oppts;

Or, you can get the User Id from a soql query like this:

// Let's query all users and use the 3rd one in the list (zero-index 2)
User[] users = [select id from user];
Opportunity o = new Opportunity(My_User__c = users[2].id, Name='Testing', StageName = 'Prospecting', CloseDate = System.today());
insert o;

Or, look up a user by their email address:

User[] users = [select id from user where email = '[email protected]' and IsActive = true];
if (users.size() > 0) {
    Opportunity o = new Opportunity(My_User__c = users[0].id, Name='Testing', StageName = 'Prospecting', CloseDate = System.today());
    insert o;
}

This is just a really good way to get the Id of the current user:

UserInfo.getUserId()
Sextan answered 30/8, 2012 at 4:8 Comment(10)
Hi twanley.. in this case you are assigning the ID from the SOQL statement to the o.My_User__c but how do i assign the same id value to a lookup field ?? is this doable ? if you can show me how i will really appreciate that. ! ThanksMaddox
I think if you pop the hood you'll find that Lookup fields really are Id fields. I provided a tutorial of sorts to help make that point. Happy to help if you're still stuck.Sextan
Hi Twamley... Here is the trigger that i wrote.. it doesn't work.. !! and i don't have an idea why.. ! :SMaddox
@JeyJim, sorry, but your change was rejected. Please add extra stuff you want to say either using comments, or by updating your original question. Editing other people answers to put your thoughts is not really welcome.Crucifixion
@Sextan Please check the trigger in my original question and let me know what i'm doing wrong here.. !! Thanks !!Maddox
Posted my take on fixing up your trigger. Let me know how it goes.Sextan
Hi Twamley.. I'm lost.. !!! I try to make the trigger work but i'm getting an error message that the Opportunity.id field is not Writable.. and actually that makes sense.. what i'm trying to do is update a field in the Opportunity object (the opportunity is already created) what can i do to change these 2 lines and get the current opp id Opportunity oppToUpdate = new Opportunity(); oppToUpdate.Id = o.Opportunity__c; The new Opportunity (); i think is creating a new id for it and the i'm trying to assign the reference Id the the newly created correct ? Please advise.. !! Thanks !Maddox
Sorry, it's not easy for me to test this code. I was reviewing this page and maybe all you're missing in your trigger is this line update o.Opportunity__r; I updated my trigger to a more governor limits friendly version of that.Sextan
@Twanley Hi Twanley. Now the requirements are different.. Please check my question again and thanks for all your feedback.. !Maddox
After struggling on how to use the Id of the parent opportunity i was able to accomplish was i trying too.. Thanks for all your help guys !Maddox

© 2022 - 2024 — McMap. All rights reserved.