Transform auto-generated CollectionType of Symfony into given HTML template
Just download and import the js file into your project, and don't forget to import the jQuery
library.
- Add "data-name" attribute to your FormType
$builder
->add('firstField', TextType::class, array(
'attr' => array(
'data-name' => 'first'//---give this attribute any name you want
)
))
->add('secondField', TextType::class, array(
'attr' => array(
'data-name' => 'second'
)
))
->add('thirdField', TextType::class, array(
'attr' => array(
'data-name' => 'third'
)
))
;
- Prepare your HTML template (for me I used a javascript function) and put your "data-name" target between two
#
so thatSFCollectionAnalyzer
will know where to put each field:
function myTemplate() {
return `<div>
<table>
<tr>
<td>First field:</td><td>#first#</td>
<tr>
<tr>
<td>Second field:</td><td>#second#</td>
<tr>
<tr>
<td>Third field:</td><td>#third#</td>
<tr>
</table>
</div><hr>`;
}
- Now you just need to give
SFCollectionAnalyzer
the "data-prototype" generated by Symfony and your HTML template, and he will take care of the rest:
// declare a counter variabel
// in case of update you can counter the dom children ex: var _counter = $('#collection-div').children().length;
var _counter = 0;
$('#btnAdd').on('click', function (){
// you just need to pass the dom that contains the data-prototype attribute along with your template function
var temp = SFCollectionAnalyzer.buildTemplate($('#collection-div'), myTemplate());
var block = temp.replace(/__name__/g, _counter);//--temp is still using "__name__" so you just need to replace it with the counter
$('#div-where-to-insert-collection').append(block);
_counter++;
});