Skip to content

How to Pragmatically Check an Input Option in an Admin Form

I am fetching data and populating radioset options for an admin form.
I can populate the options but I want to have them checked based on the fetched data.
I tried putting ‘checked’ attribute but was not successful.
Can someone please guide me in the right direction?

<?php

namespace HaywardSchedulePageBuilderUiComponentForm;

use MagentoFrameworkDataOptionSourceInterface;
use VendorModuleModelResourceModelSpeakerCollectionFactory;

class Options implements OptionSourceInterface
{
    /**
     * @var array
     */
    protected $options;
    /**
     * @var CollectionFactory
     */
    protected $collectionFactory;

    public function __construct(
        CollectionFactory $collectionFactory
    )
    {
        $this->collectionFactory = $collectionFactory;
    }

    /**
     * @return array
     */
    public function toOptionArray()
    {
        $collection = $this->collectionFactory->create();
        $items = $collection->getItems();

        uasort($items, function ($a, $b) {
            return strcmp($a['lastname'], $b['lastname']);
        });
        // I tried adding 'checked' => "checked" to the array below, but it didn't work.
        foreach ($items as $item) {
            $formattedLabel = $item['lastname'] . ', ' . $item['firstname'];
            $this->options[] = ['label' => $formattedLabel, 'value' => $item['id'], 'checked' => "checked"];
        }
        return $this->options;
    }
}

form.xml

        <field name="speakers" formElement="radioset">
            <settings>
                <label translate="true">Speakers</label>
                <dataScope>speakers</dataScope>
            </settings>
            <formElements>
                <radioset>
                    <settings>
                        <options class="VendorModuleUiComponentFormOptions"/>
                        <multiple>true</multiple>
                    </settings>
                </radioset>
            </formElements>
        </field>

Thank you.