Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Handle list of initial objects in ajax select2
Anna Siwik06772da9dfe4
diff --git a/saleor/core/forms.py b/saleor/core/forms.pyindex de4330c3d5..781897a36a 100644--- a/saleor/core/forms.py+++ b/saleor/core/forms.py@@ -7,6 +7,7 @@ class AjaxSelect2ChoiceField(forms.ChoiceField):""" This field enables usage of select2 with ajax fetched data.fetch_data_url - specifies url, from which select2 will fetch data+ initial - initial object"""def __init__(self, fetch_data_url='', initial=None, *args, **kwargs):@@ -32,22 +33,48 @@ class AjaxSelect2ChoiceField(forms.ChoiceField):return Truedef set_initial(self, obj):- """ Sets initially selected object on field's widget. """- self.widget.attrs['data-initial-display'] = str(obj)- self.widget.attrs['data-initial-value'] = obj.pk+ """ Sets initially selected objects on field's widget. """+ selected = {'id': obj.pk, 'text': str(obj)}+ self.widget.attrs['data-initial'] = json.dumps(selected)+++class AjaxSelect2MultipleChoiceField(forms.MultipleChoiceField):+ """ This field enables selecting multiple values in select2+ with ajax fetched data.+ fetch_data_url - specifies url, from which select2 will fetch data+ initial - list of initial objects+ """-class AjaxSelect2MultipleChoiceField(AjaxSelect2ChoiceField):- """ Enables multiple select for AjaxSelect2ChoiceField. """def __init__(self, fetch_data_url='', initial=[], *args, **kwargs):- super(AjaxSelect2MultipleChoiceField, self).__init__(- fetch_data_url, initial, *args, **kwargs)- self.widget.attrs['multiple'] = True+ self.queryset = kwargs.pop('queryset')+ super(AjaxSelect2MultipleChoiceField, self).__init__(*args, **kwargs)+ self.widget.attrs['class'] = 'enable-ajax-select2'+ self.widget.attrs['data-url'] = fetch_data_urlif initial:self.set_initial(initial)+ self.widget.attrs['multiple'] = True++ def to_python(self, value):+ if value in self.empty_values:+ return None+ elif not isinstance(value, (list, tuple)):+ raise ValidationError(+ self.error_messages['invalid_list'], code='invalid_list')+ for choice in value:+ try:+ self.queryset.get(pk=choice)+ except (ValueError, TypeError, self.queryset.model.DoesNotExist):+ raise forms.ValidationError(+ self.error_messages['invalid_choice'],+ code='invalid_choice')+ return [str(val) for val in value]++ def valid_value(self, value):+ forms.Field.validate(self, value)+ return Truedef set_initial(self, objects):""" Sets initially selected objects on field's widget. """- self.widget.attrs['data-initial'] = json.dumps([- {'id': obj.pk, 'text': str(obj)} for obj in objects- ])+ selected = [{'id': obj.pk, 'text': str(obj)} for obj in objects]+ self.widget.attrs['data-initial'] = json.dumps(selected)diff --git a/saleor/dashboard/discount/forms.py b/saleor/dashboard/discount/forms.pyindex b5e39ee749..9954c98f07 100644--- a/saleor/dashboard/discount/forms.py+++ b/saleor/dashboard/discount/forms.py@@ -26,7 +26,8 @@ class SaleForm(forms.ModelForm):def __init__(self, *args, **kwargs):super(SaleForm, self).__init__(*args, **kwargs)- self.fields['products'].set_initial(self.instance.products.all())+ if self.instance.pk:+ self.fields['products'].set_initial(self.instance.products.all())def clean(self):cleaned_data = super(SaleForm, self).clean()diff --git a/saleor/static/dashboard/js/components/utils.js b/saleor/static/dashboard/js/components/utils.jsindex 65cd9bf430..09b748d3e2 100644--- a/saleor/static/dashboard/js/components/utils.js+++ b/saleor/static/dashboard/js/components/utils.js@@ -23,24 +23,25 @@ export function initSelects() {$ajaxSelect2Elements.each(function() {let $select = $(this);- if ($select.attr('data-initial-display') &&- $select.attr('data-initial-value')) {- let display = $select.data('initial-display');- let value = $select.data('initial-value');-- $select.append($('<option></option>').attr('value', value).text(display));- $select.val(value);- };-if ($select.attr('data-initial')) {- let initial = $select.data('initial');- let selected = []- initial.forEach(function(item) {+ function appendOption(select, option) {$select.append($('<option></option>').attr(- 'value', item.id).text(item.text));- selected.push(item.id);- });- $select.val(selected);+ 'value', option.id).text(option.text));+ }++ let initial = $select.data('initial');+ if (initial instanceof Array) {+ let selected = []+ initial.forEach(function(item) {+ appendOption($select, item);+ selected.push(item.id);+ });+ $select.val(selected);+ }+ else {+ appendOption($select, initial);+ $select.val(initial.id);+ }};let url = $select.data('url');