1

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?

3

Change this

'name' => 'payment_types',

to this

'name' => 'payment_types[]',

and the rest of your code should work.

  • Sounds logical, but when I change it to 'payment_types[]' I get and error "Something went wrong while saving the point." – jurgen May 26 '16 at 15:03
  • see how the data you get throgh $_POST looks like. – Marius May 26 '16 at 15:08
  • When I made explode and implode in Model, it has no effect. But when I made it in ResourceModel in _afterLoad() and _beforeSave(), it works perfectly, thank you! – jurgen May 26 '16 at 16:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.