Question

I am new to magento 2, and I would like to know how to update an added field in the customer_entity table, I have created a popup form with sending the information through post jquery, and the controller receives the information to be able updated in the database.

But the consumer field is not updated in the database, any suggestions?

Below the code:

/app/code/ElTiempo/ModalOverlay/Setup/UpgradeSchema.php

<?php

namespace Vendor\Module\Setup;

use Magento\Framework\DB\Ddl\Table;
use Magento\Framework\Setup\UpgradeSchemaInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
use Magento\Framework\Setup\ModuleContextInterface;

/**
 * Class UpgradeSchema
 */
class UpgradeSchema implements UpgradeSchemaInterface
{
    /**
     * @param SchemaSetupInterface $setup
     * @param ModuleContextInterface $context
     */
    public function upgrade(SchemaSetupInterface $setup, ModuleContextInterface $context)
    {
        if (version_compare($context->getVersion(), '1.0.1', '<')) {
            $this->addHabeasDataField($setup);
        }
    }

    /**
     *  table
     *
     * @param \Magento\Framework\Setup\SchemaSetupInterface $setup
     */
    protected function addHabeasDataField($setup)
    {
        $setup->startSetup();

        // Get module table
        $tableName = $setup->getTable('customer_entity');

        // Check if the table already exists
        if ($setup->getConnection()->isTableExists($tableName) == true) {
            // Declare data
            $columns = [
                'accept_habeas_data_datetime' => [
                    'type' => Table::TYPE_TIMESTAMP,
                    null,
                    'nullable' => true,
                    'comment' => 'Accept Habeas Data Datetime'
                ],
            ];

            $connection = $setup->getConnection();

            foreach ($columns as $name => $definition) {
                $connection->addColumn($tableName, $name, $definition);
            }
        }

        $setup->endSetup();
    }
}

/app/code/Vendor/Module/view/frontend/templates/view.phtml

date_default_timezone_set("America/New_York");
        $currentDateTime = date("Y-m-d H:i:s");
        $currentDateTimeStamp = strtotime($currentDateTime);
        if ($currentDateTimeStamp >= strtotime("2020-12-17 16:00:00")) {
            if ($content = $block->getContent('popup-habeas-data')) { 
        ?>
            <div id="modal-habeas-data" style="display:none;">
                <form action="<?php  echo $block->getBaseUrl() . 'accepthabeasdata/index/update';?>"
                    method="post" 
                    id="form-validate" 
                    enctype="multipart/form-data"
                    autocomplete="off"
                    data-mage-init='{"validation":{}}' 
                    data-hasrequired="<?php /* @escapeNotVerified */ echo __('* Required Fields') ?>">
                    <?php echo $content ?>
                    <input type="hidden" name="accept_habeas_data_datetime" value="<?php echo $currentDateTime ?>">
                </form>
            </div>
            <script type="text/x-magento-init">
                {
                    "*": {
                        "Magento_Ui/js/core/app": {
                            "components": {
                                "modal_habeas_data": {
                                    "component": "Vendor_Module/js/modal_habeas_data"
                                }
                            }
                        }
                    }
                }    </script>
        <?php 
            }
        }

/app/code/Vendor/Module/view/frontend/web/js/modal_habeas_data.js

initialize: function () {

        this._super();
        var options = {
            type: 'popup',
            responsive: true,
            innerScroll: false,
            title: false,
            clickableOverlay: false,
            opened: function($Event) {
                $('.modal-header button.action-close', $Event.srcElement).hide();
            },
            buttons: [{
                text: $.mage.__('Aceptar'),
                class: 'btn btn-primary',
                click: function () {
                    var form_data = $("#form-validate").serialize();
                    console.log(form_data);

                    $.ajax({
                        url: "accepthabeasdata/index/update",
                        type: 'POST',
                        data: form_data,
                        success: function(data) {
                            console.log(data);
                        },
                        error: function(result) {
                            console.log('no response !');
                        }
                    });

                    this.closeModal();
                }
            }]
        };

        var modal_habeas_data_element = $('#modal-habeas-data');
        var popup = modal(options, modal_habeas_data_element);

        modal_habeas_data_element.css("display", "block");

        this.openModalHabeasDataModal();

    },

/app/code/Vendor/Module/etc/frontend/routes.xml

<?xml version="1.0"?>
<!--
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/App/etc/routes.xsd">
    <router id="standard">
        <route id="acceptHabeasData" frontName="accepthabeasdata">
            <module name="Vendor_Module"/>
        </route>
    </router>
</config>

/app/code/Vendor/Module/Controller/Index/Update.php

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

namespace Vendor\Module\Controller\Index;

