2013-10-28 36 views
2

是否可以做我想要的東西?爲表單構建器創建自定義選項添加方法

我知道如何創建一個表單字段:

public function buildForm(FormBuilderInterface $builder, array $options) 
{ 
    $builder 
     ->add('field', null, array_of_options) 
    ; 
} 

add method第三個參數是像predifined選項數組:labelattr,等等...如果你做這樣的事情:

$builder 
    ->add('field', null, array('my_option' => 'my value')); 

你會得到這樣的錯誤:

The option "my_option" does not exist. Known options are: "action", "attr", "auto_initialize", "block_name", "by_reference", "cascade_validation", "compound", "constraints", "csrf_field_name", "csrf_message", "csrf_protection", "csrf_provider", "data", "data_class", "disabled", "empty_data", "error_bubbling", "error_mapping", "extra_fields_message", "grouping", "inherit_data", "intention", "invalid_message", "invalid_message_parameters", "label", "label_attr", "mapped", "max_length", "method", "pattern", "post_max_size_message", "precision", "property_path", "read_only", "required", "rounding_mode", "translation_domain", "trim", "validation_groups", "virtual" 

我已閱讀並理解this但它不是我在找的東西。我不想通過控制器的createForm方法傳遞選項。

我想要的是爲add method中的第三個參數的數組創建自定義option

對不起,如果我不清楚!

回答

3

我已經解決了這個問題。

首先,回答@ hcoat的評論,我想有3 custom optionsopen_colclose_colcol_dims)爲form theming。我通過他們在attr選項:

public function buildForm(FormBuilderInterface $builder, array $options) 
{ 
    $builder 
     ->add('field1', null, array('attr' => array('open_col' => true, 'col_dims' => '2-8'))) 
     ->add('field2', null, array('attr' => array('close_col' => true, 'col_dims' => '6-8'))) 
    ; 
} 

和檢索的那些選項值如下:

{% block form_row %} 
{% spaceless %} 



{% set open_col, close_col = 'open_col', 'close_col' %} 
    {% if open_col in attr|keys %} 
    <div class="mws-form-row"> 
     <div class="mws-form-cols"> 
      <div class="mws-form-col-{{ (open_col in attr|keys) ? attr['col_dims']:'4-8' }}"> 
    {% elseif close_col in attr|keys %} 
      <div class="mws-form-col-{{ (open_col in attr|keys) ? attr['col_dims']:'4-8' }}"> 
    {% else %} 
    <div class="mws-form-row"> 
    {% endif %} 

     {{ form_label(form) }} 
     <div class="mws-form-item"> 
      {{ form_widget(form) }} 
     </div> 
    {% if close_col in attr|keys %} 
      </div> 
     </div> 
    </div> 
    {% elseif open_col in attr|keys %} 
    </div> 
    {% else %} 
    </div> 
    {% endif %} 
{% endspaceless %} 
{% endblock form_row %} 

它工作正常!

2

我認爲你的解決方案並不完美。當然,它的工作,但你應該考慮另一種解決方案。

您應該使用允許您添加自己的屬性的選項解析器。 http://symfony.com/doc/current/components/options_resolver.html

因此,在您formType類,你應該添加以下方法:

public function setDefaultOptions(OptionsResolverInterface $resolver) 
{ 
    $resolver->setDefaults(
     array(
      'my_option' => 'my_default_value', 
     ) 
    ); 
} 

然後你就可以在樹枝模板得到這個屬性爲:

{{ my_option }} //it return"my_defaul_value" 
    {{ form.your_field_name.my_option }} //it retun your field value