[英]How can I wrap my input field with a <div> tag when using with Symfony formbuilder?
I am creating an input field with Symfony: 我正在用Symfony创建一个输入字段:
$formBuilder->add($field['fieldName'], TextType::class, array('attr' => array('class' => 'form-control')));
The output is: 输出为:
<input type="text" id="form_color" name="form[color]" class="form-control">
The output I would need is: 我需要的输出是:
<div class="cp input-group colorpicker-component">
<input type="text" id="form_color" name="form[color]" class="form-control" /> <span class="input-group-addon"><i></i></span>
</div>
This means I somehow have to add a parent to the specific form field. 这意味着我必须以某种方式将父项添加到特定的表单字段。 I cannot add it to the actual form, because this parent div is only added to the field in specific cases.
我无法将其添加到实际表单中,因为此父div仅在特定情况下才添加到字段中。 Is there a way to do it in the formbuilder?
有没有办法在formbuilder中做到这一点?
I'd create my own custom field type to handle these fields. 我将创建自己的自定义字段类型来处理这些字段。
First define the field class 首先定义字段类
// src/Form/Type/ColorSelectorType.php
namespace App\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
class ColorSelectorType extends AbstractType
{
public function getParent()
{
return TextType::class;
}
}
Then you'll need to create the template for the field: 然后,您需要为该字段创建模板:
{# templates/form/fields.html.twig #}
{% block color_selector_widget %}
{% spaceless %}
<div class="cp input-group colorpicker-component">
<input{{ block('widget_container_attributes') }} />
<span class="input-group-addon"><i></i></span>
</div>
{% endspaceless %}
{% endblock %}
Register your custom templates: 注册您的自定义模板:
# config/packages/twig.yaml
twig:
form_themes:
- 'form/fields.html.twig'
And finally use your new field: 最后使用您的新字段:
$formBuilder->add($field['fieldName'], ColorSelectorType::class);
Logically, you'll need to customize this to suit your needs, but it should be enough to get you going. 从逻辑上讲,您需要自定义此选项以适合您的需求,但这足以使您前进。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.