我正在尝试重现 Symfony 2 Cookbook Tutorial Add a new Tag
我使用的代码与教程中的代码完全相同,但 jQuery 包含有一些问题。
新的.html.twig:
<form action="..." method="POST" {{ form_enctype(form) }}>
{# render the task's only field: description #}
{{ form_row(form.description) }}
<h3>Tags</h3>
<ul class="tags" data-prototype="{{ form_widget(form.tags.vars.prototype)|e }}">
{# iterate over each existing tag and render its only field: name #}
{% for tag in form.tags %}
<li>{{ form_row(tag.name) }}</li>
{% endfor %}
</ul>
<a href="#" class="add_tag_link">Add a tag</a>
{{ form_rest(form) }}
{# ... #}
</form>
这就是我在 base.html.twig 中包含 jquery 的方式:
<script src="http://code.jquery.com/jquery.js"></script>
下一步:在页面的某处添加脚本标记,以便您可以开始编写一些 JavaScript。
所以我也将它复制粘贴到了 base.html.twig 中。
// Get the ul that holds the collection of tags
var collectionHolder = $('ul.tags');
// setup an "add a tag" link
var $addTagLink = $('<a href="#" class="add_tag_link">Add a tag</a>');
var $newLinkLi = $('<li></li>').append($addTagLink);
jQuery(document).ready(function () {
// 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);
}
最后我写了在列表之后添加一个标签。
但是当我单击添加标签链接时,不会出现新的标签输入字段。