Keine Beschreibung

jquery.grp_related_fk.js 2.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /**
  2. * GRAPPELLI RELATED FK
  3. * foreign-key lookup
  4. */
  5. (function($){
  6. var methods = {
  7. init: function(options) {
  8. options = $.extend({}, $.fn.grp_related_fk.defaults, options);
  9. return this.each(function() {
  10. var $this = $(this);
  11. var $parent = $this.parent();
  12. // remove djangos object representation
  13. if ($parent.find('a.related-lookup').next().is('strong')) {
  14. $parent.find('a.related-lookup').get(0).nextSibling.nodeValue="";
  15. $parent.find('a.related-lookup').next('strong').remove();
  16. }
  17. // add placeholder
  18. $parent.find('a.related-lookup').after(options.placeholder);
  19. // add related class
  20. $this.addClass('grp-has-related-lookup');
  21. // lookup
  22. lookup_id($this, options); // lookup when loading page
  23. $this.on("change focus keyup", function() { // id-handler
  24. lookup_id($this, options);
  25. });
  26. });
  27. }
  28. };
  29. $.fn.grp_related_fk = function(method) {
  30. if (methods[method]) {
  31. return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
  32. } else if (typeof method === 'object' || ! method) {
  33. return methods.init.apply(this, arguments);
  34. } else {
  35. $.error('Method ' + method + ' does not exist on jQuery.grp_related_fk');
  36. }
  37. return false;
  38. };
  39. var lookup_id = function(elem, options) {
  40. var text = elem.parent().find('.grp-placeholder-related-fk');
  41. $.getJSON(options.lookup_url, {
  42. object_id: elem.val(),
  43. app_label: grappelli.get_app_label(elem),
  44. model_name: grappelli.get_model_name(elem),
  45. query_string: grappelli.get_query_string(elem),
  46. to_field: grappelli.get_to_field(elem)
  47. }, function(data) {
  48. if (data[0].label === "") {
  49. text.hide();
  50. } else {
  51. text.show();
  52. }
  53. if (data[0].safe) {
  54. text.html($('<span class="grp-placeholder-label"></span>').html(data[0].label + '\u200E'));
  55. } else {
  56. text.html($('<span class="grp-placeholder-label"></span>').text(data[0].label + '\u200E'));
  57. }
  58. });
  59. };
  60. $.fn.grp_related_fk.defaults = {
  61. placeholder: '<div class="grp-placeholder-related-fk"></div>',
  62. repr_max_length: 30,
  63. lookup_url: ''
  64. };
  65. })(grp.jQuery);