我正在使用 symfony 2.8,我创建了一份注册表单,我想将引导表单控制类添加到密码和重复密码表单字段。
$builder
->add('name', TextType::class,array(
'attr' => array(
'class' => 'form-control'
)
))
-> add('plainPassword', RepeatedType::class, array(
'type' => PasswordType::class,
'first_options' => array('label' => 'Password'),
'second_options' => array('label' => 'Repeat Password'),
'attr' => array('class' => 'form-control')
));
如果“名称”字段有效,但对于密码字段,该类不会添加。 如何为密码字段添加“表单控制”类。 任何帮助深表感谢。 谢谢。
options
,它将选项向下传递到每个基础字段:
->add('plainPassword', RepeatedType::class, array(
'type' => PasswordType::class,
'first_options' => array('label' => 'Password'),
'second_options' => array('label' => 'Repeat Password'),
'options' => array('attr' => array('class' => 'form-control'))
));
first_options
和 second_options
字段中添加类,如下所示。如果您有特定于每个字段的选项或者您想要覆盖主选项中的某些内容,这将很有用。
->add('plainPassword', RepeatedType::class, array(
'type' => PasswordType::class,
'first_options' => array(
'label' => 'Password',
'attr' => array('class' => 'form-control')
),
'second_options' => array(
'label' => 'Password',
'attr' => array('class' => 'form-control-override')
),
'attr' => array('class' => 'form-control')
));
此外,从 Symfony 2.6 开始,它具有 内置 Bootstrap 表单主题支持,您不必手动将这些类添加到所有字段。
Symfony 开发团队的一些人建议您应该直接在 html 中使用 boostrap 的类(这里,如果您想查看建议)。这个建议对我来说非常有意义,因为 Symfony 是用于后端开发的,而不是前端。因此,解决此问题的理想方法是在
Type
类中创建两个字段,并在渲染表单时添加以下内容:
{{ form_row(name, { attr: { 'class': 'form-control' } ) }}
{{ form_row(password, { attr: { 'class': 'form-control' } ) }}
{{ form_row(plainPassword, { attr: { 'class': 'form-control' } ) }}
自 Symfony 2.x 起,您可以使用内置表单主题作为 twig 模板。
对于 4.x 及更高版本,只需在 config/packages/twig.yml
文件中添加
可用主题之一,如下所示:
twig:
/* ... */
form_themes: ['bootstrap_5_layout.html.twig']
/* ... */