2012-08-29 35 views
2

我實現了在形式的幫助信息作爲documentation如何通過FormBuilder的領域

{% extends 'form_div_layout.html.twig' %} 

{% block field_widget %} 
    {{ parent() }} 
    {% if help is defined %} 
     <span class="help">{{ help }}</span> 
    {% endif %} 
{% endblock %} 

要渲染的幫助部分傳遞樹枝參數的例子說,「幫助」應在樹枝被定義文件,如:

{{ form_widget(form.title, {'help': 'foobar'}) }} 

不過,我想定義「幫助」爲在表單生成器領域中的一個選項,如:

class myClassType extends AbstractType 
{ 
    public function buildForm(FormBuilder $builder, array $options) 
    { 
     $builder 
      ->add('title',null,array('help'=>'foobar')); 
    } 
} 

這沒有結果(「選項」幫助「不存在」)。我也試過

$builder 
    ->add('title',null,array('attr'=>array(help'=>'foobar'))); 

而且它也不起作用。

任何想法得到這樣的工作?

回答

4

使用

$builder 
->add('title',null,array('attr'=>array('help'=>'foobar'))); 

然後

{% if attr['help'] is defined %} 
    <span class="help">{{ attr['help'] }}</span> 
{% endif %} 
+0

謝謝!這正是我所期待的。 – Galle

+1

一個小缺點是輸入字段也會有'help ='foobar''設置,它是多餘的恕我直言。 –

+0

謝謝我正在尋找一種方法將自定義參數傳遞給一個自定義的「'''block'''。正如你在這裏所建議的那樣,我是通過'''attr ['help']'''完成的。 http://stackoverflow.com/questions/17533159/defining-custom-twig-form-b​​lock-for-errors-rendering – svassr

0

我的猜測是,你無法做到這一點的原因是表單字段幫助文本主要是視圖/模板關注。我意識到這並不完全回答你的問題。

2

您可以利用finishView方法AbstractType最終實現FormTypeInterface。 e.g,

// Vendor/YourBundle/Form/Type/YourFormType 

namespace Vendor\YourBundle\Form\Type; 

// other use definitions 
use Symfony\Component\Form\FormInterface; 
use Symfony\Component\Form\FormView; 
use Symfony\Component\Form\AbstractType; 

class YourFormType extends AbstractType 
{ 
    // other methods.... 

    /** 
    * {@inheritdoc} 
    */ 
    public function finishView(FormView $view, FormInterface $form, array $options) 
    { 
     parent::finishView($view, $form, $options); 
     $view['title']->vars['help'] = "Title help message"; 
     // same for other fields 
    } 
}