Pragmatic allows the creation of events that facilitate data preloading in a form instance. This data can be obtained from different sources depending on the selected event type: SQL, MongoDB, or JavaScript function.

The event execution occurs exclusively at the Load execution moment. This moment occurs when the user accesses the form, so this is where we seek to obtain the data, load it onto the instance, and make the data immediately visible in the corresponding fields.



Creating Data Preload Events

General Conditions

For a data preload event to work correctly, the following requirements must be met:

  1. The event must return a valid response structure according to the event type.
  2. The field response structure must follow the syntax specified for that event type for correct data mapping.
  3. Once created, the event must be associated with the form and configured in the events section of a form, to be executed at the form instance load moment.



Implementation by Event Type

SQL Event Type

For an SQL event type, data preloading is implemented through an SQL query that must return a single record. The column names in the query must match the field IDs or unique names of the form.

Specific Conditions:

  • A single record must be obtained in the query results.
  • The column name must be specified as the ID or the unique name of the field to which the data will be loaded.

Example:

SELECT 
    id as "banco-id",  -- Can use unique name or numeric ID (e.g., "20")
    abono_mensual as "banco-abonoMensual", 
    nombre as "20",  -- Using numeric ID instead of unique name
    descripcion as "banco-descripcion", 
    porcentaje_promocion as "banco-porcentajePromocion", 
    fecha_promocion as "banco-fechaPromocion" 
FROM bancos 
WHERE id = @parameter.idBanco

Supported Field Types and Syntax:

Field TypeSyntaxValue Example
TextMust be a string"John Carlos Pérez González"
Long TextMust be a string"Reason 1: The project requires an initial investment higher than budgeted.\nReason 2: Delivery times are not feasible according to the proposed schedule."
NumberMust be a numeric value42 or 3.14
PercentageMust be a numeric string between 0 to 100"75" or "99.9"
DateMust be a string in ISO 8601 format"2024-04-08T00:00:00.000Z"



MongoDB Event Type

For a MongoDB event type, data preloading is implemented through an aggregation query that must return a single document.

The return structure must be the same as that used in the JavaScript function event type, that is, an array of objects where each object contains EITHER uniqueName OR id (not both) and value. For more details about the value structure according to the field type, see the supported field syntax.

Specific Conditions:

  • A single document must be obtained in the results
  • The query must transform the data to return an array of objects with the structure:
    [
      {
        "uniqueName": "field-name",  // Or use "id"
        "value": value
      }
    ]

Example:

[
  // 1. Filter document by ID
  { $match: { _id: ObjectId(@parameter._id) } },
  
  // 2. Convert _id to string to avoid serialization issues
  { 
    $addFields: { 
      _id: { $toString: "$_id" } 
    } 
  },
  
  // 3. Convert document to key-value pairs array
  { 
    $project: {
      kv: { $objectToArray: "$$ROOT" }
    }
  },
  
  // 4. Map each field to the required structure
  {
    $project: {
      mapped: {
        $map: {
          input: "$kv",
          as: "field",
          in: {
            uniqueName: {
              $switch: {
                branches: [
                  { case: { $eq: ["$$field.k", "_id"] },   then: "usuario-id" },  // Can use unique name or numeric ID
                  { case: { $eq: ["$$field.k", "nombre"] },   then: "20" },  // Using numeric ID instead of unique name
                  { case: { $eq: ["$$field.k", "apellido"] }, then: "usuario-apellidos" },
                  { case: { $eq: ["$$field.k", "correo"] }, then: "usuario-correoElectronico" },
                  { case: { $eq: ["$$field.k", "celular"] }, then: "usuario-celular" },
                  { case: { $eq: ["$$field.k", "fechaNacimiento"] }, then: "usuario-fechaNacimiento" },
                  { case: { $eq: ["$$field.k", "promedioSemestral"] }, then: "usuario-promedioSemestral" },
                  { case: { $eq: ["$$field.k", "nivelEstudios"] }, then: "usuario-nivelEstudios" },
                  { case: { $eq: ["$$field.k", "activo"] }, then: "usuario-activo" },
                  { case: { $eq: ["$$field.k", "tareasPorRealizar"] }, then: "usuario-tareas" },
                  { case: { $eq: ["$$field.k", "eventoPorAsistir"] }, then: "usuario-evento" },
                  { case: { $eq: ["$$field.k", "invitacion"] }, then: "usuario-invitacion" }
                ],
                default: null
              }
            },
            value: "$$field.v"
          }
        }
      }
    }
  },
  
  // 5. Clean structure to get only mapped data
  { 
    $project: { 
      _id: 0, 
      data: "$mapped" 
    } 
  },
  
  // 6. Expand array into individual documents
  { $unwind: "$data" },
  
  // 7. Replace root with each mapped document
  { $replaceRoot: { newRoot: "$data" } }
]



JavaScript Function Event Type

For a JavaScript function event type, data preloading is implemented through a function that must return an array of objects with the response structure.

The return structure must be the same as that used in the MongoDB event type, that is, an array of objects where each object contains EITHER uniqueName OR id (not both) and value. For more details about the value structure according to the field type, see the supported field syntax.

