2011-09-20 92 views
22

我試圖在symfony2中的每個表單中的字段後添加一些幫助消息。將「幫助」消息添加到字段

我已閱讀官方文檔來解決問題:http://symfony.com/doc/current/cookbook/form/form_customization.html#adding-help-messages

但是這種解決方案變得毫無意義,因爲我們需要手動創建的所有形式。例如,很容易定義標籤:$formBuilder->add('myfieldname', 'text', array('label'=>'some my field label'));但是如何傳遞幫助信息? (換句話說,一些自定義變量)

回答

12

$formBuilder->add('myFieldName', 'text', array('help' => 'My Help Message'));但它認爲你還需要添加添加爲所有形式的默認選項的擴展:
https://github.com/simplethings/SimpleThingsFormExtraBundle#helpextension
這使得你可以直接從您編輯屬性FormTypes。

+2

這束重構和鏈接不活像k更多。現在轉到這裏:https://github.com/simplethings/SimpleThingsFormExtraBundle#helpextension – jmlnik

1

有點偏離主題,但如果您打算爲您的項目使用Bootstrap仍然有用,那麼您可以利用Mopa Bootstrap Bundle提供的某些表單助手。

演示:http://bootstrap.mohrenweiserpartner.de/mopa/bootstrap/forms/help_texts

GitHub上:https://github.com/phiamo/MopaBootstrapBundle

例子:

<?php 

$form = $this->get('form.factory') 
     ->createNamedBuilder('form_name') 
     ->setMethod('POST') 
     ->add('testSelect', 'choice', [ 
      'choices' => ['val1' => 'Value 1', 'val2' => 'Value 2'], 
      'required' => true, 
      'help_block' => 'Here some help text!!!' 
     ]) 
     ->add('Save', 'submit') 
     ->getForm(); 

return $form->createView(); 
3

像你描述你可以使用該解決方案在官方文檔。

但是,工作尚未完成。你必須創建一個表型的擴展,基於這篇文章:http://symfony.com/doc/current/cookbook/form/create_form_type_extension.html

後填寫表格型的擴展創作,你可以添加幫助信息是這樣的:

$form = $this->createFormBuilder() 
      ->add('name', 'text', array(
       'help' => 'this is a help message to user', 
     )) 

我認爲這是一個天然的更好的解決方案。 另外,我建議閱讀這篇大文章將告訴您如何啓用和設置在Symfony2的形式幫助選項: http://toni.uebernickel.info/2012/11/03/how-to-extend-form-fields-in-symfony2.1.html

+0

我確定答案在鏈接中,但您能否從文檔和文章中概述解決方案? – Trudbert

20

一個沒有另一部分的另一種方法:

在你的表單生成器類:

$builder->add('yourField',null, array('attr'=>array('help'=>'text help'))) 

在您的表單模板重寫:

{% block form_row %} 
    {% spaceless %} 
      {{ form_label(form) }} 
       {{ form_widget(form) }} 
       {% for attrname, attrvalue in attr %} 
        {% if attrname == 'help' %} 
         <span class="help-block">{{ attrvalue }}</span> 
        {% endif %} 
       {% endfor %} 
      {{ form_errors(form) }} 
    {% endspaceless %} 
{% endblock form_row %} 
+2

該解決方案將添加屬性「幫助」到輸入字段,因此它不理想。它會創建無效的html。 – pulzarraider

+1

@pulzarraider是對的。改爲使用'data-help'屬性。 –