Firstly thanks to Nicolas & Oliver for posting code examples and being of the belief we'll all benefit here's a working example building on Nicolas' simple record copy here http://helpdesk.knackhq.com/support/discussions/topics/5000007940.
Scenario: Estimates with Estimate Items (one-many) are built using a complex Billing System -> Estimate Template -> Estimate template items structure that allow users to select a template for their estimate and have the estimate items inserted ready for modification. This replicates a tried and tested system built in Access and users love it.
So here's the Javascript code example complete with possible inefficiencies from a Javascript newbie (feedback welcome):
$(document).on('knack-record-create.view_167', function(event, view, record) {
Knack.showSpinner();
var KnackAppID = “XXXX”
var KnackAPIKey= “YYYY”
var EstimateID = [record.id]
var Estimate = record
var EstimateTemplateID = record.field_207_raw[0].id
var BillingSystemID = record.field_208_raw[0].id
var api_url = ‘https://api.knackhq.com/v1/objects/object_23/records’; // api access to EstimateTemplateitems
var filters = [{field: ‘field_222’, operator: ‘is’, value: EstimateTemplateID}]
api_url += ‘?filters=’ + encodeURIComponent(JSON.stringify(filters));
//Get EstimateTemplateItems
$.ajax({url: api_url, type: "GET",
headers: {"X-Knack-Application-Id": KnackAppID, "X-Knack-REST-API-Key":KnackAPIKey},
success: function(data) { //alert('Records Retrieved!' + data.total_records);
//Loop through data, build newdata and insert new record into EstimateItems
for(var i = 0; i < data.total_records; i++) {
//alert(data.records[i].field_200);
var newdata = {
field_163: data.records[i].field_198, //Text
field_165: i + 1, //Order
field_170: data.records[i].field_200_raw[0].id, //Billing item Connection
field_172: data.records[i].field_201, //Hourly Rate
field_173: data.records[i].field_202, //Hours
field_179: BillingSystemID, //Billing System
field_210: EstimateID //Estimate
}
//Add data to EstimateItems
$.ajax({
url: "https://api.knackhq.com/v1/objects/object_19/records/",
type: "POST",
headers: {"X-Knack-Application-Id": KnackAppID, "X-Knack-REST-API-Key":KnackAPIKey},
data: newdata,
//success: function(response) {alert('Records Added!');}
});
}
Knack.hideSpinner();
}
});
});