Specific Conditions:

  • The function must return an array of objects
  • Each object must contain:
    • uniqueName OR id: Identifier of the field to which the mapping will be done. One or the other must be used, not both
    • value: The value corresponding to the field, which must follow the structure corresponding to the field type
  • The value must follow the structure corresponding to the field type

Example:

// 1. Get necessary data
const idBanco = @parameter.idBanco

// 2. Make API request
return axios.get(`https://api.ejemplo.com/bancos/${idBanco}`)
.then((response) => {
    const banco = response.data
    
    // 3. Return response structure
    return [
        {
            "uniqueName": "banco-id",  // Using unique name
            "value": banco.id
        },
        {
            "uniqueName": "banco-abonoMensual",  // Using unique name
            "value": banco.abono_mensual
        },
        {
            "id": 20,  // Using numeric ID
            "value": banco.nombre
        },
        {
            "uniqueName": "banco-descripcion",  // Using unique name
            "value": banco.descripcion
        },
        {
            "uniqueName": "banco-porcentajePromocion",  // Using unique name
            "value": banco.porcentaje_promocion.toString()
        },
        {
            "uniqueName": "banco-fechaPromocion",  // Using unique name
            "value": banco.fecha_promocion
        }
    ]
})

Supported Field Types and Syntax for MongoDB and Function:

For data preloading to work correctly in MongoDB and JavaScript Function events, each event type must return data in the appropriate format according to the field type. Below is the response structure for each field type:

Field TypeResponse StructureValue
TextThe value is of type string, that is, a simple text."John Pérez"
PercentageThe value is an integer, but must be stored as string."75"
GridThe structure is an array of arrays, where each sub-array has a number followed by a text.[[1, "Item A"], [2, "Item B"]]
PromptThe structure is an object that has a value property of type number and a description property that is an array of objects with label (string) and value (can be string, boolean or number).{ "value": 3, "description": [{ "label": "Category", "value": "Event" }] }
AttachmentThe structure is an array of objects, where each object has the properties uuid, name, type and size (all are required).[ { "uuid": "unique-id", "name": "document.docx", "type": "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "size": 45678 } ]
Long TextThe value is of type string, but line breaks are allowed."Description line 1\nDescription line 2"
DateThe value is a string in ISO 8601 format, which has the form "YYYY-MM-DDTHH:MM:SS.sssZ"."2024-04-08T00:00:00.000Z"
NumberThe value is of type number, and must be an integer or decimal. This is validated by checking that typeof value === "number". This ensures that only numeric values are accepted.42
ComboThe value is an object with the value property, which can be of type number or string. The structure is: module.exports = { type: "object", properties: { value: { type: ["number", "string"] } }, required: ["value"] };{ "value": "Option 1" }
Multiple ComboThe value is an array of objects, where each object has the properties value and label, both of type string.[ { "value": "Option 1", "label": "Label 1" }, { "value": "Option 2", "label": "Label 2" } ]
BooleanThe value is of type boolean, that is, true or false.true or false



Example Structure for Each Field Type

For a form containing each field type, the correct structure to preload the data for each field would be as follows. You can use EITHER id OR uniqueName to identify the field:

[
  {
    "id": "21", // Percentage - Using numeric ID
    "value": "98"
  },
  {
    "uniqueName": "usuario-nombre", // Text - Using unique name
    "value": "John Pérez"
  },
  {
    "id": "25", // Grid - Using numeric ID
    "value": [
      [1, "Item A"],
      [2, "Item B"]
    ]
  },
  {
    "uniqueName": "usuario-evento", // Prompt - Using unique name
    "value": {
      "value": 2,
      "description": [
        {
          "label": "id",
          "value": 2
        },
        {
          "label": "Name",
          "value": "Tech Hackathon"
        },
        {
          "label": "Is presential",
          "value": "No"
        }
      ]
    }
  },
  {
    "id": "28", // Attachment - Using numeric ID
    "value": [
      {
        "uuid": "123e4567-e89b-12d3-a456-426614174000",
        "name": "document.pdf",
        "type": "application/pdf",
        "size": 102400
      }
    ]
  },
  {
    "uniqueName": "usuario-descripcion", // Long Text - Using unique name
    "value": "Description line 1\nDescription line 2"
  },
  {
    "id": "31", // Date - Using numeric ID
    "value": "2023-05-15T10:30:00.000Z"
  },
  {
    "uniqueName": "usuario-cantidad", // Number - Using unique name
    "value": 100
  },
  {
    "id": "37", // Combo - Using numeric ID
    "value": {
      "value": "primary",
      "label": "Primary"
    }
  },
  {
    "uniqueName": "usuario-equipos", // Multiple Combo - Using unique name
    "value": [
      {
        "value": "laptop",
        "label": "Dell Laptop"
      },
      {
        "value": "monitor",
        "label": "24 inches monitor"
      }
    ]
  },
  {
    "id": "42", // Boolean - Using numeric ID
    "value": true
  }
]