I am trying to save data from a model to the database. Most of the data is being saved correctly, but I am having issues with boolean fields.

The database has several boolean fields something like the following:

Vendor/Module/Setup/InstallSchema.php

->addColumn(
    'sunday_openclose',
    \Magento\Framework\DB\Ddl\Table::TYPE_BOOLEAN,
    null,
    ['nullable' => false, 'default' => true],
    'Sunday Open or Close'
)

This produces a TINYINT(1) field in the database, so I would imagine I just use 0s and 1s for values.

I am using an UI Component form to make the adminhtml form to work with this model and database table. This is an example of the field that correspond to the database column above:

Vendor/Module/view/adminhtml/ui_component/form.xml

<field name="sunday_openorclose">
    <argument name="data" xsi:type="array">
        <item name="config" xsi:type="array">
            <item name="label" xsi:type="string">Sunday - Open or Close</item>
            <item name="visible" xsi:type="boolean">true</item>
            <item name="dataType" xsi:type="string">boolean</item>
            <item name="formElement" xsi:type="string">checkbox</item>
            <item name="prefer" xsi:type="string">toggle</item>

            <item name="valueMap" xsi:type="array">
                <item name="true" xsi:type="string">1</item>
                <item name="false" xsi:type="string">0</item>
            </item>

            <item name="toggleLabels" xsi:type="array">
                <item name="on" xsi:type="string">Open</item>
                <item name="off" xsi:type="string">Close</item>
            </item>

            <item name="checked" xsi:type="boolean">true</item>
            <item name="default" xsi:type="string">1</item>
            <item name="source" xsi:type="string">hours</item>
        </item>
    </argument>
</field>

This makes a toggle looking "checkbox". Finally this is part of the Save controller that handles interpreting the data from the form to the database:

EDITED
Vendor/Module/Adminhtml/Index/Save.php

public function execute()
{
    $model = $this->locationFactory->create();
    $resultRedirect = $this->resultRedirectFactory->create();

    $data = $this->getRequest()->getPostValue(); // Get the post data
    $hours = $data['hours']; // Get the hours form data

    if($data){
        try{
            // Snippit

            // Setting Hours
            $this->logger->info('Hours Data');
            $model = $this->setHoursData($hours, $model);

            // Snippit

            // Save Model
            $model->save();

            // After saving model
            $this->messageManager->addSuccess('Model successfully saved!');

            // Would like to know how to not use object manager w/o triggering "already being used" error
            $this->_objectManager->get('Magento\Backend\Model\Session')->setFormData(false);
        } catch (\Exception $e){
            $this->messageManager->addError($e->getMessage());

            // Would like to know how to not use object manager w/o triggering "already being used" error
            $this->_objectManager->get('Magento\Backend\Model\Session')->setFormData($data);

            return $resultRedirect->setPath('*/*/edit');
        }
    }

    return $resultRedirect->setPath('*/*/');
}


private function setHoursData($hour, $model)
{
    $days = [1 => 'sunday', 2 => 'monday', 3 => 'tuesday', 4 => 'wednesday', 5 => 'thursday', 6 => 'friday', 7 => 'saturday'];

    // Loop through all of the days
    foreach($days as $dayName){
        if($hour[$dayName . '_openorclose'] === '1'){
            $model->setData($dayName . '_openorclose', 1);
            // Other irrelevant code
        } else {
            $model->setData($dayName . '_openorclose', 0);
            // Other irrelevant code
        }
    }

    return $model;
}

Should be simple enough. If its '1' then insert as 1 otherwise if it's '0' then insert as 0.

The problem I am getting is that regardless what I do the database record always returns 1 or true regardless if sunday or any other day is false or 0. I have tried using true/false in the save controller, removing the default value attribute, and removing the not null attribute from the database column(s).

In the case of removing the default value, the database column values returns 0 regardless of value for the respective fields.

有帮助吗?

解决方案

Have you created all names column in table ? Like sunday_openclose, monday_openclose,etc ? – Rohan Hapani 1 hour ago

I may had the columns created in the database, but in the Controller I had it set for *_openorclose instead of *_openclose. That was the solution.

许可以下: CC-BY-SA归因
scroll top