Magento 2 Developement

Magento 2: Working with ArraySerialized backend model

Complete module code can be found on github.
Ready-to-paste package – magento2_configuration_arrayserialized.zip.
Installation instructions

Magento 2 ArraySerialized is backend model used to store configuration data ( dynamic settings array ) in serialized state in one field. It extends \Magento\Config\Model\Config\Backend\Serialized model and has two basic methods:

beforeSave serializes data before saving, as a result options converted to a string and can be stored in a single field in the database

_afterLoad unserialize value before return it to caller.

Magento 2.0.x and Magento 2.1.x use default PHP serialize functionality. Starting from Magento 2.2.x it uses the JSON format by default.

Implementation

Dynamic settings in system configuration is really cozy when you don’t know exact number of parameters. Here is sample screenshot from Magento 2 Product Slider extension by NWDthemes. It allows you to control number of items in slider for certain screen width. You can add and delete options according to your needs.

1. Add new field in /etc/adminhtml/system.xml.

It use ArraySerialized as backend model.

2. Create frontend model Block/Adminhtml/Form/Field/ResponsiveItems.php. We use text field for sample, but it can be any html element like checkbox, dropdown, radio button etc.

$this->addColumn() add columns to settings array. Function take two params:

  1. $name – define column name
  2. $params – column parameters array. Possible parameters are:
    • ‘label’
    • ‘size’
    • ‘style’
    • ‘class’
    • ‘renderer’

Thats it. Clear cache if enabled and you can see new field in magento admin.

Default values for system configuration

Usually default values for configuration set in etc/config.xml. But it does not work with ArraySerialized in Magento 2.0.x – 2.1.x. Check this issue on github for details. To resolve it we will use Setup/InstallData.php. Data setup used to insert default module data into database. Attributes that come with Magento by default, 404 and other Cms pages are all examples of data setup.

How data stored in database

Magento 2.0.x – 2.1.x use default PHP serialize functionality.

Magento 2.2.x use the JSON format by default.

Array keys like _1528879546018_18 generated by magento when you add new option to your dynamic settings. Its purpose is just to generate unique element ID. Javascript code that add new row use time and milliseconds to generate it. We will use this info to generate default value.

Add default value

$state->setAreaCode('adminhtml'); line in constructor set store area. Area is not set in Magento CLI (it is not required for any core commands). When you try to run setup:upgrade without the area you will get the error:

Data script use \Magento\Config\Model\Config model to save default value. We pass array to the model, but it needs to be serialized before save. Config model check if field has backend model and use it for data processing. Check Mage2.PRO for complete code flow of how magento 2 save a backend config form vield value.

Starting from magento 2.2.4 you should be able to set default value directly in etc/config.xml. Check this commit for a fix and usage sample.

Using dynamic settings in your models / blocks / templates

To use dynamic settings in module we will create a helper.

public function getConfigValue() used to load any value from config table.
public function getSerializedConfigValue() is modified to automatically unserialize config data. It detect if we have serialized string or json string and use proper method to unserialize data. This code works in both 2.0.x – 2.1.x and 2.2.x versions. Starting from 2.2.4 it should be enough to use just public function getConfigValue().

Sample block to illustrate helper usage.

We inject helper in block constructor and use it to grab the data from configuration. Complete module code can be found on github.

Installation

Install via composer (recommend)

Run the following command in Magento 2 root folder:

Check this article if you have for details – install magento 2 module using github

Install ready-to-paste package

Uninstallation

Magento 2: How to disable module
Magento 2: How to uninstall module

2 thoughts on “Magento 2: Working with ArraySerialized backend model

  1. Hi, i got “my_variable is not defined” when trying to use this code in Block/Adminhtml/Form/Field/ResponsiveItems.php:
    $this->addColumn(‘subject_email’, [‘label’ => __(‘Subject Email’)]);

    This only happen when i do this the second time. On first time i put 2 column and it worked perfectly:
    $this->addColumn(‘subject_code’, [‘label’ => __(‘Subject Code’)]);
    $this->addColumn(‘subject_label’, [‘label’ => __(‘Subject Label’)]);

    Please help, thanks

  2. Hi
    Can you add more details?
    1. What magento version you have?
    2. Could you add full code of ResponsiveItems.php file to check the error?

Leave a Reply

Your email address will not be published. Required fields are marked *