Unfortunately populating lookup fields isn't that straight forward like the other fields with a simple set value.
If you thought about using something like
formcontext.getAttribute("field here").setValue("value here")
then you are not going to have a good time.
The reason for this is basically that lookup fields are an entity of it's own and it needs a GUID to assign a value to that field.
Here I present to you the way to populate a lookup field:
var value = new Array();
value[0] = new Object();
value[0].id = GUID HERE;
value[0].name = NAME HERE;
value[0].entityType = ENTITY LOOKUP HERE;
formContext.getAttribute("lookupfield").setValue(value);
You need three values to populate a lookup field
- The GUID of the record of the record in the lookup entity
- The name of the record of the record in the lookup entity
- The name of the entity that is used for the lookup field
1. The GUID
To find this, go to the lookup field and fill it with the record you want it to be filled with by code. Then click on that value, it should bring your directly to the record itself.
Now look in the addressbar. The last part is always the GUID of the record. Copy this into your script.
2. The Name
The name should be easy, it's basically the display name of the record when the lookup field is populated. Don't worry, even if you do get the name wrong, CRM Dynamics will correct it to the actual value in the record once you saved the record where the lookup field is in.
3. Entity Name
You can actually find this in the addressbar as well! Just before the part where you found the GUID.
Once you have all the information you need, you are ready to populate your lookup field! Your function should look something like this:
function poplookupfield(executionContext){
//get formContext
var formContext = executionContext.getFormContext();
var value = new Array();
value[0] = new Object();
value[0].id = "55d91848-aa9f-e611-80eb-c4346bac4838";
value[0].name = "This is a lookup field";
value[0].entityType = contact;
formContext.getAttribute("new_lookupfield").setValue(value);
}
Run this onLoad on your form and look at that field getting populated!
The biggest downside to this method is that it isn't very dynamic. If you need to populate your lookup field based on certain conditions and the lookup field should always contain something else, then this is not the way to do it.
I wouldn't recommend copy/pasting the same lines either for every existing GUID. It will make your script very long and bloated.
My recommendation would be to use the WebAPI and perform lookups on the lookup entity to retrieve and populate your lookup field. I've written an article about that as well and you can find it here: CRM Dynamics 365 Odata and Javascript