我一直在尝试在我的Symfony 2表单中使用thr vollevtion字段类型,但它不起作用。我前段时间已经问了同样的问题,但我没有得到我想要的答案。我再次reed文档(http://symfony.com/doc/current/reference/forms/types/collection.html),但我仍然遇到同样的问题。
我已经在我的其他帖子中解释了所有内容,所以这里是:
How to integrate multiple entity in form in Symfony 2
请有人帮助我!
答案 0 :(得分:0)
希望这可以帮助你
<强> ParentType的:强>
->add('funding', 'collection', array(
'type' => new FundingType(),
'allow_add' => true,
'by_reference' => false,
'allow_delete' => true))
<强> ChildType:强>
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('type', 'text', array(
'label' => 'Funding'));
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Bundle\Entity\Funding',
));
}
<强>控制器:强>
$funding = new Funding();
$project->getFunding()->add($funding);
<强>枝条强>
<div class="funding" data-prototype="{{ form_widget(form.funding.vars.prototype)|e}}">
{% for funding in form.funding %}
{{ form_row(funding.type) }}
{% endfor %}
</div>
<script>
// Funding
// setup an "add a tag" link
var $addFundingLink = $('<a href="#" class="add_funding_link">Add Funding type</a>');
var $newLinkLi1 = $('<p></p>').append($addFundingLink);
jQuery(document).ready(function() {
// Get the ul that holds the collection of tags
var $collectionHolder1 = $('div.funding');
// add the "add a tag" anchor and li to the tags ul
$collectionHolder1.append($newLinkLi1);
// count the current form inputs we have (e.g. 2), use that as the new
// index when inserting a new item (e.g. 2)
$collectionHolder1.data('index1', $collectionHolder1.find(':input').length);
$addFundingLink.on('click', function(e) {
// prevent the link from creating a "#" on the URL
e.preventDefault();
// add a new tag form (see code block below)
addFundingForm($collectionHolder1, $newLinkLi1);
});
});
function addFundingForm($collectionHolder1, $newLinkLi1) {
// Get the data-prototype explained earlier
var prototype = $collectionHolder1.data('prototype');
// get the new index
var index1 = $collectionHolder1.data('index1');
// Replace '$$name$$' in the prototype's HTML to
// instead be a number based on how many items we have
var newForm1 = prototype.replace(/__name__/g, index1);
// increase the index with one for the next item
$collectionHolder1.data('index1', index1 + 1);
// Display the form in the page in an li, before the "Add a tag" link li
var $newFormLi1 = $('<p></p>').append(newForm1);
// also add a remove button, just for this example
$newFormLi1.append('<a href="#" class="remove-funding">Delete</a>');
$newLinkLi1.before($newFormLi1);
// handle the removal, just for this example
$('.remove-funding').click(function(e) {
e.preventDefault();
$(this).parent().remove();
return false;
});
}
</script>