Reputation: 5
I have a contact form and I'm trying to put a class to an input of my form.
This is in the ContactType:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', TextType::class);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Contact::class,
]);
}
And this in my twig:
{{ form_start(form) }}
{{ form_widget(form.name, {attr: {class: 'myclass', placeholder: 'name'} }) }}
{{ form_end(form) }}
I get this html:
<input type="text" class="form-control" id="contact_name" name="contact[name]" required="required" placeholder="name">
It's working for placeholder, but not to class. I have tried to put the attr in the builder and it is the same. Is the class form-control
overwriting my class? How can I fix it?
Upvotes: 1
Views: 115
Reputation: 155
You can read it from the official page: https://symfony.com/doc/current/reference/forms/types/form.html#attr
Just add: {'attr': {'attribute name': 'value'}}
As shown below
{{ form_widget(form.propertyName, {'attr': {'placeholder': 'name'} }) }}
Upvotes: 1
Reputation: 659
I think you're using a bootstrap form theme, check into the config file.
and if the case, you can add this line on the top of your twig file :
{% form_theme form 'form_div_layout.html.twig' %}
Upvotes: 2
Reputation: 4379
I believe you can't define two attributes on form_wdiget
. The way around this is doing both in the FormBuilder or one in the FormBuilder.
You can define attributes on a form element like so:
$builder
->add('name', TextType::class, [
'attr' => [
'class' => 'my-class',
],
]);
Note that for a CSS class, it must be in the array attr
, not to be confused with a class as in your entity like on the EntityType::class
.
Or
$builder
->add('name', TextType::class, [
'placeholder' => 'My place holder',
]);
So you could achieve both like:
$builder
->add('name', TextType::class, [
'attr' => [
'class' => 'my-class',
],
'placeholder' => 'My place holder',
]);
You can read more about form field attributes here.
Upvotes: 1
Reputation: 202
Try this if it will help you
{{ form_start(form) }}
{{ form_widget(form.name, {'attr': {'class': 'input-text input-text--white', 'placeholder': 'name'} }) }}
{{ form_end(form) }}
Upvotes: 1