可以做我想做的事吗?
我知道如何创建表单字段:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('field', null, array_of_options)
;
}
add 方法的第三个参数是一组预定义选项,例如:label
、attr
等...如果您这样做像这样的东西:
$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但这不是我要找的。我不想从 Controller 传递 createForm
方法中的选项。
我想要的是为add方法
中第三个参数的数组创建一个自定义选项
。
抱歉,如果我不清楚!
最佳答案
我已经解决了这个问题。
首先,为了回答@hcoat的评论,我想要3个自定义选项
(open_col
,close_col
,col_dims
)用于表单主题
。我在 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 %}
效果很好!
关于symfony - 为表单生成器添加方法创建自定义选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19626053/