Search code examples
javascriptgoogle-app-maker

How to detect an error in item creation on the client side (App Maker)


I am creating an app to store schedules and I do not want two schedules with the same date. To combat this I added this code (javascript) to the onBeforeCreate() and onBeforeSave() events.

var query = app.models.DataSource.newQuery(); // New query

query.filters.date._equals = record.date; //Search for a record that has the same 

if (query.run().length) {
  throw new Error("There is already a schedule on that date"); // Throw an error
}

This works great to prevent the duplicate entries, but how would I go about detecting this on the client side and reporting it to the user?

Its probably a quick fix but any input would be greatly appreciated :)

Thanks!!


Solution

  • First, you need to modify the datasource field to be unique.
    You'll need to go to ModelName > FieldName > Advanced:

    enter image description here

    Then, when creating the item on the client side, let's say, for example, using a button widget which its datasource is set in create mode, then on the onClick event handler, use the following:

    widget.datasource.createItem({
      success: function(record){
        console.log(record._key);
      },
      failure: function(error){
        var err = error.toString();
        if(err.indexOf("Duplicate entry") > -1){
          alert("There is already a schedule on that date");
        } else {
          alert(error.toString());
        }
      }    
    });
    

    For more information, I recommend you to consult the official documentation.