I created a Symfony Poll-Bundle which has the Entitys Campaign->Block->Line->Field->PollResult. So i have a CollectionType CampaignType which consists of many blocks. One block consist of many Lines. One Line consist of many Fields. (One Line is for example the line for fever and the fields are for intensity, and the period from and due the fever occured) And every Field has one PollResult which holds the Answer of the user who filled out the campaign.
Now i want to make the user to be able to add new Fields to a line to enter a second fever period for example. So i need a 'Add a Line'-Button for every Line that duplicates this line.
I used this documentation to do that.
First i added 'allow_add' => true
to my LineType FormBuilder:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('userAddFlag');
$builder->add('fields', CollectionType::class, array(
'entry_type' => FieldType::class,
'entry_options' => array('label' => false),
'allow_add' => true,
));
}
Then i added this to my view with the data-prototype:
<ul class="fields" data-prototype=" {{ form_widget(line.fields.vars.prototype)|e('html_attr') }} ">
<li>
{% for field in line.fields %}
<div>
{% for pollResult in field.pollResults %}
<div class="formLabelDiv">{{ field.vars.value.getTranslationName(app.request.getLocale()) }}</div>
<div class="formWidgetDiv">{{ form_widget(pollResult) }}</div>
{% endfor %}
</div>
{% endfor %}
</li>
</ul>
And last i added this jQuery code:
<script>
var $collectionHolder;
//setup an "add a Line" Link
var $addLineButton = $('<button type="button" class="add_line_link">Add a Line</button>');
var $newLinkLi = $('<li></li>').append($addLineButton);
jQuery(document).ready(function (){
//Get the ul that holds the collection of fields
$collectionHolder = $('ul.fields');
//add the "add a line" anchor and li to the tags ul
$collectionHolder.append($newLinkLi);
//count the current form inputs we have, use that as the new index when inserting a new item
$collectionHolder.data('index', $collectionHolder.find(':input').length);
$addLineButton.on('click', function (e){
addFieldsForm($collectionHolder, $newLinkLi);
})
})
function addFieldsForm($collectionHolder, $newLinkLi){
//get the data-prototyp
var prototype = $collectionHolder.data('prototype');
//get the new index
var index = $collectionHolder.data('index');
var newForm = prototype;
$collectionHolder.data('index', index+1);
// Display the form in the page in an li, before the "Add a tag" link li
var $newFormLi = $('<li></li>').append(newForm);
$newLinkLi.before($newFormLi);
}
</script>
So now the 'Add a Line'-Button appears on the page, but it doesn't add anything.. How can i add a new field and how am i able to duplicate the whole line and not only add one Field to the added line (I want to have the three fields intensity(dropdown), from and due(both textfield with datepicker))
Try adding
'by_reference' => false,
to the LineType.php