Aerendir Aerendir - 1 year ago 172
PHP Question

How to use setAttribute on Symfony Form field

I'm trying to add a

attribute to a field generated with

This is the code I'm using:

$form = $this->formFactory->createBuilder(FormType::class, [
'action' => $this->router->generate('storeSubscription', ['id' => $store->getId()]),
'method' => 'POST',
->add('plan', PremiumType::class, [
'data_class' => PremiumFeaturesEmbeddable::class,
'data' => $store->getPremium(),

if (null === $store->getBranchOf()->getStripeCustomer() || null === $store->getBranchOf()->getStripeCustomer()->getDefaultSource()) {
$form->add('credit_card', CreditCardStripeTokenType::class)
->add('company_data', CompanyType::class, [
'data_class' => Company::class,
'data' => $store->getBranchOf()

// Remove unused data

// Set data-stripe
->get('legalName')->setAttributes(['attr' => ['data-stripe', 'name']]);

As you can see, the last line of this code gets the first the
form type, then of this gets the field
: on this I want to set the attribute

But this code doesn't work.

To add the attribute I have to use
in Twig:

<div class="form-group">
{{ form_errors(form.company_data.legalName) }}
{{ form_label(form.company_data.legalName) }}
{{ form_widget(form.company_data.legalName, {'attr': {'class': 'form-control input-sm', 'data-stripe': 'name'}}) }}

This way it works and attribute is correctly added.
For sure, I may continue setting those attributes in Twig, but I'd like to add them in PHP but don't understand why it doesn't work. Is someone able to explain me how to solve the problem? Thank you!

What I tried

Test 1

// Set data-stripe
->get('legalName')->setAttributes(['data-stripe', 'name']);

Test 2

// Set data-stripe
->get('legalName')->setAttribute('data-stripe', 'name');

Test 3

// Set data-stripe
->get('legalName')->setAttributes(['attr' => ['data-stripe', 'name']]);

No one of those work. I don't know what to try more.

NOTE: I've opened an issue on GitHub too.

Answer Source

If you need add/modify any option from any existing field, just do the following:

// to keep the current options
$options = $form->get('company_data')->get('legalName')->getConfig()->getOptions();

// add/change the options here
$options['attr']['data-stripe'] = 'name';

// re-define the field options
$form->get('company_data')->add('legalName', TextType::class, $options);

This doesn't alter the order of the fields, only change their options. Useful for conditional options on buildForm() and listener/suscriber events.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download