2017-05-08 107 views
3

我有一个奇怪的问题。我的web应用程序中有一个产品选择元素项目。因为数据库中有很多产品,我决定用select2动态加载它们。问题是我想传递一个额外的参数(单位),将显示在选择框对面。所以要找到一个产品,我使用Django作为后端,我的方法看起来像这样。select2参数为templateResult和templateSelection不同(django)

class FindProductAjaxView(AjaxableResponseMixin, CreateView): 
    model = Product 
    form_class = ProductForm 

    def get_ajax(self, request, *args, **kwargs): 
     query = request.GET.get('q', None) 
     if query: 
      products = Product.objects.filter(name__icontains=query).values(
       "pk", "name", "unit") 
      results = list(products) 
      return JsonResponse(data={'items': results}, safe=False) 
     else: 
      return JsonResponse(data={'success': False, 
             'errors': 'No mathing items found'}) 

所以它正确地返回pk,名称和单位字段。这里是我用来创建我的select2产品输入的脚本。

<script> 
    function initProductSelect2 (select) { 
     select.select2({ 
      placeholder: "Wyszukaj...", 
      ajax: { 
       url: '/recipes/find_product', 
       dataType: 'json', 
       delay: 250, 
       language: 'pl', 
       data: function (params) { 
        return { 
        q: params.term, // search term 
        page: params.page 
        }; 
       }, 
       processResults: function (data) { 
        data = data.items.map(function (item) { 
         return { 
          id: item.pk, 
          text: item.name, 
          name: item.name, 
          unit: item.unit 
         }; 
        }); 
        return { results: data }; 
       }, 
       cache: true 
      }, 
      escapeMarkup: function (markup) { return markup; }, 
      minimumInputLength: 1, 
      templateResult: formatItem, 
      templateSelection: formatItemSelection 
     }); 
     select.siblings('span').find('.select2-selection').addClass('form-control'); 
    } 

    function formatItem (item) { 
     console.log(item) 
     if (item.loading) return item.name || item.text; 
     var markup = '<div class="clearfix" data-unit=' + item.unit + '>' + item.name + '</div>'; 
     return markup; 
    } 

    function formatItemSelection (item) { 
     console.log(item); 
     return item.name || item.text; 
    } 
</script> 

问题在于该formatItemformatItemSelection方法中。传递给formatItem的项目是可以的。它具有我需要的所有字段(PK,名称,单位)。但是进入formatItemSelection的项目只有id和文本字段。

我一直在努力解决这个问题几个小时,但我不知道。我试过(正如你在代码中看到的那样)将单元参数作为jQuery数据元素传递,但我不知道如何检索它。最好的解决方案是,如果传递给formatItemSelection的项目将拥有从控制器传递的所有字段(pk,name,unit)。

在此先感谢!

编辑:我用选择2的最新版本4.0.3

回答

1

好吧,我有一个答案。在initProductSelect2()的上下文中,我创建了一个options对象,该对象在ProcessResults中填充,然后在选择事件被触发时从那里检索我的选项。我也改变了processResults方法。这是我的更新代码,其中显示了所选产品的单位。我初始化了我的select2,但是像这样使用了第二个参数:initProductSelect2(select, [])

function initProductSelect2 (select, options) { 
     select.select2({ 
      placeholder: "Wyszukaj...", 
      ajax: { 
       url: '/recipes/find_product', 
       dataType: 'json', 
       delay: 250, 
       language: 'pl', 
       data: function (params) { 
        return { 
        q: params.term, // search term 
        page: params.page 
        }; 
       }, 
       processResults: function (data, params) { 
        params.page = params.page || 1; 
        data.items.forEach(function (entry, index) { 
         entry.id = entry.pk; 
        }); 
        options = data.items; 
        return { 
         results: data.items, 
         pagination: { 
          more: (params.page * 30) < data.total_count 
        } 
        }; 
       }, 
       cache: true 
      }, 
      escapeMarkup: function (markup) { return markup; }, 
      minimumInputLength: 1, 
      templateResult: formatItem, 
      templateSelection: formatItemSelection 
     }); 
     select.on("select2:select", function(e) { 
      var id = $(this).val(); 
      var result = $.grep(options, function(e){ return e.id == id; }); 
      if (result.length != 0) { 
       alert(result[0].unit); 
      } 
     }); 
     select.siblings('span').find('.select2-selection').addClass('form-control'); 
    } 
相关问题