0
votes

I have a Styles (Garments) model and an Images model and a one to many Styles<=Images relationship.

I have a Cloudinary jQuery widget to upload images and then I am trying to update the Images relationship with the URL to the images. The intention is then to display these images in a table.

However, when I update the relation using my code, it only saves the newest StyleCode against the relation.

So if I save one image, then another one, the Image table goes from this:

Image URL         Style
http://abc        1234

to this

Image URL         Style
http://abc        <blank>
http://xyz        1234  

My first question is, how does the relation actually work? It seems it relies on my StyleCode to keep the record relation. I would've thought it would've been _key.....????

Secondly, is there anything you can spot in my code which might be overwriting the previous StyleCode?

Server side code

function saveImageToStyle(images, styleCode) {
  var imgs = [];
  images.forEach(function(image)
  {
    var imageRecord = app.models.Images.newRecord();
    imageRecord.ThumbnailURL = image.thumbnail_url;
    imageRecord.ImageURL = image.url;
    imageRecord.Path = image.path;
    imageRecord.ImageName = image.original_filename;
    imgs.push(imageRecord);
  }); 
  app.saveRecords(imgs);
  var query = app.models.Styles.newQuery();
  query.filters.StyleCode._equals = styleCode; // is it this???
  var styleRecord = query.run()[0];
  styleRecord.Images = imgs;
  app.saveRecords([styleRecord]);
}

Client side code

function saveStyleImages(images) {
  var styleCode = app.datasources.Styles.item.StyleCode; // is there a better way to get the current StyleCode?
  var status = app.pages.StyleEdit.descendants.Status; 
  google.script.run
  .withFailureHandler(function(error) {
    status.text = error.message;
  })
  .withSuccessHandler(function(result) {
    status.text = images + "success";
  })
  .saveImageToStyle(images, styleCode);
}
2

2 Answers

1
votes

Looks like you can do everything on the client (if you don't have any limitations with your security model):

function addStyleImage(newImage) {
  var newImageDs = app.datasources.Styles.relation.Images.modes.create;
  var newImage = newImageDs.item;

  newImage.ThumbnailURL = image.thumbnail_url;
  newImage.ImageURL = image.url;
  newImage.Path = image.path;
  newImage.ImageName = image.original_filename;

  newImageDs.createItem(function(record) {
     // do smth with new record
  });
}

With this approach you'll immediately see new image on client (if Images relation is bound to table/list/grid).

Read more:

https://developers.google.com/appmaker/models/datasources#create_mode_datasource

0
votes

The following line replaces all existing style associations:
styleRecord.Images = imgs;

You can replace it with:
styleRecord.Images = styleRecord.Images.concat(imgs);