How to add radio option in Magento 2?

change type from radio to radios

$fieldset->addField(
            'test',
            'radios',
            [
                'label' => __('test'),
                'title' => __('test'),
                'name' => 'test',
                'required' => true,
                'values' => array(
                            array('value'=>'1','label'=>'Radio1'),
                            array('value'=>'2','label'=>'Radio2'),
                            array('value'=>'3','label'=>'Radio3'),
                       ),
                'disabled' => $isDisabled
            ]
        );

for more types you can look in to namespace Magento\Framework\Data\Form\Element


Use below code:

$fieldset->addField(
            'test',
            'radios',
            [
                'name' => 'test',
                'label' => __('Radio'),
                'title' => __('Radio'),
                'required' => true,
                'values' => [
                                ['value' =>1, 'label' => __('Yes')],
                                ['value' => 0, 'label' => __('No')]
                            ],
                'disabled' => $isElementDisabled
            ]
        );

enter image description here


It seems like the way Magento 2 handles radio require multiple radio fields with the same name.

There's a good example in app/code/Magento/ConfigurableProduct/Block/Adminhtml/Product/Edit/AttributeSet/Form.php

In your case the right code would be:

    $fieldset->addField(
        'Radio1',
        'radio',
        [
            'name' => 'test',
            'value' => '1'
        ]
    );
    $fieldset->addField(
        'Radio2',
        'radio',
        [
            'name' => 'test',
            'value' => '2'
        ]
    );
    $fieldset->addField(
        'Radio3',
        'radio',
        [
            'name' => 'test',
            'value' => '3'
        ]
    );

On top of that it seems like app/code/Magento/Catalog/Block/Adminhtml/Product/Helper/Form/Weight.php uses a slightly different method in the below code but as it is a custom element I'm not sure if that will fit your needs:

    $this->weightSwitcher = $factoryElement->create('radios');
    $this->weightSwitcher->setValue(
        WeightResolver::HAS_WEIGHT
    )->setValues(
        [
            ['value' => WeightResolver::HAS_WEIGHT, 'label' => __('Yes')],
            ['value' => WeightResolver::HAS_NO_WEIGHT, 'label' => __('No')]
        ]
    )->setId(
        'weight-switcher'
    )->setName(
        'product_has_weight'
    )->setLabel(
        __('Does this have a weight?')
    );