Я пытаюсь создать форму, которая будет добавлять новое текстовое поле каждый раз, когда будет нажата ссылка «Добавить новое поле». Я прочитал следующий пример. http://symfony.com/doc/current/reference/forms/types/collection.html
В основном я следовал примеру из книги. Но когда страница отображается и я нажимаю на ссылку, ничего не происходит. Какие-нибудь мысли? Спасибо.
Это мой контроллер.
public function createAction() {
$formBuilder = $this->createFormBuilder();
$formBuilder->add('emails', 'collection', array(
// each item in the array will be an "email" field
'type' => 'email',
'prototype' => true,
'allow_add' => true,
// these options are passed to each "email" type
'options' => array(
'required' => false,
'attr' => array('class' => 'email-box')
),
));
$form = $formBuilder->getForm();
return $this->render('AcmeRecordBundle:Form:create.html.twig', array(
'form' => $form->createView(),
));
}
Это точка зрения.
<form action="..." method="POST" {{ form_enctype(form) }}>
{# store the prototype on the data-prototype attribute #}
<ul id="email-fields-list" data-prototype="{{ form_widget(form.emails.get('prototype')) | e }}">
{% for emailField in form.emails %}
<li>
{{ form_errors(emailField) }}
{{ form_widget(emailField) }}
</li>
{% endfor %}
</ul>
<a href="#" id="add-another-email">Add another email</a>
</form>
<script type="text/javascript">
// keep track of how many email fields have been rendered
var emailCount = '{{ form.emails | length }}';
jQuery(document).ready(function() {
jQuery('#add-another-email').click(function() {
var emailList = jQuery('#email-fields-list');
// grab the prototype template
var newWidget = emailList.attr('data-prototype');
// replace the "$$name$$" used in the id and name of the prototype
// with a number that's unique to our emails
// end name attribute looks like name="contact[emails][2]"
newWidget = newWidget.replace(/\$\$name\$\$/g, emailCount);
emailCount++;
// create a new list element and add it to our list
var newLi = jQuery('<li></li>').html(newWidget);
newLi.appendTo(jQuery('#email-fields-list'));
return false;
});
})
</script>
data-prototype
не заполнялся или что-то подобное. Часть моей точки зрения состоит в том, чтобы сделать максимально общий вариант и никогда не использовать конкретный javascript (например, ваш пример#add-another-email
... Скажите, помог ли вам мой ответ. - person renoirb   schedule 20.06.2012