Code triggers
Settings → Code Triggers runs JavaScript you write when a lead, account, contact, opportunity, case or custom object record is created or updated, from anywhere: the app, the mobile app, the API, web forms, email to case, chat and other automation. Before the save, code can change fields or block the save with a message. After the save, it can look up, create and update other records, and call other systems’ REST APIs.
Code triggers are an add-on feature. If you don’t see Code Triggers in Settings under Automation, ask CRMSix support to turn it on. Creating and editing them needs the Customize application permission (Admin profile).
Try the no-code tools first. A workflow rule or a flow covers most field updates, emails, tasks and webhooks. Use a code trigger when the logic is easier to write than to click together: string handling, calculations, rules that look at related records, or many records at once.
1. Create a code trigger
- Go to Settings → Code Triggers and choose New code trigger.
- Give it a Name and choose the Object: Leads, Accounts, Contacts, Opportunities, Cases, or one of your custom objects (listed under Custom objects; see Custom objects).
- Write the code. The page starts you with an example for the object. As you type, it checks the code and shows which events it runs on, or the line with a mistake.
- Test it on a record (see Testing), then choose Save. With Active ticked, it runs from the next save.
2. The four functions
A code trigger runs only the functions it defines. Define one, some or all of them:
| Function | Runs | Use it to |
|---|---|---|
beforeInsert | When a record is created, before the save is final | Fill in or clean up fields, or block the save |
beforeUpdate | When a record is edited, before the save is final | Compare old and new values, change fields, or block the save |
afterInsert | After a record is created | Create tasks or related records, update other records |
afterUpdate | After a record is edited | Pass a change on to related records |
Each function gets one object:
{
records, // the records being saved (a list): read and, before the save, change their fields
old, // their values before the save, in the same order (updates only; null on insert)
user, // who is saving: { id, name, email }, or null for web forms, email and automation
object, // 'leads', 'accounts', 'contacts', 'opportunities' or 'cases'
event // 'beforeInsert', 'beforeUpdate', 'afterInsert' or 'afterUpdate'
}
Fields use their API names, such as last_name, stage or close_date. Custom fields end in __c. The editor lists every field of the object; click one to put its name in the code. Each record also has id and record_id (the 14-character ID shown in CRMSix).
3. Before the save: change fields or block it
Set a field on records[i] and the record is saved with the new value. Call addError to stop the save: the person saving sees your message and nothing is saved.
function beforeUpdate({ records, old }) {
records.forEach((opp, i) => {
// Note every stage change.
if (opp.stage !== old[i].stage) {
opp.next_step = 'Moved from ' + old[i].stage + ' to ' + opp.stage;
}
// A won deal needs an amount.
if (opp.stage === 'Closed Won' && !opp.amount) {
opp.addError('amount', 'Enter the amount before closing the deal as won');
}
});
}
record.addError('field', 'message')names the field in the message;record.addError('message')oraddError('message')doesn’t.- Values are checked as if you’d typed them: a picklist takes one of its values, a date is
YYYY-MM-DD, a number is a number, a user field takes an active user’s ID. A wrong value blocks the save and says why. - Fields CRMSix sets itself (such as
created_at,status_categoryor formula fields) can’t be changed. - In a before function you can look records up with
crm.queryandcrm.get, but not save other records: do that after the save.
4. After the save: work with other records
async function afterInsert({ records }) {
for (const lead of records) {
await crm.insert('tasks', {
subject: 'Call ' + lead.first_name + ' ' + lead.last_name,
lead_id: lead.id,
due_date: new Date(Date.now() + 2 * 86400000).toISOString().slice(0, 10),
priority: 'High',
});
}
}
async function afterUpdate({ records, old }) {
const account = records[0];
if (account.phone === old[0].phone) return;
const contacts = await crm.query('contacts', { where: { account_id: account.id, phone: null } });
await crm.update('contacts', contacts.map((c) => ({ id: c.id, phone: account.phone })));
console.log('Gave', contacts.length, 'contacts the new phone number');
}
The crm functions
| Call | Does |
|---|---|
await crm.query(object, { where, orderBy, limit }) | Finds records of leads, accounts, contacts, opportunities, cases, or a custom object by its API name, such as 'project__c'. Returns a list (up to 200; 50 if you don’t give a limit). orderBy is a field name, with - in front for newest or largest first (the default is -created_at). |
await crm.get(object, id) | One record by its id or record_id, or null. |
await crm.insert(object, record or list) | Creates records (after the save only). Also takes 'tasks': subject, description, due_date, priority (Normal or High), status, assigned_to, and one of case_id, lead_id, opportunity_id, contact_id. Returns what was created, with its id. |
await crm.update(object, record or list) | Updates records by their id (after the save only); give only the fields to change. |
console.log(...) | Writes a line to the test output and to Debug Logs. |
where matches each field you name:
where: {
status: 'Working', // equals (text ignores upper and lower case)
rating: ['Hot', 'Warm'], // one of
amount: { '>=': 10000, '<': 50000 }, // =, !=, >, >=, <, <=
company: { contains: 'Acme' }, // also startsWith, in, notIn
email: null, // is blank ({ '!=': null } is not blank)
}
Records you create or update run their own automation: validation rules, workflow rules, flows and their own code triggers. If one of them blocks the save, the crm call throws an error your code can catch with try … catch; nothing of that record is kept.
Custom objects
Code triggers work on custom objects too. Choose the object when you create the trigger, and name it by its API name (such as project__c) in crm.query, crm.get, crm.insert and crm.update. A custom object’s record has:
id,record_idandname, the record name. When the object numbers its records automatically (such as PRJ-0001), CRMSix gives the name and code can’t change it.owner_id,created_by,updated_by,created_atandupdated_at.- Each of its fields by its API name, such as
budget__c. A Lookup field holds theidof the record it points to.
// On Milestones: a new milestone needs its project to be open, and gets the project’s code.
async function beforeInsert({ records }) {
for (const m of records) {
const project = m.project__c ? await crm.get('project__c', m.project__c) : null;
if (!project || project.stage__c === 'Done') m.addError('project__c', 'Choose an open project');
else m.code__c = project.code__c + '-' + m.name;
}
}
Values are checked as the record page checks them: picklist values, required fields, controlling and dependent picklists, and that a Lookup points to an existing record. The object’s validation rules run on the record as saved, including the changes a before function made. Deleting a custom object also deletes its code triggers.
5. Calling other systems (REST APIs)
After the save, code can call a REST API, for example to send a new customer to your ERP and keep the ID it gives back.
- In Settings → Code Triggers, under Calling other systems, list the Allowed sites, one per line:
api.example.com, or*.example.comfor all its subdomains. Code can call only these, and only athttps://addresses. - Under Secrets, add the API’s key or token with a name such as
ERP_TOKEN. It’s stored encrypted and can’t be shown again, only replaced or deleted. - Call the API from
afterInsertorafterUpdate:
async function afterInsert({ records }) {
for (const account of records) {
const res = await http.post('https://erp.example.com/api/customers', {
headers: { Authorization: 'Bearer ' + secrets.ERP_TOKEN },
body: { name: account.name, phone: account.phone },
});
if (res.ok) {
await crm.update('accounts', { id: account.id, account_number: res.body.id });
} else {
console.warn('ERP said', res.status, res.body);
}
}
}
| Call | Does |
|---|---|
await http.get(url, { headers, query }) | A GET. query is added to the address: { query: { email: c.email } }. |
await http.post(url, { headers, body, query })http.put, http.patch, http.delete | The same with a body. An object is sent as JSON (Content-Type: application/json); a string is sent as it is. |
Each call answers { status, ok, headers, body }: body is parsed when the answer is JSON, and text otherwise. An error status such as 404 or 500 is returned, not thrown, so check res.ok. If the site can’t be reached or doesn’t answer within 5 seconds, the call throws an error; catch it with try … catch to let the save go through anyway.
Secrets stay secret. In code, secrets.ERP_TOKEN is only a placeholder: the real value goes into the request as it leaves CRMSix. The code, console.log, test output, error messages and debug logs never show it, and if the other system echoes it back, it’s hidden there too.
Waiting, or in the background
http.post(…) (and get, put, patch, delete) | http.queue.post(…) (and the others) | |
|---|---|---|
| When it’s sent | At once, while the save is going on | After the save commits |
| The person saving | Waits for the answer (up to 5 seconds) | Doesn’t wait |
| The answer | Returned to your code, which can use it in the same save (write an ID back, or block the save) | Given to a function you name in onResponse, which runs afterwards and can update records |
| If the other system is down | The call throws; catch it or the save is blocked | Tried again after 2 and 4 minutes (3 times in all) when there’s no answer or it answers 429 or 5xx |
| If the save is blocked | The call has already been made | Nothing is sent |
| Per save | 10 calls | 20 calls |
async function afterInsert({ records }) {
for (const account of records) {
await http.queue.post('https://erp.example.com/api/customers', {
headers: { Authorization: 'Bearer ' + secrets.ERP_TOKEN },
body: { name: account.name },
onResponse: 'saveErpId', // a function in this trigger (optional)
context: { accountId: account.id }, // handed to it as it is (up to 10 KB)
});
}
}
// Runs once the call is finished: answered, or failed after the last attempt.
async function saveErpId({ response, error, context, attempts, object, recordId }) {
if (response && response.ok) {
await crm.update('accounts', { id: context.accountId, account_number: response.body.id });
} else {
console.warn('ERP call failed:', error || response.status);
}
}
http.queue.*answers{ queued: true, id }at once. The trigger’s page lists its Background calls: when, the call, waiting, done, failed or cancelled, the attempts, the answer’s status and time, and any problem.- The
onResponsefunction runs as the person who saved, withcrm.*andhttp.*. It can’t queue more calls. If it fails, the error is kept on the call and on the trigger. - Calls still waiting when the trigger is made inactive or Code triggers are turned off are cancelled; deleting the trigger deletes them.
- Calls are usually sent within seconds of the save. A retry is sent when it’s due the next time someone in your organization has CRMSix open, and at the latest by the daily run.
- With
http.get,http.postand the others, the person saving waits for the calls, so keep them few and quick. They count toward the 8-second limit of a trigger. - Redirects aren’t followed: a 3xx answer is returned with its
locationheader. - Addresses on private networks are refused, even when listed.
- A call is made once, when the trigger runs. If the save is then blocked by another trigger or rule, the other system has still received it.
Testing
Under the code, Test runs the code as it is in the editor (saved or not) on a record of yours:
- Paste the record’s ID (the 14-character ID on its page).
- Choose A new record (insert) to run
beforeInsertandafterInsertas if it had just been created, or An edit (update) to runbeforeUpdateandafterUpdate. For an edit, enter the changes it makes as JSON, for example{ "status": "Working" }. - Choose Run test. You see whether the save would go through or be blocked, the fields the code changes, the records it would create or update, what it logged and how much of the limits it used.
Everything a test does is rolled back: no record is changed or created and no email or webhook goes out. GET calls to other systems are sent, so you can see their answers; POST, PUT, PATCH and DELETE calls are shown but not sent (they answer { status: 0, simulated: true }), and http.queue calls are shown but not queued, so a test can’t change anything in the other system.
Limits
Code runs in a sealed sandbox: it can’t reach files or other organizations, it has no timers, and it reaches the internet only through http calls to your allowed sites. These limits apply to each save, counting every trigger the save sets off, including saves your code makes:
| Limit | Per save |
|---|---|
| Time running code (CPU) | 2,000 ms |
| Time for one trigger, waiting for the database included | 8 seconds |
| Memory for one trigger | 32 MB |
crm.query and crm.get calls | 100, returning up to 2,000 records |
crm.insert and crm.update calls | 100, writing up to 500 records (200 per call) |
| Saves within saves (a trigger saving a record that runs triggers …) | 5 deep |
http calls | 10, each with 5 seconds to answer and up to 1 MB sent or received |
http.queue calls | 20, each with 5 seconds to answer and up to 1 MB sent or received |
console.log lines kept | 200 |
| Code length | 100,000 characters |
Each save runs the triggers once for the record saved, so records holds one record. Write your code for a list anyway (for (const r of records)) and it keeps working however records arrive.
Records added with Settings → Data Import don’t run code triggers, as they don’t run workflow rules or flows.
When code fails
- Someone is signed in (the app, the mobile app, the API): an error in the code, a wrong value or a limit blocks the save. They see the trigger’s name, the function and the line, for example Code trigger “Lead clean-up” (beforeInsert): TypeError: cannot read property 'x' of undefined (line 4).
- No one is signed in (web forms, email to case, chat, scheduled automation): the record is saved anyway, so no customer request is lost. What the failing trigger did is undone.
- Either way, the error is kept on the trigger: the Code Triggers list and the trigger’s page show the last error and when it happened.
To stop a trigger at once, untick Active and save, or delete it.
Debug logs
In Settings → Debug Logs, the Code triggers category records each trigger that runs, its console.log lines, and errors or messages that blocked a save. Field history shows changes made by code as Code trigger, with the trigger’s name.
Building in a sandbox
A sandbox’s copy of your organization includes its code triggers, so you can write and test code there without touching production. Allowed sites and secrets aren’t copied, so a sandbox calls no other system until you set them up there, for example with your ERP’s test site and key. When it works, create the trigger in production with the same code.