2017-02-13 4 views
0

У меня есть веб-приложение в Symfony. Когда у меня есть коллекция объектов (у пользователя много адресов), мне нужно реализовать метод JavaScript/jQuery, чтобы пользователь мог добавить количество адресов, которые у него есть (https://symfony.com/doc/current/form/form_collections.html).Symfony/JQuery Коллекция объектов

Проблема в том, что я хочу обернуть каждую метку и каждый тег ввода с определенным div, как <div class="col-lg-4 col-md-4 col-sm-4 col-xs-12"></div>, но после нескольких попыток я не могу этого сделать. Вы можете мне помочь ?

Мой код:

<div class="row"> 
    <div id="addressList" data-prototype="{{ form_widget(parent_form.addresses.vars.prototype)|e }}"> 

    </div> 
</div> 

{{ form_widget(parent_form.addresses.vars.prototype)|e }} в data-prototype="..." генерирует этот HTML:

<div id="AddChildStep1_child_addresses___name__"> 
    <div class="form-group"> 
     <label class="control-label required" for="AddChildStep1_child_addresses___name___street1">Street1</label> 
     <input type="text" id="AddChildStep1_child_addresses___name___street1" name="AddChildStep1[child][addresses][__name__][street1]" required="required" maxlength="100" pattern=".{5,}" class="form-control" /> 
    </div> 
    <div class="form-group"> 
     <label class="control-label" for="AddChildStep1_child_addresses___name___street2">Street2</label> 
     <input type="text" id="AddChildStep1_child_addresses___name___street2" name="AddChildStep1[child][addresses][__name__][street2]" maxlength="100" class="form-control" /> 
    </div> 
    <div class="form-group"> 
     <label class="control-label" for="AddChildStep1_child_addresses___name___number">Number</label> 
     <input type="number" id="AddChildStep1_child_addresses___name___number" name="AddChildStep1[child][addresses][__name__][number]" class="form-control" /> 
    </div> 
    <div class="form-group"> 
     <label class="control-label" for="AddChildStep1_child_addresses___name___box">Box</label> 
     <input type="number" id="AddChildStep1_child_addresses___name___box" name="AddChildStep1[child][addresses][__name__][box]" class="form-control" /> 
    </div> 
    <div class="form-group"> 
     <label class="control-label" for="AddChildStep1_child_addresses___name___locality">Locality</label> 
     <select id="AddChildStep1_child_addresses___name___locality" name="AddChildStep1[child][addresses][__name__][locality]" class="form-control"> 
      <option value=""></option> 
      <option value="1">1080 - Molenbeek-Saint-Jean - BELGIUM</option> 
      <option value="2">1060 - Saint-Gilles - BELGIUM</option> 
      <option value="3">1050 - Ixelles - BELGIUM</option> 
     </select> 
    </div> 
    <div class="form-group"> 
     <label class="control-label required" for="AddChildStep1_child_addresses___name___addressType">Address type</label> 
     <select id="AddChildStep1_child_addresses___name___addressType" name="AddChildStep1[child][addresses][__name__][addressType]" class="form-control"> 
      <option value="HOME">Home</option> 
      <option value="WORK">Work</option> 
      <option value="HOLIDAYS">Holidays</option> 
      <option value="OTHER">Other</option> 
     </select> 
    </div> 
</div> 

А потом документацию Symfony предлагают этот код, чтобы добавить адрес:

var collectionHolder; 

// Set up an "add address" link 

var addAddressLink = $('<a href="#" class="add_address_link">Add address</a>'); 
var newLinkP = $('<p class="centered"></p>').append(addAddressLink); 

function addAddressForm(collectionHolder, newLinkP){ 

    // Get the data prototype 
    var prototype = collectionHolder.data('prototype'); 

    // get the new index 
    var index = collectionHolder.data('index'); 

    // Replace '__name__' in the prototype's HTML 
    //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 new item 
    collectionHolder.data('index', index+1); 

    //Display the form in the page nan li, before the "add address" link 
    var newFormP = $('<div class="one-address"></div>').append(newForm); 
    newLinkP.before(newFormP) 
} 

jQuery(document).ready(function(){ 
    // Get the div that holds the collection of addresses 
    collectionHolder = $('div#addressList'); 

    // add the "add address" anchor 
    collectionHolder.append(newLinkP); 

    // Count the current form inputs 
    // use that as the new index when inserting a new item 
    collectionHolder.data('index', collectionHolder.find(':input').length); 
    addAddressLink.on('click', function(e) 
    { 
     // Prevent the link from creating a "#" on the URL 
     e.preventDefault(); 
     // add a new address form 
     addAddressForm(collectionHolder, newLinkP); 
    }) 
}); 

I хотел бы оберните каждый элемент метки и каждый элемент ввода (то есть в div.one-address) с <div class="col-lg-4 col-md-4 col-sm-6 col-xs-12></div>.

ответ

2

Вы всегда можете настроить рендеринг своей формы на любом уровне. Здесь вам нужно настроить его для конкретной ветки. Этот document является вашей ссылкой. Вы можете выбрать form_label и form_widget блоки для перезаписи в соответствии с вашими потребностями.

{% form_theme form _self %} 

{% block form_label %} 
    <div class="col-lg-4 col-md-4 col-sm-6 col-xs-12> 
     {{- parent() -}} 
    </div> 
{% endblock %} 

{% block form_widget %} 
    <div class="col-lg-4 col-md-4 col-sm-6 col-xs-12> 
     {{- parent() -}} 
    </div> 
{% endblock %} 

В коде выше form переменная форма в веточке.

Если вы хотите, чтобы поля вашей коллекции имели другую структуру, сохраните их в отдельной ветке и включите в основную ветку. Затем настройте только включенную веточку.

PS: Код не проверен.

Надеюсь, это поможет!

+0

Спасибо! Я сделал обычную 'form_row', и это упростило мою жизнь! –

Смежные вопросы