I have an entity BaseEntity which has an OneToMany relationship to entity EventEntity. So one BaseEntity can have multiple EventEntities.
There is a form (BaseEntityType) which adds the embedded form for the EventEntity via:
->add('events', 'collection', array('label' => false, 'type' => new EventEntityType(),'allow_add' => true))
The class EventEntityType looks like this:
$builder
->add('type', 'choice', array("choices" => EventEntity::getReadableTypes()))
->add('date', "date", array("label" => "Date"))
->add('note', "textarea", array("label" => "Note"));
With a little bit Javascript I adapted from symfony documentation
var $collectionHolder;
// setup an "add a tag" link
var $addTagLink = $('<a href="#" class="add_tag_link">Add an event</a>');
var $newLinkLi = $('<li></li>').append($addTagLink);
$(document).ready(function() {
// Get the ul that holds the collection of tags
$collectionHolder = $('#events');
// add the "add a tag" anchor and li to the tags ul
$collectionHolder.append($newLinkLi);
// count the current form inputs we have (e.g. 2), use that as the new
// index when inserting a new item (e.g. 2)
$collectionHolder.data('index', $collectionHolder.find(':input').length);
$addTagLink.on('click', function(e) {
// prevent the link from creating a "#" on the URL
e.preventDefault();
// add a new tag form (see next code block)
addTagForm($collectionHolder, $newLinkLi);
});
});
function addTagForm($collectionHolder, $newLinkLi) {
// Get the data-prototype explained earlier
var prototype = $collectionHolder.data('prototype');
// get the new index
var index = $collectionHolder.data('index');
// Replace '__name__' in the prototype's HTML to
// instead be a number based on how many items we have
var newForm = prototype.replace(/__name__/g, index);
// increase the index with one for the next item
$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);
}
I'm able to render the form and add multiple embedded forms for the events which looks like this:
Each time I click add event one event form will be added:
The thing is: I would like the existing events to be rendered in a different way (like in a simple <ul> tag, a ListBox like EventName (Date) or in a table) and only have one form for adding new events. So there should only be one form for adding events and each time I klick "add event" the event is added to the ListBox and I can add a new event. Like this:
Do I need different FormTypes for displaying and creating? How would the implementation look like?
I hope my question is clear, please feel free to ask if not. I really wasn't able to find an example / best practice for this use case... Thank you very much!
Aucun commentaire:
Enregistrer un commentaire