Skip to content

Instantly share code, notes, and snippets.

@jackcoldrick90
Last active March 27, 2024 08:28
Show Gist options
  • Save jackcoldrick90/faa4f25eb6f07a6bc50b84589a574b3d to your computer and use it in GitHub Desktop.
Save jackcoldrick90/faa4f25eb6f07a6bc50b84589a574b3d to your computer and use it in GitHub Desktop.
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 …
// Import the Hubspot NodeJS Client Library - this will allow us to use the HubSpot APIs
const hubspot = require('@hubspot/api-client');
/*
This function is called when the custom code action is executed. It takes 2 arguements. The first is the event object which contains information on the currently enrolled object.
The second is the callback function which is used to pass data back to the workflow.
*/
exports.main = (event, callback) => {
// Instantiate a new HubSpot API client using the HAPI key (secret)
const hubspotClient = new hubspot.Client({
accessToken: process.env.HUBSPOTTOKEN
});
// Retrive the currently enrolled contacts "company" property
hubspotClient.crm.contacts.basicApi.getById(event.object.objectId, ["company"])
.then(results => {
// Get data from the results and store in variables
let companyName = results.body.properties.company;
//console.log("SEARCH TERM: " + companyName); // - FOR DEBUG
// Create search criteria
const filter = { propertyName: 'name', operator: 'EQ', value: companyName }
const filterGroup = { filters: [filter] }
const sort = JSON.stringify({ propertyName: 'name', direction: 'DESCENDING'})
const properties = ['name']
const limit = 1
const after = 0
const searchCriteria = {
filterGroups: [filterGroup],
sorts: [sort],
properties,
limit,
after
}
// Search the CRM for Companies matching "companyName" variable defined earlier
hubspotClient.crm.companies.searchApi.doSearch(searchCriteria).then(searchCompanyResponse => {
//console.log("RESULTS: " + searchCompanyResponse.body.total); // - FOR DEBUG
// If total equals 0 no results found
if(searchCompanyResponse.body.total == 0){ //NO MATCH FOUND - CREATE COMPANY AND ASSOCIATE
// console.log("COMPANY " + companyName + "NOT FOUND: CREATE + ASSOCIATE") // - FOR DEBUG
//Create a Company object
const companyObj = {
properties: {
name: companyName,
},
}
//Create the Company using Company object above
hubspotClient.crm.companies.basicApi.create(companyObj).then(companyCreateResponse =>{
//Associate Company with Contact using the ID returned from the previous request
hubspotClient.crm.companies.associationsApi.create(companyCreateResponse.body.id,'contacts', event.object.objectId,'company_to_contact');
});
}else{ // MATCH FOUND - ASSOCIATE COMPANY TO CONTACT
// console.log("COMPANY " + companyName + " FOUND: ASSOCIATE RECORDS"); // - FOR DEBUG
//Associate Company with Contact
hubspotClient.crm.companies.associationsApi.create(searchCompanyResponse.body.results[0].id,'contacts', event.object.objectId,'company_to_contact');
}
});
callback({outputFields: {}});
})
.catch(err => {
console.error(err);
});
}
@evolv-vhilaire
Copy link

@jackcoldrick90 I want to edit this so that I can associate a custom object with contacts that match (based on email domain field) but I don't want it to create anything if the search turns up nothing. Would all I have to do is remove the "if total equals zero" and "create company" sections?

@z-churn
Copy link

z-churn commented Mar 27, 2024

Hey @jackcoldrick90 and everyone here. I wanted to ask if you all have been successful in adapting this code for other object associations to use in a custom coded workflow, specifically creating a deal-to-contact association automatically based on a common field/variable value that is always an email address. The goal is to automate the association process for Deals and their existing Contacts. Here has been my logic in adapting this code for my purposes, please let me know if I am missing something here:

  • I do not need to look for the deal itself as it is available through the workflow enrollment; I just define the Deal Record ID and then use it in the code. const hs_deal_id = event.inputFields['hs_object_id'];

  • My next task is to use an existing field value which is always an email address to look for the existing correlating contact object (these contacts will always be in the system). I am assuming much of the filtering above is not needed for this? Can I adapt the search filters to include only the email as the property like this:

const filter = { propertyName: 'email', operator: 'EQ', value: contactEmail }
	const filterGroup = { filters:	[filter] 	}
        const sort = JSON.stringify({ propertyName: 'email', direction: 'DESCENDING'})
        const properties = ['email']
        const limit = 1
        const after = 0

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

And then I would run the rest of the code but instead of company, search through contacts and adjust the association to be deals to contacts? I want to make sure that I am on the right track. Thank you in advance!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment