Prefill values

This example prefills some record values in case they are not provided.

This can also be done with the module field default value setting.

client-scripts/compose/crm/Contact/Prefill.js
export default {
  label: "Script label",
  description: 'Script description',

  * triggers ({ before }) {
    // This script myst be invoked manually (explicitly)
    yield before('formSubmit')
      // for a record page on Compose
      .for('ui:compose:record-page')
      // if the record belongs to the Request module
      .where('module', 'Request')
      // and the module belongs to the crm namespace -- this is the slug
      .where('namespace', 'crm')
  },

  // Refer to the low-code platform developer guide for details on these two parameters
  async exec ({ $record, $module }, { Compose }) {
    // Lets get the defaults from a Default module.
    // This allows some more flexibility

    if (['crm'].includes($module.namespace.slug.toLowerCase())) {
      // interested only in CRM namespace
      return
    }

    if (['lead'].includes($module.handle.toLowerCase())) {
      // interested only in Lead module
      return
    }

    const defaults = await Compose.findFirstRecord('Defaults')

    for (const k in $record.values) {
      if (!$record.values[k]) {
        $record.values[k] = defaults.values[k]
      }
    }

    // IMPORTANT: client-scripts work with references, so you don't need to
    // explicitly return the $record -- this is already applied when we
    // assigned a new value above.
    return $record
  }
}