class Update extends \Magento\Framework\App\Action\Action
{
    /**
     * @var CustomerRepositoryInterface
     */
    protected $customerSession;
    protected $customerRepository;

    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Customer\Model\Session $customerSession,
        \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository
    )
    {
        $this->customerSession = $customerSession;
        $this->customerRepository = $customerRepository;
        return parent::__construct($context);
    }

    public function execute()
    {
        $customerId =  $this->customerSession->getCustomer()->getId(); //Get Current customer ID
        echo $customerId;
        $data = $this->getRequest()->getParams('accept_habeas_data_datetime');
        var_dump($data);
        $customer = $this->customerRepository->getById($customerId);
        $customer->setCustomAttribute('accept_habeas_data_datetime', $data);
        $this->customerRepository->save($customer);
    }
}
Was it helpful?

Solution

I have the solution, I needed to create before the attribute with the same name of the field. With this I have been able to update the data in the customer_entity table

/app/code/Vendor/Module/Setup/UpgradeData.php

<?php

namespace Vendor\Module\Setup;

use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Customer\Setup\CustomerSetupFactory;
use Magento\Quote\Setup\QuoteSetupFactory;
use Magento\Sales\Setup\SalesSetupFactory;
use Magento\Framework\Setup\UpgradeDataInterface;
use Magento\Eav\Model\Entity\Attribute\SetFactory as AttributeSetFactory;
use Magento\Customer\Api\CustomerMetadataInterface;

/**
 * @codeCoverageIgnore
 */
class UpgradeData implements UpgradeDataInterface
{
    /**
     * @var CustomerSetupFactory 
     */
    private $customerSetupFactory;

    /**
     * @var SalesSetupFactory
     */
    private $salesSetupFactory;

    /**
     * @var QuoteSetupFactory
     */
    private $quoteSetupFactory;

    /**
     * @var AttributeSetFactory 
     */
    private $attributeSetFactory;

    /**
     * @var \Magento\Eav\Setup\EavSetupFactory 
     */
    private $eavSetupFactory;


    /**
     * UpgradeData constructor.
     * @param CustomerSetupFactory $customerSetupFactory
     * @param SalesSetupFactory $salesSetupFactory
     * @param QuoteSetupFactory $quoteSetupFactory
     * @param \Magento\Eav\Setup\EavSetupFactory $eavSetupFactory
     * @param \Magento\Eav\Model\Config $eavConfig
     * @param AttributeSetFactory $attributeSetFactory
     */
    public function __construct(
        CustomerSetupFactory $customerSetupFactory,
        SalesSetupFactory $salesSetupFactory,
        QuoteSetupFactory $quoteSetupFactory,
        \Magento\Eav\Setup\EavSetupFactory $eavSetupFactory,
        \Magento\Eav\Model\Config $eavConfig,
        AttributeSetFactory $attributeSetFactory
    ) {
        $this->customerSetupFactory = $customerSetupFactory;
        $this->salesSetupFactory = $salesSetupFactory;
        $this->quoteSetupFactory = $quoteSetupFactory;
        $this->eavSetupFactory = $eavSetupFactory;
        $this->eavConfig = $eavConfig;
        $this->attributeSetFactory = $attributeSetFactory;
    }

    /**
     * @param ModuleDataSetupInterface $setup
     * @param ModuleContextInterface $context
     */
    public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context) {


        $installer = $setup;
        $installer->startSetup();

        /** @var CustomerSetup $customerSetup */
        $customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);


        if (version_compare($context->getVersion(), '1.0.1') < 0) {

            $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);

            $customerEntity = $customerSetup->getEavConfig()->getEntityType('customer');
            $attributeSetId = $customerEntity->getDefaultAttributeSetId();


            $attributeSet = $this->attributeSetFactory->create();
            $attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId);

            $customerSetup->addAttribute(\Magento\Customer\Model\Customer::ENTITY, 'accept_habeas_data_datetime', [
                'type' => 'static',
                'label' => 'Accept Habeas Data',
                'input' => 'text',
                'required' => false,
                'visible' => true,
                'user_defined' => true,
                'sort_order' => 1000,
                'position' => 1000,
                'system' => 0,
            ]);

            $eavSetup->addAttributeToSet(
                CustomerMetadataInterface::ENTITY_TYPE_CUSTOMER,
                CustomerMetadataInterface::ATTRIBUTE_SET_ID_CUSTOMER,
                null,
                'accept_habeas_data_datetime');

            $customerSetup->getEavConfig()->getAttribute(\Magento\Customer\Model\Customer::ENTITY, 'accept_habeas_data_datetime')
                ->addData([
                    'attribute_set_id' => $attributeSetId,
                    'attribute_group_id' => $attributeGroupId,
                    'used_in_forms' => ['adminhtml_customer','customer_address_edit','adminhtml_customer_address', 'customer_register_address','customer_account_edit', 'customer_account_create']
                ])->save();;

        }

        $installer->endSetup();
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top