如何将参数/变量/参数传递给symfony 2.4表单主题?

时间:2014-03-18 06:50:06

标签: symfony twig

我正在自定义表单主题并想知道是否有办法将变量传递给主题?

e.g。我自定义label_block并想要为所有labelfields添加一个类,而不是逐个执行。将变量传递给表单主题的方法是什么?

1 个答案:

答案 0 :(得分:1)

您可以通过formBuilder传递参数。

以下是传递给collection_widget

的参数autocompleteJsonWsUrl的示例

在thig视图中!

{% form_theme form 'AppBundle:Form:collection.html.twig' %}
{{ form(form) }}

在收集树枝视图中

{% block collection_widget %}
<script type="text/javascript">
    $(function() {
        var $autocompleteJsonWsUrl = "{{ attr['autocompleteJsonWsUrl'] }}";
        var $collectionHtmlId = "{{ form.vars.id }}";
        initialiseCollectionFieldProcessing($collectionHtmlId,$autocompleteJsonWsUrl);
    });
</script>
<div id="{{ form.vars.id }}" data-prototype="{{ form_widget(form.vars.prototype)|escape }}">
    <ul class="collection">
    {% for child in form %}
        <li>{{ form_row(child) }}</li>
    {% endfor %}
    </ul>
</div>
{% endblock %}
表单构建器中的

public function buildForm(FormBuilderInterface $builder, array $options){
$contributersAutocompleteJsonWsUrl = $options['contributersAutocompleteJsonWsUrl'];
$builder->add('contributers','collection',array(
            'label'                 => 'request.form.contributers', 
            'type'                  => 'userSelector',
            'allow_add'             => true,
            'allow_delete'          => true,
            'by_reference'          => false,
            'required'              => false,
            'error_bubbling'        => false,
            'attr'                  => array('autocompleteJsonWsUrl' => $contributersAutocompleteJsonWsUrl ),
            'options'               => array(
                'label' => false,
                'invalid_message' => 'request.contributer.404')));
$builder->add('save', 'submit', array('label' => 'request.form.add.submit'));
}

public function setDefaultOptions(OptionsResolverInterface $resolver){
    $defaults = array(
        'data_class'            => 'AppBundle\Entity\Request',
        'intention'             => 'request',
        'translation_domain'    => 'request',
        'contributersAutocompleteJsonWsUrl' => ''
    );
    $resolver->setDefaults($defaults);
}

在控制器中:

$form = $this->createForm(new $formName,$object, array('contributersAutocompleteJsonWsUrl' => $contributersAutocompleteJsonWsUrl));