I'll keep this concise as I find I ramble on too much if I don't.
I've come up with the code below, but I believe I need to add it as an OnClick event for the Add Existing contact button. Can someone confirm I am going down the right path? Has anyone here done this before?
For context:
I have three tables in a model driven app that have connections to each other.
Account Contact Facility
The facility table has a form in which I want a subgrid that can only add contacts that are already associated with the "parent" account to the facility. So only contacts with parentcustomerid (from the contact) == associatedaccount (on the facility) can be seen when a user adds them via the subgrid. I think I am making a mistake with the gridContext portion and either looking at the wrong control which might explain the error?
function setFacilityContactView(executionContext)
{
var formContext = executionContext.getFormContext();
var gridContext = formContext.getControl("lookup_associated_contact_subgrid");
var fetchXml = "<fetch><entity name='contact'><attribute name='fullname' /><attribute name='emailaddress1' /><attribute name='parentcustomerid' /><link-entity name='xyz_facilities' from='xyz_associatedaccount' to='parentcustomerid' alias='Facility'><attribute name='xyz_associatedaccount' /></link-entity><filter><condition attribute='parentcustomerid' operator='eq' valueof='Facility.xyz_associatedaccount' /></filter></entity></fetch>";
var layoutXml = "<grid name='resultset' object='2' jump='fullname' select='1' icon='1' preview='1'><row name='result' id='contactid'><cell name='fullname' width='142' /><cell name='emailaddress1' width='131' /></row></grid>";
var viewId = "{00000000-0000-0000-0000-000012112023}";
var viewDisplayName = "Facility Contacts";
gridContext.addCustomView(viewId, "contact", viewDisplayName, fetchXml, layoutXml, true);
}