5

I am trying to build an extension that will check if a specific cookie exists at the time an order is being placed. If the cookie does exist, I would like to save its value to the order in the database.

I know how to check and retrieve the cookie and its value, but what is the best approach for saving this cookie's value to the order in the database in a way that it can be retrieved later on?

So far I have looked into adding custom columns to the quote and sales_order tables, but I have not found anything that shows how to save or retrieve values that way.

I have also looked at the extension attributes feature that is new to Magento 2, but I do not know enough about how that works to implement this feature.

How would I go about achieving this requirement?

UPDATE WITH SOLUTION Here is the solution that I came up with based on the answer provided below.

Company\ModuleName\etc\extension_attributes.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Api/etc/extension_attributes.xsd">
    <extension_attributes for="Magento\Checkout\Api\Data\ShippingInformationInterface">
        <attribute code="affiliate_id" type="string"/>
    </extension_attributes>
</config>

Company\ModuleName\etc\frontent\events.xml

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="controller_action_predispatch">
        <observer name="naturehills_affiliatetracking" instance="NatureHills\AffiliateTracking\Observer\AffiliateTracking" shared="false" />
    </event>
    <event name="sales_model_service_quote_submit_before">
        <observer name="naturehills_affiliatetracking_add_to_order" instance="NatureHills\AffiliateTracking\Observer\SaveAffiliateId"/>
    </event>
</config>

Company\ModuleName\Observer\SaveAffiliateId.php

<?php

namespace Company\ModuleName\Observer;

use Magento\Framework\Event\Observer as EventObserver;
use Magento\Framework\Event\ObserverInterface;

class SaveAffiliateId implements ObserverInterface
{
    /**
     * @var
     */
    protected $_cookieManager;

    /**
     * SaveAffiliateId constructor.
     * @param \Magento\Framework\Stdlib\CookieManagerInterface $cookieManager
     */
    public function __construct(\Magento\Framework\Stdlib\CookieManagerInterface $cookieManager)
    {
        $this->_cookieManger = $cookieManager;
    }

    /**
     * @param EventObserver $observer
     * @return $this
     */
    public function execute(EventObserver $observer)
    {
        $order = $observer->getEvent()->getOrder();

        $affiliateCookie = $this->_cookieManager->getCookie(self::COOKIE_NAME);

        if($affiliateCookie)
        {
            $order->setAffiliateId($affiliateCookie);
        }

        return $this;
    }
}

Company\ModuleName\Setup\InstallSchema.php

<?php

namespace Company\ModuleName\Setup;

use Magento\Framework\Setup\InstallSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;

/**
 * @codeCoverageIgnore
 */
class InstallSchema implements InstallSchemaInterface
{
    /**
     * {@inheritdoc}
     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
     */
    public function install(SchemaSetupInterface $setup, ModuleContextInterface $context)
    {
        $installer = $setup;
        $installer->startSetup();
        $installer->getConnection()->addColumn(
            $installer->getTable('quote'),
            'affiliate_id',
            [
                'type' => 'text',
                'nullable' => true,
                'comment' => 'Affiliate Id',
            ]
        );

        $installer->getConnection()->addColumn(
            $installer->getTable('sales_order'),
            'affiliate_id',
            [
                'type' => 'text',
                'nullable' => true,
                'comment' => 'Affiliate Id',
            ]
        );

        $setup->endSetup();
    }
}

Do not forget the module.xml (Company\ModuleName\etc\module.xml)

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Company_ModuleName" setup_version="0.0.1" />
</config>

And the registration.php (Company\ModuleName\registration.php)

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Company_ModuleName',
    __DIR__
);
6

For saving data into order table try following way

Vendor/Module/etc/events.xml


<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="sales_model_service_quote_submit_before">
        <observer name="sr_delivery_date" instance="Vendor\Module\Observer\SaveDataToOrderObserver"/>
    </event>
</config>

Vendor/Module/Observer/SaveDataToOrderObserver.php


namespace Vendor\Module\Observer;

use Magento\Framework\Event\Observer as EventObserver;
use Magento\Framework\Event\ObserverInterface;

class SaveDataToOrderObserver implements ObserverInterface
{
    public function execute(EventObserver $observer)
    {
        $order = $observer->getOrder();
        $order->setYourCustomColumn('TEST DATA');
        return $this;
    }
}

That's it.

Here is an example module

|improve this answer|||||

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.