Skip to content

Instantly share code, notes, and snippets.

@sstok
Forked from bjo3rnf/example_form.html.twig
Created May 2, 2021 13:57
Show Gist options
  • Save sstok/ccd2a7d4e1bbd3f1ba2af783396b492e to your computer and use it in GitHub Desktop.
Save sstok/ccd2a7d4e1bbd3f1ba2af783396b492e to your computer and use it in GitHub Desktop.
Stimulus.js controller for Symfony collection form type with configurable item limit
{% macro collection_item(form) %}
<div data-form-collection-target="field">
{{ form_widget(form) }}
<button data-action="form-collection#removeItem">
remove
</button>
</div>
{% endmacro %}
{% import _self as formMacros %}
{{ form_start(form) }}
<div data-controller="form-collection"
data-form-collection-max-items-value="10"
data-form-collection-prototype-value="{{ formMacros.collection_item(form.collectionField.vars.prototype)|json_encode }}">
<div data-form-collection-target="fields">
{% do form.collectionField.setRendered %}
{% for field in form.collectionField %}
{{ formMacros.collection_item(field) }}
{% endfor %}
</div>
<button data-action="form-collection#addItem">
add
</button>
</div>
{{ form_rest(form) }}
{{ form_end(form) }}
import { Controller } from 'stimulus'
export default class extends Controller {
static targets = [ 'fields', 'field', 'addButton' ]
static values = {
prototype: String,
maxItems: Number,
itemsCount: Number,
}
connect () {
this.index = this.itemsCountValue = this.fieldTargets.length
}
addItem(event) {
event.preventDefault()
let prototype = JSON.parse(this.prototypeValue)
const newField = prototype.replace(/__name__/g, this.index)
this.fieldsTarget.insertAdjacentHTML('beforeend', newField)
this.index++
this.itemsCountValue++
}
removeItem(event) {
event.preventDefault()
this.fieldTargets.forEach(element => {
if (element.contains(event.target)) {
element.remove()
this.itemsCountValue--
}
})
}
itemsCountValueChanged() {
if (false === this.hasAddButtonTarget || 0 === this.maxItemsValue) {
return
}
const maxItemsReached = this.itemsCountValue >= this.maxItemsValue
this.addButtonTarget.classList.toggle('hidden', maxItemsReached)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment