0

I created a module that save the name of the Admin logged in, into "Sales Representative" column at "sales_order" table.

It's working pretty fine.

Now i need to save the same value into custom attribute of customer. (when a new customer is created by Admin in the customer page or create order page)

My code until now is: InstallSchema.php

<?php
/**
 * Store Admin Name Order table save
 *
 * @category     Store
 * @package      Store_Sales
 */
namespace Emporio\Seller\Setup;

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

class InstallSchema implements InstallSchemaInterface
{
    /**
     * Install DB schema for a module
     *
     * @param SchemaSetupInterface $setup
     * @param ModuleContextInterface $context
     * @return void
     */
    public function install(SchemaSetupInterface $setup, ModuleContextInterface $context)
    {
        $setup->startSetup();

        //$quote = 'quote';
        $orderTable = 'sales_order';

        //Order Grid table
        $setup->getConnection()
            ->addColumn(
                $setup->getTable($orderTable),
                'sales_representative',
                [
                    'type' => \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
                    'length' => 255,
                    'comment' =>'Vendedor'
                ]
            );

        $setup->endSetup();
    }
} 

events.xml

<?xml version="1.0"?>
<!--
/**
 * Store Admin Name Order table save
 *
 * @category     Store
 * @package      Store_Sales
 */
 -->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="checkout_submit_all_after">
        <observer name="store_admin_checkout_submit_all_after" instance="Emporio\Seller\Observer\AdminCheckoutSubmitAllAfter" />
    </event>
</config>

AdminCheckoutSubmitAllAfter.php

<?php
/**
 * Store Admin Name Order table save
 *
 * @category     Store
 * @package      Store_Sales
 */
namespace Emporio\Seller\Observer;

use Magento\Framework\Event\ObserverInterface;

class AdminCheckoutSubmitAllAfter implements ObserverInterface
{
    /**
     * @var \Magento\Backend\Model\Auth\Session
     */
    protected $backendAuthSession;
    protected $logger;

    /**
     * @param \Magento\Backend\Model\Auth\Session $backendAuthSession
     */
    public function __construct(
        \Magento\Backend\Model\Auth\Session $backendAuthSession
    ) {
        $this->backendAuthSession = $backendAuthSession;
    }

    /**
     * Add sale repsentative name to the order table
     *
     * @param \Magento\Framework\Event\Observer $observer
     * @return void
     */
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $adminUserName = $this->backendAuthSession->getUser()->getUserName();
        if ($adminUserName) {
            $order = $observer->getEvent()->getOrder();
            $order->setSalesRepresentative($adminUserName);
            $order->save();
        }
    }
} 

What do I have to do to save the value as custom attribute of customer and save in DB ?

1 Answer 1

1

To save the same attribute in customer, who will have to create 'sales_representative' attribute for customer.

  1. InstallData.php/UpgradeData.php - create the eav attribute 'sales_representative'.

    /* UpgradeData.php */ 
    
    
    <?php
     namespace Emporio\Seller\Setup;
    
     use Magento\Framework\Setup\UpgradeDataInterface;
     use Magento\Framework\Setup\ModuleDataSetupInterface;
     use Magento\Framework\Setup\ModuleContextInterface;
     use Magento\Customer\Setup\CustomerSetupFactory;
    
     class UpgradeData implements UpgradeDataInterface
     {
    
         protected $customerSetupFactory;
    
         protected $customerSetup;
    
         public function __construct(
            CustomerSetupFactory $customerSetupFactory
         ) {
            $this->customerSetupFactory = $customerSetupFactory;
         }
    
    
         public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
        {
            $setup->startSetup();
    
            $this->customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);
    
            $code = 'sales_representative';
            if (!$this->customerSetup->getAttribute(Customer::ENTITY, $code)) {
              $this->customerSetup->addAttribute(
                Customer::ENTITY,
                $code,
                [
                  'type' => 'varchar',
                  'label' => 'Sales Representative',
                  'input' => 'text',
                  'required' => false,
                  'visible' => true,
                  'user_defined' => true,
                  'position' => 1000,
                  'system' => 0,
                ]
             );
          }
          $setup->endSetup();
       }
    }
    
  2. You can use an observer "customer_register_success" to save your attribute in customer. As you only want to save admin details so we can create events.xml inside adminhtml folder.

    /* etc/adminhtml/events.xml */
    
    <event name="customer_register_success">
         <observer name="save_admin_customer_register_success" 
            instance="Emporio\Seller\Observer\Customer\SaveRepresentative"/>
    </event>
    
  3. Our Observer file will save that attribute

    /* Emporio\Seller\Observer\Customer\SaveRepresentative.php */
    
    class SaveRepresentative implements \Magento\Framework\Event\ObserverInterface
    {
    
        /**
         * @var \Magento\Backend\Model\Auth\Session
         */
         protected $backendAuthSession;
    
         public function __construct(
            \Magento\Backend\Model\Auth\Session $backendAuthSession
         ) {
            $this->backendAuthSession = $backendAuthSession;
         }
    
        public function execute(\Magento\Framework\Event\Observer $observer)
        {
           $customer = $observer->getEvent()->getCustomer();
           $adminUserName = $this->backendAuthSession->getUser()->getUserName();
           if ($adminUserName) {
               $customer->setData('sales_representative', $adminUserName);
               $customer->save();
           }
    
           return $this;
        }
    }
    
  4. to show the attribute value in order grid

Create sales_order_grid.xml file under app/code/Vendor/Module/view/adminhtml/ui_component

<listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
  <columns name="sales_order_columns">
    <column name="short_name" class="Vendor/Module\Ui\Component\Listing\Column\Representative">
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="filter" xsi:type="string">text</item>
                <item name="label" xsi:type="string" translate="true">Representative</item>
            </item>
        </argument>
    </column>
  </columns>
</listing>
  1. to show the value in order view information section, override the info template

Create sales_order_view.xml file under app/code/Vendor/Module/view/adminhtml/layout

<?xml version="1.0"?>
 <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
  <body>
    <referenceBlock name="order_info">
        <action method="setTemplate">
            <argument name="template" xsi:type="string">Vendor_Module::order/view/info.phtml</argument>
        </action>
    </referenceBlock>
  </body>
</page>
9
  • Thank you for your help. Will continue saving on DB (sales_order) and as custom attribute with this code ? Or only will save like custom attribute ? Jun 14, 2020 at 16:45
  • Yes, this will be saved like a custom attribute. Jun 14, 2020 at 16:57
  • I got this error while installing the module: Notice: Undefined property: Emporio\Seller2\Setup\InstallData ::$customerSetup in /var/www/clients/client1/web10/web/app/code/Emporio/Seller2/ Setup/InstallData.php on line 58 Jun 15, 2020 at 4:07
  • Could you give me the full "InstallData.php" file ? Jun 15, 2020 at 4:08
  • sure adding full content. But as you have your module already installed, you should write your code in UpgradeData.php Jun 15, 2020 at 4:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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