Fix default handling
This commit is contained in:
@@ -6,11 +6,13 @@ export default class extends Controller {
|
||||
static targets = [ "label", "item", "hiddenFieldTemplate" ]
|
||||
static values = {
|
||||
selectPropertyName: { type: String, default: "aria-checked" },
|
||||
defaultValue: String
|
||||
defaultValue: String,
|
||||
defaultLabel: String
|
||||
}
|
||||
static classes = ["withDefault"]
|
||||
|
||||
connect() {
|
||||
this.labelTarget.textContent = this.#selectedLabel
|
||||
this.#selectedItem = this.#selectedItem
|
||||
}
|
||||
|
||||
change(event) {
|
||||
@@ -21,6 +23,14 @@ export default class extends Controller {
|
||||
}
|
||||
|
||||
get #selectedLabel() {
|
||||
const selectedValue = this.#selectedItemValue()
|
||||
console.debug("Es ", this.defaultValueValue);
|
||||
if (this.hasDefaultLabelValue && (selectedValue === this.defaultValueValue || !selectedValue)) {
|
||||
return this.defaultLabelValue
|
||||
}
|
||||
|
||||
console.debug("EIN", this.#selectedItem);
|
||||
|
||||
return this.#selectedItem?.dataset?.comboboxLabel || ""
|
||||
}
|
||||
|
||||
@@ -28,11 +38,18 @@ export default class extends Controller {
|
||||
return this.itemTargets.find(item => item.getAttribute(this.selectPropertyNameValue) === "true")
|
||||
}
|
||||
|
||||
#selectedItemValue() {
|
||||
return this.#selectedItem?.dataset?.comboboxValue || ""
|
||||
}
|
||||
|
||||
set #selectedItem(item) {
|
||||
if (!item) return
|
||||
|
||||
this.#clearSelection()
|
||||
item.setAttribute(this.selectPropertyNameValue, "true")
|
||||
this.labelTarget.textContent = this.#selectedLabel
|
||||
this.hiddenField.value = item.dataset.comboboxValue
|
||||
this.#updateWithDefaultClass()
|
||||
}
|
||||
|
||||
#clearSelection() {
|
||||
@@ -53,4 +70,17 @@ export default class extends Controller {
|
||||
this.element.appendChild(field)
|
||||
return field
|
||||
}
|
||||
|
||||
#updateWithDefaultClass() {
|
||||
if (this.hasWithDefaultClass && this.hasDefaultValueValue) {
|
||||
const selectedValue = this.#selectedItemValue()
|
||||
const shouldHaveClass = selectedValue === this.defaultValueValue
|
||||
|
||||
if (shouldHaveClass) {
|
||||
this.element.classList.add(this.withDefaultClass)
|
||||
} else {
|
||||
this.element.classList.remove(this.withDefaultClass)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user