I am trying to insert a record into a child custom object using the external id of the parent custom object. I am almost clear on how to setup the external id field in the parent object, but very confused with how to setup a foreign key in my child object. I am attaching the pics here which has details of the master and child custom objects. What I am i supposed to add to the child custom object to link its records to the parent object.
Also here is the code I got from another post in stackoverflow, but that didn't work in my case
enter image description heresumchans__City_Master__c city = new sumchans__City_Master__c(Name='[![enter image description here][1]][1]Vancouver',sumchans__PROVINCE__c = 'BC', sumchans__City_Name_Ext_Id__c = 'Vancouver');
insert city;
sumchans__City_Stat__c cityStat = new sumchans__City_Stat__c(Name = 'Vancouver', sumchans__ON_BILLINGS__c = 50, sumchans__City_Master__c=new sumchans__City_Master__c(sumchans__City_Name_Ext_Id__c='Vancouver'));
insert cityStat;
Ext. ids are meant to be used in integrations, Data Loader... They can be used in Apex too but the syntax looks bit funny. Use them in Apex if you must save on queries or want to go "dear salesforce, I don't remember if I saved this object already, I know unique identifier is 123, go figure it out yourself whether it needs insert or update".
If you insert parent and child in same transaction - just user the Id generated into parent record. If they're separate, a while ago you did this:
insert new sumchans__City_Master__c city = new sumchans__City_Master__c(Name=Vancouver',
sumchans__PROVINCE__c = 'BC',
sumchans__City_Name_Ext_Id__c = 'Vancouver'
);
Then later in another transaction you can do this without querying:
sumchans__City_Stat__c cityStat = new sumchans__City_Stat__c(Name = 'Vancouver',
sumchans__ON_BILLINGS__c = 50,
sumchans__City_Master__r = new sumchans__City_Master__c(
sumchans__City_Name_Ext_Id__c='Vancouver'
)
);
insert cityStat;
Note that I used __r instead of __c. __c would be your real foreign key, Id field, 15 or 18 characters. __r would be a reference to another object (with ext. id or query result for example), similar to writing SELECT FirstName, Email, Account.Name FROM Contact.
In Apex it has to be as a object referece (so either query or cheat with new keyword, just to create it in memory. You won't actually save that "parent"). In things like data loader you can map values bit like myCsvExtIdColumn -> sumchans__City_Master__r.sumchans__City_Name_Ext_Id__c
Create a lookup field instead. Because External ID field used to reference an ID from another external system.
If you want to relate the foreign key with and relational DBMS, you need to create a lookup relationship type field in the child object. There you need to assign the Parent Object in the Related To field.
Related
I need to do 1 of two things (I believe):
1- Get a Custom Object ID so I can query it directly
2- Get a list of values of a specific field within the Object entries.
Ultimate End goal:
Add and modify rows in my custom object via external API. However to do this I need to check and make sure my new entry/row does not already exist.
What I have:
I have a custom object (called Customer_Arrays__c). It is a table that I can add new rows to (I will call entrys). Each entry has 6 or 7 fields. 1 of these fields is called (external_ID__c). This is the field I utilize to match to new incoming data to see if the entry already exists, or if it needs to add a new row to my table. This Customer_Arrays__c is a child to my opportunity I believe – it is part of every opportunity and each line item I add has a field defaulted to the opportunity.
Help I need:
1- How do I query the value of my Cutomer_Arrays__c based upon an opportunity ID?
2- How do I query a list of values in my (external_ID__c) based upon an opportunity ID?
Thanks for your help! I have read half a dozen+ posts on similar topics and am missing something. Examples of some Past try's that failed:
Select external_ID__c,FROM Custom_Arrays__c WHERE Opportunity='00...'
Select Id (Select ID, Custom_Arrays__c from Custom_Arrays__c) from Opportunity where id ='00...'
List FROM Custom_Arrays__c WHERE Opportunity='00...'
Select Id, external_ID__c, (Select external_ID__c FROM Custom_Arrays__c) WHERE Opportunity__c='00...'
Thanks again!
Only you know how did you name the lookup field (foreign key) from arrays to Opportunity. You'll need to check in setup, next to where external_ID__c is. Since it's a custom field (gets __c at the end), my guess is you went with default.
Try
SELECT Id, Name, External_Id__c
FROM Customer_Arrays__c
WHERE Opportunity__c = '006...'
Thank you eyescream, that got me almost all the way there. Turns out I also needed a __r for the parent child relationship.
Here is a snip out of my final code that works - I think it covers everything:
SELECT Field1__c, Opportunity__r.Id, Opportunity__r.Opportunity__c,
FROM Customer_Arrays__c
WHERE Opportunity__r.Id = '006...'.
Thank you so very much!!!
i have two objects KNDY4__Sales_Order__c and KNDY4__Bill_to__c.these two are linked through lookup relationship.i am trying to insert one order record as follows
`KNDY4__Sales_Order__c order=New KNDY4__Sales_Order__c();
order.KNDY4__Ship_to__c ='a14q0000001LnIeAAK';
order.KNDY4__Bill_to__r.Predicted_External_ID__c ='CN-0222741-Sold To';
order.KNDY4__Company__c ='a0l1N00000BQQKF';
Insert order;`
i am geting error as {"Object reference not set to an instance of an object."}.
how to assign values to lookup field.can anyone help me
When linking a record based on an external id, the relationship field needs to be set to an sObject with the external id, and not just the value of the id itself.
On line 3, since KNDY4__Bill_to__c is a lookup field to a custom object possibly named KNDY4__Customer__c, you should set the value of the lookup to an instance of that object, e.g.
order.KNDY4__Bill_to__r = new KNDY4__Customer__c(KNDY4__Predicted_External_ID__c ='CN-0222741-Sold To');
Ok so I have an application that uses GAE and consequently the datastore.
Say I have multiple companies A, B and C and I have within each company Employees X,Y and Z. The relationship between a company and employee will be OneToMany, with the company being the owner. This results in the Company Key being of the form
long id = 4504699138998272; // Random Example
Key CompanyKey = KeyFactory.createKey(Company.class.getSimpleName(), id);
and the employee key would be of the form
long id2 = 5630599045840896;
Key EmployeeKey = KeyFactory.createKey(CompanyKey,Employee.class.getSimpleName(),id2);
all fine and well and there is no problem, until in the front end, during jsp representation. Sometimes I would need to generate a report, or open an Employees profile, in which case the div containing his information would get an id as follows
<div class="employeeInfo" id="<%=employee.getKey().getId()%>" > .....</div>
and this div has an onclick / submit event, that will ajax the new modifications to the employee profile to servelet, at which point I have to specify the primary key of the employee, (which I thought I could easily get from the div id), but it didnt work server side.
The problem is I know the Employees String portion of the Key and the long portion, but not the Parent key. To save time I tried this and it didnt work
Key key = KeyFactory.creatKey(Employee.class.getSimpleName(); id);
Employee X = em.find(Employee.class,key);
X is always returned null.
I would really appreciate any idea of how to find or "query" Entities by keys without knowing their parents key (as I would hate having to re-adjust Entity classes)
Thanks alot !!
An Entity key and its parents cannot be separated. It's called ancestor path, a chain composed of entity kinds and ids.
So, in your example ancestor paths will look like this:
CompanyKey: ("Company", 4504699138998272)
EmployeeKey: ("Company", 4504699138998272, "Employee", 5630599045840896)
A key composed only of ("Employee", 5630599045840896) is a completely different one comparing to the EmployeeKey even though both keys end with the same values. Think of concatenating elements into a single "string" and comparing final values, they will never match.
One thing you can do is use encoded keys instead of their id values:
String encodedKey = KeyFactory.keyToString(EmployeeKey);
Key decodedKey = KeyFactory.stringToKey(encodedKey);
decodedKey.equals(EmployeeKey); // true
More about Ancestor Paths:
https://developers.google.com/appengine/docs/java/datastore/entities#Java_Ancestor_paths
KeyFactory Java doc:
https://developers.google.com/appengine/docs/java/javadoc/com/google/appengine/api/datastore/KeyFactory#keyToString(com.google.appengine.api.datastore.Key)
Quick Question. In the below code, you can see that the for loop (which takes all of the records in newTimecards and puts them as a variable called timecard) and adds the Resource_c to the resourceIds set. I'm confused about how this object is considered an ID data type. When an object is made in Salesforce does it automatically have an ID made, so that it knows Resource_c ID can be added to a set? Note that within the Resource_c Object there is also a field called Resource_ID_c. Resource_c within Timecard_c is a Master-Detail data type. Resource_c is the parent of Timecard_c.
Now that I think about it, resourceIds.add(timecard.Resource_c), does that reference the relationship between the two objects and then searches through Resource_c and adds the ID field Resource_ID_c automactically since it's a unique field?
Thanks for your help.
public class TimecardManager {
public class TimecardException extends Exception {}
public static void handleTimecardChange(List<Timecard__c> oldTimecards,
List<Timecard__c> newTimecards) {
Set<ID> resourceIds = new Set<ID>();
for (Timecard__c timecard : newTimecards) {
resourceIds.add(timecard.Resource__c);
}
Every object instance (and that means EVERY, including factory ones) has a unique organization level ID, whose field name is always Id, is covered by Apex type ID and is a case-sensitive string of 15 characters that also has an 18 character case-insensitive representation. The first three characters are object prefix code (e.g. 500 for a Case) so all instances of the same object share the same prefix. You see these values all across SF (for example in https://na1.salesforce.com/02s7000000BW59L the 02s7000000BW59L in the URL is the ID). When an instance of the object is created using INSERT DML operation, the salesforce automatically assigns unique value based on the prefix and the next available transactional sub ID, it all happens transparently to you.
This is not to be confused with object Name field which is a field you define when you create an object and which can be auto-incremented and so on (e.g. MYOBJ-{00000}) and which can have more meaning to a user than a cryptic ID
When you create a lookup or master-detail relationship it is ID that is being used to link the two instances, not the Name. In the above example Resource__c seems to be that lookup field and it contains Id value of row's master.
What the code does is it enumerates all resources used in timelines and builds a set of their IDs, the purpose of which is most probably to be used via WHERE Id IN :resourceIds clause to load resource details from master table.
mmix's answer is a great overview to what an ID is and where it comes from. To answer what I think is your specific question:
Any time there is a reference from one object to another (like here, between Timecard_c and Resource_c), the field representing the reference will be an ID. So, the for loop that calls resourceIds.add(timecard.Resource__c) is just building up your set of ID's (those 15-character strings). The timecard.Resource__c doesn't look through the Resource__c table to find the ID, timecard.Resource__c is the ID.
What is the best method to create a database for the given example model and assign each entry with a unique key/name which I already have and to overwrite it if the given key/name shows up again. From what I read you are supposed to use keyname? But I am not getting it to overwrite.
class SR(db.Model):
name = db.StringProperty()
title = db.StringProperty()
url = db.StringProperty()
s = SR(key_name="t5-2rain")
s.name = 't5-2rain'
s.title = 'kaja'
s.url = 'okedoke'
db.put(s)
If I enter this again with the same key name but different title value, will create another entry how do I overwrite an existing value with the same key-name.
Basically how do I populate a table with unique identifiers and overwrite values if the same unique identifier already exist?
I realize I can search for an existing name or key name etc, call that object make the changes to the instances and repopulate but, I would imagine there has to be a better method than that for overwriting especially if I am trying to put a list where some values may be overwrites and some not.
You've got the right idea already.
If 2 SR entities were constructed with the same key_name argument, then they will have the same Key path. Writing one will overwrite any old SR entity which had that key_name argument.
You should be able to observe this by querying the datastore for the entity with its unique key:
s = db.get(db.Key.from_path('SR', 't5-2rain'))