HubSpot API in Custom Code Element to Append and Delete Specific Value from Multiple Checkboxes Property

[September 2023]

A Tutorial with Full Code

We used this functionality to grant contacts access to specific website pages based on a single multiselect field. In our case, we have over 100 different dynamically created pages, all of which have different access levels. Creating and keeping track of 100 different single checkmark properties was not going to work for our workflows or organization. Initially, to append values to the multiselect property, we used workflows with branches for each possible addition, however new dynamic pages could be added at any time. Though this got the job done we were determined to find a better, more simple solution. There also was the issue of removing the values. To solve this initially, we used additional properties to show “you  cannot access this content” messages on the pages if a contact had previously gained access to the content and later were removed. The amount of time and resources needed to manually import adjustments to properties or physically select the options for each contact would have been too much for our client.

In this example, we use a form submission to enroll a contact in a workflow that passes the value that is to be added or removed from a multiple checkboxes contact property. 

In our example, we use a simple text field for a user to add a value to within a form. Please note – this must match the internal value exactly of the multiple checkboxes property option.

In our code, this property name is Ex – Special Info with special-info as the key.

We also have a second property for the actual multi-select property – this is named Ex – Additional Registration Info with the key additional_registration_info.

In our actual case of this, we prefilled the form using a dynamic link built from cell values in a multilevel HubDB table. This way, contacts could be given access to specific records/dynamically created pages based on the ID of that record. Alternatively, they could loose access. We did not want contacts to have access to all of the possible records, so we did not want add the multiple checkboxes field to the form.

For set up, please create your single line text field and the multiple checkboxes properties. You also will want to create a form to collect the name, email, and allow people to enter in the value into the text field (again, you could use parameters within a link to prefill this value).

Basic Overview of Code:

The code performs the following steps:

  1. Retrieves the current value of a multi-select checkbox property (additional_registration_info) for a contact in HubSpot.
  2. Converts the value into an array, splitting it based on a delimiter (semicolon ;) to make it easier to work with.
  3. Either adds or removes a specified value (valueToRemove) to/from the array, depending on the use case.
  4. Converts the modified array back into a string, joining its elements using the same delimiter.
  5. Updates the multi-select checkbox property with the new value, effectively saving the changes back to the contact’s property in HubSpot.

In essence, it’s a script for manipulating and managing the values of a multi-select checkbox property for a HubSpot contact (of Company). It can add or remove specific values to/from the property and update it accordingly.

Workflow Element Setup:

Custom Code Settings

Append a Value:

const axios = require('axios');

exports.main = async (event, callback) => {
  const apiKey = 'your-api-key'; // Enter your API Key
  const contactId = event.inputFields['hs_object_id']; // Contact ID
  const additionalInfoIds = event.inputFields['additional_registration_info']; // Enumeration (multiselect) property
  const valueToAdd = event.inputFields['special_info']; // The value to append

  // Log contactId, Additional Info, and valueToAdd for debugging purposes
  console.log('contactId:', contactId);
  console.log('additionalInfoIds before append:', additionalInfoIds);
  console.log('valueToAdd:', valueToAdd);

  // Check if contactId is defined
  if (contactId) {
    try {
      // Split the current value of additionalInfoIds into an array
      const currentInfoIds = additionalInfoIds.split(';');

      // Append the value to add to the array
      currentInfoIds.push(valueToAdd);

      // Join the array back into a string
      const updatedAdditionalInfoIds = currentInfoIds.join(';');

      // Update the multi-select checkbox property with the modified value
      const updateResponse = await axios.patch(
        `https://api.hubspot.com/crm/v3/objects/contacts/${contactId}`,
        {
          properties: {
            ex___additional_registration_info: updatedAdditionalInfoIds
          }
        },
        {
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${apiKey}`
          }
        }
      );

      console.log('Value appended successfully:', updateResponse.data);
      callback({
        outputFields: {
          message: 'Value appended successfully'
        }
      });
    } catch (error) {
      console.error('Error appending value:', error.response.data);
      callback({
        outputFields: {
          message: 'Error appending value'
        }
      });
    }
  } else {
    console.error('Contact ID is undefined');
    callback({
      outputFields: {
        message: 'Contact ID is undefined'
      }
    });
  }
};

Delete a Value:

const axios = require('axios');

exports.main = async (event, callback) => {
  const apiKey = 'your-api-key'; // Enter your API Key
  const contactId = event.inputFields['hs_object_id']; // Contact ID
  const additionalInfoIds = event.inputFields['additional_registration_info']; // Enumeration (multiselect) property
  const valueToRemove = event.inputFields['special_info']; // The value to remove

  // Log contactId, Additional Info, and valueToRemove for debugging purposes
  console.log('contactId:', contactId);
  console.log('additionalInfoIds before removal:', additionalInfoIds);
  console.log('valueToRemove:', valueToRemove);

  // Check if contactId is defined
  if (contactId) {
    try {
      // Split the current value of additionalInfoIds into an array
      const currentInfoIds = additionalInfoIds.split(';');

      // Remove the valueToRemove from the array
      const updatedAdditionalInfoIds = currentInfoIds.filter(item => item !== valueToRemove).join(';');

      // Update the multi-select checkbox property with the modified value
      const updateResponse = await axios.patch(
        `https://api.hubspot.com/crm/v3/objects/contacts/${contactId}`,
        {
          properties: {
            ex___additional_registration_info: updatedAdditionalInfoIds
          }
        },
        {
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${apiKey}`
          }
        }
      );

      console.log('Value removed successfully:', updateResponse.data);
      callback({
        outputFields: {
          message: 'Value removed successfully'
        }
      });
    } catch (error) {
      console.error('Error removing value:', error.response.data);
      callback({
        outputFields: {
          message: 'Error removing value'
        }
      });
    }
  } else {
    console.error('Contact ID is undefined');
    callback({
      outputFields: {
        message: 'Contact ID is undefined'
      }
    });
  }
};