Associate contact to custom object based on matching property values

Hi community,

We recently added a custom object for our referral & commission partners. This way, if a lead comes in via their specific trial links (we then capture their “partner_id” on contact level); we can link it to the custom object & it’s clear for our internal sales team that there is already an association to a parter (so the internal sales doesn’t have to work on the contact)

So: When a contact gets a value for “partner_id” by filling in a trial request; it will be triggered in a workflow. I then want a custom coded action to associate the contact to the right custom Partner object (based on a match of the partner_id property)

I found this custom code to associate a conact to a company --> This custom code snippet can be used to associate a contact to a company based on the company name property that is stored at a contact level. It's particularly useful if your customers are using a freemail address and aren't supplying a company website - just the name of their company. If no company is found a new record will be created in the CRM and an association will be made/ · GitHub from @jackcoldrick but am trying to modify it to my needs.

I was wondering if anyone would be able to help me out. @BenLerner-Paio , could you help me out again by any chance?
So, I have been able to find documentation & did some get requests to get to my object type Id & the type Id of the association of contact to partner object.

My custom object (referral_partner) had the custom object type id “2-18324712” and the type Id for the association should be 59

How do I modify the code from associateContactToCompany

in order for it to match the contents of the contact property “partner_id” to the contents of the custom object property “partner_id” & if there’s a match → associate the contact to the custom object?

I gave it a try by looking at the code & some other community stuff but it doesn’t make sense.

// Import HubSpot Client Library and instantiate client with private app token
const hubspot = require('@hubspot/api-client');
const hubspotClient = new hubspot.Client({
 accessToken: process.env.HannePartnerTest // Access token associated with your private app (also be sure to include token in secrets)
});

// Helper function to get the associated Object ID of a specified Object Type
async function getAssociatedObjectId(objectType, objectId, toObjectType) {
 let obj = await hubspotClient.crm.objects.associationsApi.getAll(objectType, objectId, toObjectType);
 return obj.results[0].id;
}

// Helper function to associate a custom object to a contact
async function associateCustomObjectToContact(objectTypeId, customObjectId, contactId) {
 const AssociationSpec = [{
 "associationCategory": "USER_DEFINED",
 "associationTypeId": 59, // Add a comma here
 "label": "Referral Contact"
 }];
 hubspotClient.apiRequest({
 method: 'put', // Use lowercase 'put'
 path: `/crm/v4/objects/${objectTypeId}/${customObjectId}/associations/contact/${contactId}`,
 body: AssociationSpec
 });
}

exports.main = async (event) => {

 // Define variables
 const objectTypeId = '2-18324712'; // Custom Object "objectTypeId" (this will be different for you)
 const objectId = event.object.objectId // Currently enrolled Custom Object Record Id

 // Storing the partnerID into a const
 const partnerID = event.inputFields['partner_id'];

 // Create search criteria 
 const filter = { propertyName: 'partner_id', operator: 'EQ', value: partnerID };
 const filterGroup = { filters: [filter] };
 const sort = JSON.stringify({ propertyName: 'partner_id', direction: 'DESCENDING' });
 const properties = ['partner_id'];
 const limit = 1;
 const after = 0;

 const searchCriteria = {
 filterGroups: [filterGroup],
 sorts: [sort],
 properties,
 limit,
 after
 };

 // Search the CRM for custom objects matching "partnerID" variable defined earlier
 hubspotClient.crm.objects.searchApi.doSearch(objectTypeId, searchCriteria).then(searchResponse => {
 // console.log("RESULTS: " + searchResponse.body.total); // - FOR DEBUG
 // Continue with the rest of your code...
 });
};
// if MATCH FOUND - ASSOCIATE partner object to CONTACT
 if(// console.log("PartnerID " + partnerId + " FOUND: ASSOCIATE RECORDS"); // - FOR DEBUG
 //Associate Company with Contact
 hubspotClient.crm.objects.associationsApi.create(searchResponse.body.results[0].id,'contacts', event.object.objectId,'associateCustomObjectToContact');
 }
 });

 callback({outputFields: {}});

 })
 .catch(err => {
 console.error(err);
 });
})

Hey, @HaVdb :waving_hand: Thanks for your question. Since this is code from a repo created by @coldrickjack, you might try opening an issue there too.

Have you tried breaking this down a bit and testing the individual calls using Postman? Verifying the calls work as expected in a simplified manner is often useful.

Additionally, have you tried adding some debugging to your code? Adding a few console.log() statements could help reveal any issues.

  • After fetching the response(s)
  • After searching for the custom object
  • Before creating the associations
  • Adding one to your catch block

Tracking down the flow of data is a great place to start in debugging your code customization.

Have fun testing! — Jaycee

Hi @Jaycee_Lewis ,

I did try some of it; but I’m a total newbie at coding so I have been trying to make sense of it (also tried to ask ChatGPT to help me out a little) but didn’t seem to be able to fully figure it out.
That’s why I thought it could be good to ask the original author of the code how I could make it work for my case :wink:
I’ll definitely take your tips with me for a next time. Thanks! :blush:

Hi @HaVdb,

I think we should easily be able to modify this code to support your use case. Would you mind letting me know if the partner_id property is storing a numeric or text value as this will influence how we look up the appropriate object to associate.

Hi @coldrickjack ,
on contact level it’s a single line text property; on the partner level it’s a number property. But I can still change this if need be, I only have 8 values currently (we haven’t migrated all our partners in HubSpot just yet).

Hi @HaVdb,

I think this code will work for you. Let me know how you get on. I’ve also recorded a short video running through how it all works.

All the best,

Jack

Hi @coldrickjack thanks A MILLION for your help on this one & the explainer video!
I added my hubspot token & had to exchange the /partner/ in the request URL with the custom object type ID; but it worked perfectly!
I might need to take a look at removing the association if the ID changes (in your video, all three of them stay associated to the contact) but that’s not super high prio at the moment.
Thank you for sharing your code & help me (& others in the future!)

Glad it was helpful @HaVdb :blush:

@coldrickjack I was wondering if you could shed some light on an issue related to this initial question.
I managed to adjust your code to also add an association label to the contact (“referral contact”); but got the question internally to add another association label on top of the initial one.
When I adjusted the code; it just overwrites the label value. I can’t seem to add 2 association labels at the same time with the workflow.
Do you know if this is possible?
I tested it with the code below, but it only associates the last label. I feel like it overwrites the first value with the last value.

Have you come across a similar issue by any chance?

Thanks for you time! :folded_hands:

const axios = require('axios');
axios.defaults.headers.common['authorization'] = `Bearer ${process.env.HannePartnerTest}`;
axios.defaults.headers.common['Content-Type'] = `application/json`;
axios.defaults.headers.put['Content-Type'] = `application/json`;

exports.main = async (event) => {
 const partner_id = event.inputFields['partner_id'];

 const partnerObjectId = await getPartner(partner_id);
 console.log(partnerObjectId.results[0].id);

 const contact_id = event["object"]["objectId"];

 const associateResult = await associateContactToPartner(contact_id, partnerObjectId.results[0].id);
 console.log(associateResult);

 // Check if the association was successful before associating the labels
 if (associateResult) {
 const label1Result = await associateLabelToContact(contact_id, partnerObjectId.results[0].id, 59);
 console.log(label1Result);

 const label2Result = await associateLabelToContact(contact_id, partnerObjectId.results[0].id, 68);
 console.log(label2Result);
 }
}

// 1. Get HubSpot Partner using Contact Partner ID value
function getPartner(partner_id) {
 let requestUrl = `https://api.hubapi.com/crm/v3/objects/2-18324712/search`;
 let data = {
 filterGroups: [{
 filters: [{
 propertyName: 'partner_id',
 operator: 'EQ',
 value: partner_id
 }]
 }],
 properties: ['name', 'partner_id'],
 }
 return new Promise((resolve) => {
 axios.post(requestUrl, data).then(res => {
 resolve(res.data);
 }).catch(err => {
 console.log(err.message)
 });
 });
}

// 2. Associate Contact to Partner Object
function associateContactToPartner(contact_id, partner_id) {
 // Request body for association with labels 59 and 68
 const associationSpec = [
 { "associationCategory": "USER_DEFINED", "associationTypeId": 59 },
 { "associationCategory": "USER_DEFINED", "associationTypeId": 68 }
 ];

 let requestUrl = `https://api.hubapi.com/crm/v4/objects/contacts/${contact_id}/associations/default/2-18324712/${partner_id}`;
 console.log(requestUrl);

 return new Promise((resolve) => {
 axios.put(requestUrl, associationSpec).then(res => {
 resolve(res.data);
 }).catch(err => {
 console.log(err.message)
 resolve(null); // Resolve with null to indicate failure
 });
 });
}

// 3. Associate Label to Contact
function associateLabelToContact(contact_id, partner_id, associationTypeId) {
 // Request body for association with a label
 const associationSpec = [{
 "associationCategory": "USER_DEFINED",
 "associationTypeId": associationTypeId
 }];

 let requestUrl = `https://api.hubapi.com/crm/v4/objects/0-1/${contact_id}/associations/2-18324712/${partner_id}`;
 console.log(requestUrl);

 return new Promise((resolve) => {
 axios.put(requestUrl, associationSpec).then(res => {
 resolve(res.data);
 }).catch(err => {
 console.log(err.message)
 resolve(null); // Resolve with null to indicate failure
 });
 });
}