Reputation: 411
I have a select2 dropdown where I disable certain selections in the dropdown based on what was selected. So, in the select and unselect events I take the data that populates the dropdown, set the disabled property to true for any options that need it and rebuild the dropdown. On the select event, this works fine. On the unselect event it throws an error: Cannot read property 'query' of null. In the select2 library, "this.dataAdapter" is null when it tries to access this.dataAdapter.query.
The initialization code for the select2 dropdown is:
$(elem).select2({
data: $.map(scope.teacher.classes, function (cls) {
if (!found && cls.selected) {
scope.teacher.isTargeted = true;
scope.teacher.initTargeted = true;
found = true;
}
cls.id = cls.classId;
cls.text = cls.className;
if (cls.selected) {
scope.teacher.selectedClassIds.push(cls.classId);
scope.teacher.selectedClasses.push(cls);
}
return cls;
}),
multiple: true,
minimumResultsForSearch: Infinity,
width: 'auto',
})
The dropdown is built in an angular directive. The code that works in the select event is
var classes = scope.teacher.classes.map(function(cls) {
cls.id = cls.classId;
cls.text = cls.className;
cls.selected = scope.teacher.selectedClassIds.indexOf(cls.classId) > -1;
cls.disabled = scope.teacher.selectedClassIds.length == 0 ? false : cls.semester == semester ? false : true
return cls;
});
$(elem).select2().empty()
$(elem).select2({data: classes, width: 'auto'}).trigger('change');
In the unselect event the same code is being used with the exception that I'm setting the containerCssClass property on the select2 object and the error is thrown here.
var classes = scope.teacher.classes.map(function(cls) {
cls.id = cls.classId;
cls.text = cls.className;
cls.selected = scope.teacher.selectedClassIds.indexOf(cls.classId) > -1;
cls.disabled = scope.teacher.selectedClassIds.length == 0 ? false : cls.semester == semester ? false : true
return cls;
});
$(elem).select2().empty()
$(elem).select2({data: classes, width: 'auto', containerCssClass: scope.teacher.selectedClassIds.length > 0 ? '' : 'has-error_within required'}).trigger('change');
UPDATE
After looking at the issue more trying to determine the cause of the error, I've found that the error only occurs when clicking the x on the selected option displayed. If I open the dropdown and unselect the option, I don't get an error. I've tried with version 4.0.3 and 4.0.5 and 4.0.6.
Upvotes: 1
Views: 3246
Reputation: 411
I found this same issue on the select2 issues list but closed and not resolved. It seems like a bug but the work around found in that thread is to call the open event before changing the data.
$(elem).select2('open');
$(elem).select2({data: classes, width: 'auto', containerCssClass: scope.teacher.selectedClassIds.length > 0 ? '' : 'has-error_within required'}).trigger('change');
Upvotes: 1