further fixes for card_multiselect breaking when removing all items; values are now static and quanity is stored in data-quantity. Also fix searching via label and change card_multiselect to accept list of cards instead of card_filter

This commit is contained in:
badblocks 2025-03-13 19:57:32 -07:00
parent b97ddde71c
commit 3df4b41750
7 changed files with 76 additions and 59 deletions

View file

@ -4,7 +4,7 @@ from cards.models import Card
register = template.Library()
@register.inclusion_tag('templatetags/card_multiselect.html')
def card_multiselect(field_name, label, placeholder, card_filter=None, selected_values=None, cache_timeout=86400, cache_key="available_cards_options"):
def card_multiselect(field_name, label, placeholder, cards=None, selected_values=None, cache_timeout=86400, cache_key="cards_multiselect"):
"""
Renders a multiselect field for choosing cards while supporting quantity data.
@ -16,7 +16,6 @@ def card_multiselect(field_name, label, placeholder, card_filter=None, selected_
- field_name: The name attribute for the select tag.
- label: Label text to show above the selector.
- placeholder: Placeholder text to show in the select.
- card_filter: (Optional) A dictionary of filter parameters or a QuerySet to obtain the available Card objects.
- selected_values: (Optional) A list of selected values; if a value includes a quantity it should be in the format "card_id:quantity".
- cache_timeout: (Optional) Cache timeout (in seconds) for the options block.
- cache_key: (Optional) Cache key.
@ -28,41 +27,28 @@ def card_multiselect(field_name, label, placeholder, card_filter=None, selected_
for val in selected_values:
parts = str(val).split(':')
card_id = parts[0]
quantity = parts[1] if len(parts) > 1 else "1"
quantity = parts[1] if len(parts) > 1 else 1
selected_cards[card_id] = quantity
# Determine how to obtain the available cards.
# If card_filter is not provided, or is None, fall back to all cards.
if card_filter is None:
available_cards_qs = Card.objects.all()
# If card_filter is a dict, treat it as mapping lookup parameters.
elif isinstance(card_filter, dict):
available_cards_qs = Card.objects.filter(**card_filter)
# Otherwise assume it's already a QuerySet.
else:
available_cards_qs = card_filter
available_cards = list(
available_cards_qs.order_by("name", "rarity__pk")
.select_related("rarity", "cardset")
.prefetch_related("decks")
)
if cards is None:
cards = Card.objects.all()
# Loop through available cards and attach preselected quantity
for card in available_cards:
for card in cards:
pk_str = str(card.pk)
if pk_str in selected_cards:
card.selected_quantity = selected_cards[pk_str]
card.selected = True
else:
card.selected_quantity = 1
card.selected = False
return {
'field_name': field_name,
'field_id': field_name, # using the name as id for simplicity
'label': label,
'available_cards': available_cards,
'cards': cards,
'placeholder': placeholder,
# Pass just the list of preselected card IDs for caching/selection logic in the template.
'selected_values': list(selected_cards.keys()),
'cache_timeout': cache_timeout,
'cache_key': cache_key,

View file

@ -59,8 +59,8 @@ class HomePageView(TemplateView):
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
# Add available_cards QuerySet so card_multiselect works properly.
context["available_cards"] = Card.objects.all() \
context["cards"] = Card.objects.all() \
.order_by("name", "rarity__pk") \
.select_related("rarity", "cardset") \
.prefetch_related("decks")

View file

@ -17,10 +17,10 @@
{% csrf_token %}
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
{% card_multiselect "have_cards" "I Have:" "Select some cards..." available_cards have_cards %}
{% card_multiselect "have_cards" "I Have:" "Select some cards..." cards have_cards %}
</div>
<div>
{% card_multiselect "want_cards" "I Want:" "Select some cards..." available_cards want_cards %}
{% card_multiselect "want_cards" "I Want:" "Select some cards..." cards want_cards %}
</div>
</div>
<div class="flex flex-col md:flex-row gap-4">

View file

@ -14,10 +14,10 @@
<!-- Card Selectors: "Have" and "Want" -->
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div class="form-control">
{% card_multiselect "have_cards" "I Have:" "Select some cards..." available_cards form.initial.have_cards %}
{% card_multiselect "have_cards" "I Have:" "Select some cards..." cards form.initial.have_cards %}
</div>
<div class="form-control">
{% card_multiselect "want_cards" "I Want:" "Select some cards..." available_cards form.initial.want_cards %}
{% card_multiselect "want_cards" "I Want:" "Select some cards..." cards form.initial.want_cards %}
</div>
</div>

View file

@ -10,10 +10,10 @@
{% csrf_token %}
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
{% card_multiselect "offered_cards" "Have:" "Select zero or more cards..." available_cards offered_cards %}
{% card_multiselect "offered_cards" "Have:" "Select zero or more cards..." cards offered_cards %}
</div>
<div>
{% card_multiselect "wanted_cards" "Want:" "Select zero or more cards..." available_cards wanted_cards %}
{% card_multiselect "wanted_cards" "Want:" "Select zero or more cards..." cards wanted_cards %}
</div>
</div>
<div class="flex flex-col md:flex-row gap-4">

View file

@ -5,11 +5,13 @@
<select name="{{ field_name }}" id="{{ field_id }}" class="select select-bordered w-full card-multiselect" data-placeholder="{{ placeholder }}" multiple>
{% cache cache_timeout cache_key selected_values|join:"," %}
<option value="" disabled>{{ placeholder }}</option>
{% for card in available_cards %}
{% for card in cards %}
<option
value="{{ card.pk }}:{{ card.selected_quantity }}"
{% if card.pk|stringformat:"s" in selected_values %}selected{% endif %}
data-html-content='{{ card|card_badge_inline:card.selected_quantity }}'
value="{{ card.pk }}"
data-card-id="{{ card.pk }}"
data-quantity="{{ card.selected_quantity }}"
{% if card.selected %}selected{% endif %}
data-html-content='{{ card|card_badge_inline:"__QUANTITY__" }}'
data-name="{{ card.name }}"
data-rarity="{{ card.rarity.icons }}"
data-cardset="{{ card.cardset.name }}">
@ -30,8 +32,7 @@ if (!window.updateGlobalCardFilters) {
let globalRarity = null;
selects.forEach(select => {
const selectedValuesRaw = select.choicesInstance ? select.choicesInstance.getValue(true) : [];
const selectedValues = selectedValuesRaw.map(val => val.split(':')[0]);
const selectedValues = select.choicesInstance ? select.choicesInstance.getValue(true) : [];
selectedValues.forEach(cardId => {
if (cardId && globalSelectedIds.indexOf(cardId) === -1) {
@ -40,7 +41,7 @@ if (!window.updateGlobalCardFilters) {
});
if (selectedValues.length > 0 && globalRarity === null) {
const option = select.querySelector(`option[value^="${selectedValues[0]}:"]`);
const option = select.querySelector(`option[value="${selectedValues[0]}"]`);
if (option) {
globalRarity = option.getAttribute('data-rarity');
}
@ -60,7 +61,6 @@ if (!window.updateGlobalCardFilters) {
item.style.display = '';
});
// filter out options and items that don't match the global rarity.
debugger;
if (globalRarity) {
select.querySelectorAll('option[data-rarity]:not([data-rarity="'+globalRarity+'"])').forEach(function(option) {
option.disabled = true;
@ -97,18 +97,21 @@ document.addEventListener('DOMContentLoaded', function() {
allowHTML: true,
closeDropdownOnSelect: false,
removeItemButton: true,
searchFields: ['data-name'],
searchFields: ['label'],
resetScrollPosition: false,
callbackOnCreateTemplates: function(template) {
// Helper to get HTML content and replace the __QUANTITY__ token.
const getCardContent = (data) => {
let htmlContent = (data.element && data.element.getAttribute('data-html-content')) || data.label;
let quantity = data.element.getAttribute('data-quantity');
quantity = quantity ? parseInt(quantity) : 1;
htmlContent = htmlContent.replace('__QUANTITY__', quantity);
return htmlContent;
};
const renderCard = (classNames, data, type) => {
const rarity = data.element ? data.element.getAttribute('data-rarity') : '';
const cardId = data.element ? data.element.getAttribute('value').split(':')[0] : 0;
const cardId = data.element ? data.element.getAttribute('data-card-id') : 0;
const cardname = data.element ? data.element.getAttribute('data-name') : '';
const content = getCardContent(data);
if (type === 'item') {
return template(`
@ -117,10 +120,11 @@ document.addEventListener('DOMContentLoaded', function() {
data-card-id="${cardId}"
data-item
data-rarity="${rarity}"
data-name="${cardname}"
aria-selected="true"
style="cursor: pointer; padding: 1rem;">
<button type="button" class="decrement absolute left-[-1.5rem] top-1/2 transform -translate-y-1/2 bg-gray-300 px-2">-</button>
<button type="button" class="increment absolute right-[-1.5rem] top-1/2 transform -translate-y-1/2 bg-gray-300 px-2">+</button>
<button type="button" class="decrement absolute left-[-1.5rem] top-1/2 transform -translate-y-1/2 bg-base-300 text-base-content px-2">-</button>
<button type="button" class="increment absolute right-[-1.5rem] top-1/2 transform -translate-y-1/2 bg-base-300 text-base-content px-2">+</button>
<div class="card-content">${content}</div>
</div>
`);
@ -134,6 +138,7 @@ document.addEventListener('DOMContentLoaded', function() {
${extraAttributes}
data-id="${data.id}"
data-card-id="${cardId}"
data-name="${cardname}"
data-choice
data-rarity="${rarity}"
style="cursor: pointer;">
@ -175,7 +180,6 @@ document.addEventListener('DOMContentLoaded', function() {
choicesContainer.addEventListener('click', function(e) {
if (e.target.classList.contains('increment')) {
debugger;
console.log("Increment button clicked.");
e.preventDefault();
e.stopPropagation();
@ -188,10 +192,10 @@ document.addEventListener('DOMContentLoaded', function() {
quantity = quantity + 1;
quantityBadge.innerText = quantity;
updateOptionQuantity(container, quantity);
}
}
if (e.target.classList.contains('decrement')) {
debugger;
console.log("Decrement button clicked.");
e.preventDefault();
e.stopPropagation();
@ -201,14 +205,13 @@ document.addEventListener('DOMContentLoaded', function() {
let quantityBadge = container.querySelector('.card-quantity-badge');
let quantity = getOptionQuantity(container);
const cardId = container.getAttribute('data-card-id');
if (quantity == 1) {
if (quantity === 1) {
console.log("Decrement action: quantity is 1 for card", cardId, "initiating removal.");
const option = selectField.querySelector('option[value^="' + cardId + ':"]');
const option = selectField.querySelector('option[value="' + cardId + '"]');
if (option) {
console.log("Removing card from Choices.js instance. Value removed:", option.value);
choicesInstance.removeActiveItemsByValue(option.value);
option.selected = false;
option.value = cardId + ':1';
} else {
console.log("No active item found for card", cardId);
}
@ -233,29 +236,57 @@ document.addEventListener('DOMContentLoaded', function() {
// Update the option's value by rewriting the "card:qty" string.
function updateOptionQuantity(item, quantity) {
debugger;
const cardId = item.getAttribute('data-card-id');
console.log("Updating option quantity for card", cardId, "to", quantity);
const option = item.closest('.choices__inner').querySelector('option[value^="' + cardId + ':"]');
const option = item.closest('.choices__inner').querySelector('option[value="' + cardId + '"]');
if (option) {
option.value = cardId + ':' + quantity;
console.log("Updated option value for card", cardId, ":", option.value);
option.setAttribute('data-quantity', quantity);
console.log("Updated data-quantity for card", cardId, "to", quantity);
}
}
function getOptionQuantity(item) {
debugger;
const cardId = item.getAttribute('data-card-id');
const option = item.closest('.choices__inner').querySelector('option[value^="' + cardId + ':"]');
if (option) {
return parseInt(option.value.split(':')[1]);
}
const option = item.closest('.choices__inner').querySelector('option[value="' + cardId + '"]');
return option ? parseInt(option.getAttribute('data-quantity')) : 1;
}
// Initial global filters update on page load.
if (window.updateGlobalCardFilters) {
window.updateGlobalCardFilters();
}
// Attach the form submit event by locating the parent form of the select field.
const form = selectField.closest('form');
if (form) {
form.addEventListener('submit', function(e) {
// Remove any previously generated hidden inputs to avoid duplicates on resubmission.
const generatedInputs = form.querySelectorAll('input[data-generated-for-card-multiselect]');
generatedInputs.forEach(input => input.remove());
// Iterate over all selected options.
const selectedOptions = selectField.querySelectorAll('option:checked');
selectedOptions.forEach(function(option) {
const cardId = option.value; // The static card ID
const quantity = option.getAttribute('data-quantity') || '1';
// Create a hidden input that mimics the multi-select behavior.
const hiddenInput = document.createElement('input');
hiddenInput.type = 'hidden';
// Using the same name as the multi-select means the POST data will contain an array of values for `{{ field_name }}`.
hiddenInput.name = '{{ field_name }}';
hiddenInput.value = cardId + ':' + quantity;
// Mark this input as generated by our script.
hiddenInput.setAttribute('data-generated-for-card-multiselect', 'true');
form.appendChild(hiddenInput);
});
// Remove the name attribute from the actual select to prevent duplicate submission.
selectField.removeAttribute('name');
console.log("Form submission: generated hidden inputs for selected cards.");
});
}
});
</script>

View file

@ -46,7 +46,7 @@ class TradeOfferCreateView(LoginRequiredMixin, CreateView):
context = super().get_context_data(**kwargs)
from cards.models import Card
# Ensure available_cards is a proper QuerySet
context["available_cards"] = Card.objects.all().order_by("name", "rarity__pk") \
context["cards"] = Card.objects.all().order_by("name", "rarity__pk") \
.select_related("rarity", "cardset") \
.prefetch_related("decks")
friend_codes = self.request.user.friend_codes.all()
@ -335,7 +335,7 @@ class TradeOfferSearchView(LoginRequiredMixin, ListView):
context = super().get_context_data(**kwargs)
from cards.models import Card
# Populate available_cards to re-populate the multiselects.
context["available_cards"] = Card.objects.all().order_by("name", "rarity__pk") \
context["cards"] = Card.objects.all().order_by("name", "rarity__pk") \
.select_related("rarity", "cardset")
if self.request.method == "POST":
context["offered_cards"] = self.request.POST.getlist("offered_cards")