Help

Update Records with IF statement

Topic Labels: Automations
972 1
cancel
Showing results for 
Search instead for 
Did you mean: 
schbrtls
4 - Data Explorer
4 - Data Explorer

Hey, 

I am a complete Java noob and I'm currently trying to write a script that looks up a record (atOrgID) fetched from a previous search step, and first checks if a specific field is already filled. If so, I want it to add an additional value to the already existing ones in that field, if not, I just want the script to update the field with the provided value. This value is also taken from a previous search step (productId) 

With the help of chatGTP I created this script but it doesn't perform any updates: 

 

let table = base.getTable("Org2")
let field = table.getField("Product IDs")
let inputConfig = input.config();
const atOrgID = inputConfig.atOrgID;
const productId = inputConfig.productId;

function addProductIDToRecord(atOrgID, productId) {
    // Holt schon existierende Einträge in dem Feld "Produkt ID"
    table
    .selectRecordsAsync({
      fields: [field],
      recordIds: [atOrgID],
    })
    .then((queryResult) => {
      let record = queryResult.records[0];
      let existingProductIDs = record.getCellValueAsString(field);
    
    // Prüft, ob das Feld 'Produkt ID' schon befüllt ist
      if (existingProductIDs != null && existingProductIDs.length > 0) {
        // Erstellt eine Anordnung 
        let productIDArray = existingProductIDs.split(",");

        // Fügt die neue Produkt ID hinzu
        productIDArray.push(productId);

        //  Setzt das Update in das Feld ein 
        return table.updateRecordAsync(record, {
          [field.id]: productIDArray.join(","),
        });
      } else {
        // Wenn noch leer, dann setzt das Script einfach die productId ein
        return table.updateRecordAsync(record, {
          [field.id]: productId,
        });
      }
    })
    .then(() => {
      console.log("Record updated successfully");
    })
    .catch((error) => {
      console.error("Error updating record:", error);
    });
}

 

Anyone able to advise on what I need to change in order to make this work? 

 

1 Reply 1

You've defined the addProductIDToRecord function but never ran it. Add 

addProductIDToRecord(atOrgID, productId)

as the last line in your script to execute the function.

Side note, you can also return variables generated from automation scripts to use in subsequent "update record" actions via output.set('actionResult', someResult) - not to confuse you, as this would require returning different things in your function but could lead to simpler logic overall.