post_relations.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. // Fills in the dropdowns for relation fields -- the ones a post type declares
  2. // when it depends on posts of another type.
  3. //
  4. // The options are fetched rather than baked into the generated template so the
  5. // picker can't go stale: posts of the target type come and go long after the
  6. // type itself was written. Auth rides the tcmslogin cookie, so a same origin
  7. // request needs nothing else.
  8. function populateRelationPicker(select) {
  9. var form = select.getAttribute('data-relation-form');
  10. if (!form) {
  11. return;
  12. }
  13. var req = new XMLHttpRequest();
  14. req.addEventListener("load", function () {
  15. var payload;
  16. try {
  17. payload = JSON.parse(this.responseText);
  18. } catch (e) {
  19. console.log('could not read the post list for ' + form + ': ' + e);
  20. return;
  21. }
  22. var selected = select.getAttribute('data-selected') || '';
  23. // A relation that isn't required needs a way to say "none".
  24. if (!select.required) {
  25. select.appendChild(new Option('(none)', ''));
  26. }
  27. for (var post of payload.posts || []) {
  28. var option = new Option(post.title, post.id);
  29. option.selected = post.id === selected;
  30. select.appendChild(option);
  31. }
  32. });
  33. req.addEventListener("error", function () {
  34. console.log('could not fetch the post list for ' + form);
  35. });
  36. req.open("GET", "/api/posts_of_form?form=" + encodeURIComponent(form));
  37. req.send();
  38. }
  39. document.addEventListener("DOMContentLoaded", function(event) {
  40. var pickers = document.querySelectorAll('select.relation-picker');
  41. for (var picker of pickers) {
  42. populateRelationPicker(picker);
  43. }
  44. });