Search code examples
phpformssymfonysymfony-formsradiobuttonlist

Symfony 3 radio input name change


I have a form which has a form (CustomerVatsType) for an entity (CustomerVats). This entity has a column (vats), which contains multiple vat rows. These rows are saved in json format. On this form, customer can choose a default vat, which will be saved in "default" index of rows saved in units column.

but problem is that radio input name is "form[vats][0][set_default]" due to structure of form. But for radio input to work correctly it needs to be same for all inputs (e.g. form[vats][set_default]). I can change name in twig file but then form class can not understand this.

What can be done for this situation. Does even Symfony support it. Here is my form class.

class VatsType extends AbstractType {
    public function buildForm(FormBuilderInterface $builder, array $options) {
        $builder
        ->add('vats', CollectionType::class, array(
                'entry_type'   => VatType::class,
                'allow_add'    => false,
                'allow_delete' => false,
                'prototype'    => false,
                'by_reference' => false,
            )
        )
        ->add('vatSumbit', SubmitType::class);
    }
}


class VatType extends AbstractType {
    public function buildForm(FormBuilderInterface $builder, array $options) {
        $builder
        ->add('country_id', HiddenType::class, array('label' => false))
        ->add('vat_high', HiddenType::class, array('label' => false))
        ->add('vat_low', HiddenType::class, array('label' => false))
        ->add('vat_zero', HiddenType::class, array('label' => false))
        ->add('vat_none', HiddenType::class, array('label' => false))
        ->add('set_default', RadioType::class, array('label' => false))
        ->add('set_show', RadioType::class, array('label' => false));
    }
}

Solution

  • I ended up using following fix for this problem. It seems bit dirty but made most sense to because I dont want to confuse other devs with some really difficult method.

    <script type="text/javascript">
        (function (document, window, $) {
            $('[data-radio-field]').change(function () {
                var field = $(this).data('radio-field');
                $('[data-radio-field="' + field + '"]').not($(this)).prop('checked', false);
            });
        })(document, window, jQuery);
    </script>
    

    If anyone can suggest a clean method, they are welcome to answer it. I think it should be a common problem. Would like to see other approaches well.