简体   繁体   中英

Symfony2 form theming for individual field

I am building forms using Symfony2 form builder and using bootstrap_3_horizontal_layout.html.twig theme (it is the default for all my forms), but I need to customize the layout for a specific field content_owner . It is a multiple select , so I am using the code below to override the default template:

{% block choice_widget_collapsed %}
<div class="col-md-4"><div class="form-group">{{- block('form_widget_compound') -}}</div> </div>
{% endblock %}

and in new.html.twig (where the form renders):

{% for name, child in form.content if name != 'graphics' %}
                        {{ form_row(child) }}
                    {% endfor %}
{{ form_widget(form.content.content_owner) }}

The output I am getting (in firebug):

<div class="form-group">
<label for="form_content_content_owner" class="col-sm-2 control-label">Content owner</label>
   <div class="col-sm-10">
    <div class="col-md-4"> 
       <div class="form-group">
            <div id="form_content_content_owner">

             <!--and it is blank. no choice widget--> 
             </div>
                </div>
                   </div>
                      </div>
                          </div>

The code breaks all of my choice widgets ,that is,no select is visible. What am I doing wrong?

Desired output:

  <div class="col-sm-4">
   <div class="form-group">
      <label for="form_content_content_owner" class="col-sm-2 control-label">Content owner</label>
         <div class="col-sm-10">
           <select class="form-control" name="form[content][content_owner]" id="form_content_content_owner">
             <option value=""></option>
             <option value="1">Anupam</option>
               <!--option value goes on-->
             <option value="31">World Com</option>
           </select>
       </div>
    </div>
  </div>

I think you will find that the choice_widget_collapsed block is rendered inside a form_widget_compound block, so you've set up an infinite loop.

Try adding a debugger breakpoint into Symfony\\Component\\Form\\FormRenderer.php at around line 250 just after where this code is:

$blockName = $blockNameHierarchy[$hierarchyLevel];

The look at what value $blockName takes during each iteration. Once you get to the field you are trying to render you should see which blocks are being called and in which order. This might help you understand what's happening in your templates a little better.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM