简体   繁体   中英

How to fix these form theming problems in Symfony2?

I have multiple questions about forms

First question, how to wrap an input with a div (with classes) in the form builder?

So I want to wrap this submit input :

->add('Submit', 'submit', array(
    'attr' =>  array(
        'class' => 'btn btn-success'
    ),
))

To get this result :

<div class="col-sm-offset-2 col-sm-10">
    <input type="submit" class="btn btn-success"/>
</div>

Second question, how to set a template to a form via the form builder?

Is there a method for this like in my wrong example? Or not?

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->setTemplate('::vertical-form.html.twig')
        ->add(...)
}

Last question, how to add a class to the form element in a custom form template?

I grab this piece of code from form_div_layout.html.twig and I add the class (9th line) to the form element. But it doesn't work, I can't see the element in my view!

{% block form_start %}
    {% spaceless %}
        {% set method = method|upper %}
        {% if method in ["GET", "POST"] %}
            {% set form_method = method %}
        {% else %}
            {% set form_method = "POST" %}
        {% endif %}
        <form class="form-horizontal" role="form" name="{{ form.vars.name }}" method="{{ form_method|lower }}" action="{{ action }}"{% for attrname, attrvalue in attr %} {{ attrname }}="{{ attrvalue }}"{% endfor %}{% if multipart %} enctype="multipart/form-data"{% endif %}>
        {% if form_method != method %}
            <input type="hidden" name="_method" value="{{ method }}" />
        {% endif %}
    {% endspaceless %}
{% endblock form_start %}

In my views, I've only that piece of code to render the form:

{% form_theme form '::custom-form.html.twig' %}
{{ form(form_name) }}

Maybe should I copy all form_div_layout.html.twig file to another template and tweak what I need?

Thanks in advance for your help!

  1. In my opinion in this case You should create submit button manually in a template (not by form class)

  2. I don't know solution which looks like this.

  3. You should copy all file content. Read this: http://symfony.com/doc/current/cookbook/form/form_customization.html

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