2017-05-08 106 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'); 
    } 
相關問題