Magento 2 Admin Form – Save Checkboxes Type in Admin Form

adminadminformdatabasemagento2

In Magento 2 there is form field type 'checkboxes'.
I've added it to my adminhtml edit form:

// app\code\Vendor\Module\Block\Adminhtml\Point\Edit\Form.php

$balloonFieldset->addField(
            'payment_types',
            'checkboxes',
            [
                'label' => __('Payment Types'),
                'name' => 'payment_types',
                'values' => [
                    ['value' => '2','label' => 'Card'],
                    ['value' => '3','label' => 'Cash'],
                    ['value' => '4','label' => 'Prepaid'],
                ],
            ]
        );

And it looks like this:

checkboxes

I've tried to store it in database in varchar field with imploding and exploding it in model:

    /**
     * Set payment_types
     *
     * @param array $paymentTypes
     * @return \Vendor\Module\Api\Data\PointInterface
     */
    public function setPaymentTypes($paymentTypes)
    {
        $stringTypes = implode(', ', $paymentTypes);

        return $this->setData(self::PAYMENT_TYPES, $stringTypes);
    }

    /**
     * Get payment types
     *
     * @return string|null
     */
    public function getPaymentTypes()
    {
        return explode(', ', $this->getData(self::PAYMENT_TYPES));
    }

But it always saves the last checkbox's value.
For example: if I check 'Card' and 'Cash', in database it will be '3', if I check 'Cash' and 'Prepaid', it will be '4' and so on.

Saving it as a string suits perfect for me, but I need it to save correct values: '2, 3' in first case and '3, 4' in second.

What is the right way of doing this?

Best Answer

Change this

'name' => 'payment_types',

to this

'name' => 'payment_types[]',

and the rest of your code should work.