I'm trying to use alpaca.js to populate a database.
I'm wanting to populate a set of form fields based on an ajax lookup on one field. I want to do an autocomplete on a hotel name field and populate other fields based on the hotel selected, e.g. number of rooms, number of floors, address, phone, etc.
My test code produces an "Uncaught TypeError: control.childrenByPropertyId is undefined" error.
I'm assuming that there is some mismatch of Javascript libraries.
My example code (I've modified urls by adding some spaces):
<!DOCTYPE html>
<html>
<head>
<title>Hotel Form</title>
<meta charset="UTF-8">
<link type="text/css" rel="stylesheet" href="//maxcdn. bootstrapcdn. com/ bootstrap/3.2.0/css/bootstrap.min.css">
<link type="text/css" rel="stylesheet" href="//cdn. jsdelivr. net/npm/[email protected]/dist/alpaca/bootstrap/alpaca.min.css">
<script type="text/javascript" src="//code. jquery. com/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="//maxcdn. bootstrapcdn. com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script type="text/javascript" src="//cdnjs. cloudflare. com/ajax/libs/handlebars.js/4.0.5/handlebars.js"></script>
<script type="text/javascript" src="//cdn. jsdelivr. net/npm/[email protected]/dist/alpaca/bootstrap/alpaca.min.js"></script>
</head>
<body>
<div id="hotel-form"></div>
<script>
$(document).ready(function() {
// Define the schema for the form
var schema = {
"type": "object",
"properties": {
"hotel": {
"type": "string",
"title": "Hotel",
"autocomplete": {
"url": "hotels?q=%QUERY",
"dataType": "jsonp",
"displayKey": "name",
"valueKey": "id",
"cache": true,
"limit": 10,
"templates": {
"suggestion": Handlebars.compile("<div>{{name}} - {{address}}</div>")
}
}
},
"numRooms": {
"type": "integer",
"title": "Number of Rooms"
},
"numFloors": {
"type": "integer",
"title": "Number of Floors"
},
"address": {
"type": "string",
"title": "Address"
}
}
};
// Define the options for the form
var options = {
"fields": {
"hotel": {
"type": "search",
"size": 40,
"placeholder": "Type the name of a hotel",
"helper": "Select a hotel from the list",
"removeDefaultNone": true
}
},
"form": {
"buttons": {
"submit": {
"title": "Submit"
}
}
},
"postRender": function(control) {
// When the hotel field changes, populate the other fields
control.childrenByPropertyId["hotel"].on("change", function() {
var hotelId = this.getValue();
if (hotelId) {
$.getJSON("hotels/" + hotelId, function(data) {
control.childrenByPropertyId["numRooms"].setValue(data.numRooms);
control.childrenByPropertyId["numFloors"].setValue(data.numFloors);
control.childrenByPropertyId["address"].setValue(data.address);
});
}
});
}
};
// Render the form
$("#hotel-form").alpaca({
"schema": schema,
"options": options
});
});
</script>
</body>
</html>