PHPackages                             bdc/module-contactpreferences - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. bdc/module-contactpreferences

ActiveMagento2-module

bdc/module-contactpreferences
=============================

BDCrops ContactPreferences module for Magento 2 extensions.

001PHP

Since Oct 16Pushed 6y ago1 watchersCompare

[ Source](https://github.com/bdcrops/module-contactpreferences)[ Packagist](https://packagist.org/packages/bdc/module-contactpreferences)[ RSS](/packages/bdc-module-contactpreferences/feed)WikiDiscussions master Synced today

READMEChangelogDependenciesVersions (1)Used By (0)

Magento 2x ContactPreferences
=============================

[](#magento-2x-contactpreferences)

This module is used as Customer Contact Preferences for all BDCrops Magento 2 extensions.understand the mechanism behind the customerData object and the section load, let's put it to use by creating a small module that adds contact preferences functionality under the customer's My Account area, as well as under the checkout.

Built a small module that allowed us to get a greater insight into Magento's customerData and sections mechanisms. We managed to build a single component, that got used both on the customer's My Account page, as well as on the checkout.

Goal
----

[](#goal)

- Adding contact preferences to customer accounts
- Manage CustomerData Entity in Magento 2
- use Section.xml file in Magento 2
- Customizing the Checkout Process
- Learn Magento 2 Certified Professional Developer exam topics "Customizing the Checkout Process 13%"

1. How to install &amp; upgrade ContactPreferences
--------------------------------------------------

[](#1-how-to-install--upgrade-contactpreferences)

#### 1.1 Copy and paste

[](#11-copy-and-paste)

If you don't want to install via composer, you can use this way.

- Download [the latest version here](https://github.com/bdcrops/module-contactpreferences/archive/master.zip)
- Extract `master.zip` file to `app/code/BDC/ContactPreferences` ; You should create a folder path `app/code/BDC/ContactPreferences` if not exist.
- Go to Magento root folder and run upgrade command line to install `BDC_ContactPreferences`:

```
php bin/magento setup:upgrade
php bin/magento setup:static-content:deploy

```

#### 1.2 Install via composer

[](#12-install-via-composer)

We recommend you to install BDC\_ContactPreferences module via composer. It is easy to install, update and maintaince.Run the following command in Magento 2 root folder.

```
composer config repositories.module-contactpreferences git
https://github.com/bdcrops/module-contactpreferences.git

composer require bdcrops/module-contactpreferences:~1.0.0
php bin/magento setup:upgrade
php bin/magento setup:static-content:deploy

```

#### 1.3 Upgrade

[](#13-upgrade)

```
composer update bdcrops/module-contactpreferences
php bin/magento setup:upgrade
php bin/magento setup:static-content:deploy

```

Run compile if your store in Product mode:

```
php bin/magento setup:di:compile

```

2. BDC\_ContactPreferences
--------------------------

[](#2--bdc_contactpreferences)

- create app/code/BDC/ContactPreferences/etc/module.xml

```

```

- create app/code/BDC/ContactPreferences/registration.php

```

```

- create app/code/BDC/ContactPreferences/Controller/Contact/Preferences.php

```

                BDC\ContactPreferences\CustomerData\Preferences

```

- create app/code/BDC/ContactPreferences/CustomerData/Preferences.php

```

```

- create app/code/BDC/ContactPreferences/view/frontend/layout/checkout\_index\_index.xml

```

                                                                    BDC_ContactPreferences/js/view/contact-preferences

```

[![](docs/checkout.png)](docs/checkout.png)

- create app/code/BDC/ContactPreferences/view/frontend/layout/customer\_account.xml

```

                    customer/contact/preferences
                    My Contact Preferences
                    230

```

[![](docs/ContactPrefCuAcc.png)](docs/ContactPrefCuAcc.png)

- create app/code/BDC/ContactPreferences/view/frontend/layout/customer\_contact\_preferences.xml

```

```

- create app/code/BDC/ContactPreferences/view/frontend/templates/customer/contact/preferences.phtml

```

    {
        ".contact-preferences": {
            "Magento_Ui/js/core/app": {
                "components": {
                    "contact-preferences-scope": {
                        "component": "contactPreferences"
                    }
                }
            }
        }
    }

```

- create app/code/BDC/ContactPreferences/view/frontend/requirejs-config.js

```
var config = {
    map: {
        '*': {
            contactPreferences: 'BDC_ContactPreferences/js/view/contact-preferences'
        }
    }
};

```

- create app/code/BDC/ContactPreferences/view/frontend/web/js/view/contact-preferences.js

```
define([
    'uiComponent',
    'jquery',
    'mage/url',
    'Magento_Customer/js/customer-data',
    'Magento_Customer/js/model/customer'
], function (Component, $, url, customerData, customer) {
    'use strict';

    let contactPreferences = customerData.get('contact_preferences');

    return Component.extend({
        defaults: {
            template: 'BDC_ContactPreferences/contact-preferences'
        },

        initialize: function () {
            this._super();

            // Trigger "contact_preferences" section load
            $.ajax({
                type: 'POST',
                url: url.build('customer/contact/preferences'),
                data: {'load': true},
                showLoader: true
            });
        },

        isCustomerLoggedIn: function () {
            return contactPreferences().isCustomerLoggedIn;
        },

        getSelectOptions: function () {
            return contactPreferences().selectOptions;
        },

        saveContactPreferences: function () {
            let preferences = {};

            $('.contact_preference').children(':checkbox').each(function () {
                preferences[$(this).attr('name')] = $(this).attr('checked') ? true : false;
            });

            $.ajax({
                type: 'POST',
                url: url.build('customer/contact/preferences'),
                data: preferences,
                showLoader: true,
                complete: function (response) {
                    // todo
                }
            });

            return true;
        }
    });
});

```

- create app/code/BDC/ContactPreferences/view/frontend/web/template/contact-preferences.html

```

```

- Result [![](docs/ContactPrefAdmin.png)](docs/ContactPrefAdmin.png)[![](docs/ContactPrefCuAcc.png)](docs/ContactPrefCuAcc.png)[![](docs/db.png)](docs/db.png)

FAQ
---

[](#faq)

### What are exactly those sections ?

[](#what-are-exactly-those-sections-)

A section is a piece of customer data grouped together. Each section is represented by key that is used to access and manage data and data itself. Magento loads sections by AJAX request to /customer/section/load/ and caches loaded data in the browser local storage under the key mage-cache-storage. Magento tracks when some section is changed and load updated section automatically.

### How do you define a section ?

[](#how-do-you-define-a-section-)

A section defined in di.xml file by adding a new section into sections pool

```

            Magento\Checkout\CustomerData\Cart
            Magento\Checkout\CustomerData\DirectoryData

```

So here two new sections are registered cart and directory-data. Magento\\Checkout\\CustomerData\\Cart and Magento\\Checkout\\CustomerData\\DirectoryData implements Magento\\Customer\\CustomerData\\SectionSourceInterface and provides actual data as result of getSectionData method.

### How are the section updates triggered ?

[](#how-are-the-section-updates-triggered-)

Magento assumes that customer's private data is changed when a customer sends some state modification request (POST, PUT, DELETE). To minimize the load on server, developers should specify which action (or request) updates which customer data section in etc/section.xml.

```

```

Action name is an action key pattern. When a user calls to action that matches specified pattern Magento will detect that corresponding section is outdated and loads it again. If action name is \* that means that section will be updated on each POST and PUT request. If section tag is missed then all section will be updated. So conceptually this is wrong to update mini cart when you rich cart page. At this point, mini cart (or cart section) already should be updated.

### How to Internal Implementation ?

[](#how-to-internal-implementation-)

To understand when and how sections are updated let's see implementation. Key to understanding are files magento2ce/app/code/Magento/Customer/view/frontend/web/js/section-config.js and magento2ce/app/code/Magento/Customer/view/frontend/web/js/customer-data.js.

At the end of last one of the two events handlers are registered for ajaxComplete and submit. That means that when any form is posted (with POST or PUT methods) to server, or when JavaScript sends an AJAX, POST or PUT request, the handlers will be invoked. Both handlers have similar logic: with help of Magento\_Customer/js/section-config check should be any section updated or not. If some section should be updated then customerData.invalidate(sections) is called. And later all invalidated sections are loaded from a server.

So how does Magento\_Customer/js/section-config know which section should be removed and on which action? The answer is in Magento/Customer/view/frontend/templates/js/section-config.phtml:

```

```

In such way, a server passes merged sections configuration to a browser.

### How section may be updated only by POST or PUT form submitting or AJAX request?

[](#how--section-may-be-updated-only-by-post-or-put-form-submitting-or-ajax-request)

In addition, there are only two notes:

all described here is internal implementation and may be changed, so you may safely use only sections.xml and expect section updates when specified POST or PUT or DELETE actions are triggered. if you sure, that you really need update some section you can always do something like this:

```
 require('Magento_Customer/js/customer-data').reload(['cart'], false)

```

### What is Section.xml file in Magento 2?

[](#what-is-sectionxml-file-in-magento-2)

With the growing use of the internet and technology, several changes &amp; enhancement happen into design, layout, and code to provide a better &amp; a richer experience to the users. Also, Magento moved smartly with concepts like knockout js, AJAX other add ons that allows web applications to send and retrieve data from a server asynchronously without refreshing or reloading. This technique helps reducing server request and saves time by reloading only one portion or section of the webpage. For example, we have one extension in Magento 2 that offers Ajax login functionality and we want to restore old cart items once a user successfully login to their account. To do the same we only need to refresh a mini cart only, not the whole page. By default, Magento 2 creates a small group of data and each group has a unique name/key. So, if we want to refresh a particular section we can use its group key to refresh data. In all new Magento 2, it stores data at both hands, so we also need to update local storage data of browser if we want to refresh a particular portion.

### How to implementing Section.xml file in Magento 2?

[](#how-to-implementing-sectionxml-file-in-magento-2)

To do the same, first you need to create “di.xml” at this path. app\\code\\Vendor\\Extension\\etc\\di.xml To do the same, first you need to create “di.xml” at this path. app\\code\\Vendor\\Extension\\etc\\di.xml

```

        	Magento\Checkout\CustomerData\Cart
        	Magento\Checkout\CustomerData\DirectoryData

```

Now, in above code we just register cart and directory-data in customer Data section. For that we need to create section.xml using below code at this path. app\\code\\Vendor\\Extension\\etc\\frontend\\section.xml

```

```

So, now whenever we call action like “ajaxlogin/index/getlogin” Magento will consider the current cart section is outdated and it re-initialize the cart section. You can also refresh the cart section on each request, by using \* instead of action.

### Explain Customer Data Management in Magento 2?

[](#explain-customer-data-management-in-magento-2)

It happens that you are frequently facing asynchronous customer data loading while working with Magento 2. For example cart reloading, checkout, logging and user log in and some others are working through AJAX. In order to work with these data, Magento development team provides with a proper interface, that we are going to overview now.

Interface of the current module consists of js-module, which is uploaded by RequireJs and from backend interface that allows sending data by AJAX. Let’s consider a template for name displaying in default Magento 2 theme.Customer’s name is displayed by this code implemented:

```
