How to create table in system configuration

Sometimes we need to store configuration data as a table with the ability to add new roles. This functionality already exists in Magento 2. Let's look in detail.

Add backend model in system.xml

So you have an field 'table' in system.xml. Add frontend and backend models.

ArmMage\Config\Block\System\Config\Form\Field\Table

Magento\Config\Model\Config\Backend\Serialized\ArraySerialized

The backend model (Magento\Config\Model\Config\Backend\Serialized\ArraySerialized) will encode and decode data between config and DB table core_config_data. 

The frontend model will render your table.

Notice frontend model name style:

- ArmMage is the vendor name.

- Config is the module name.

- Block\System\Config\Form\Field is the usual path to the class.

- Table is a frontend model. It's time to check it.

Create frontend model

2.1 Create class ArmMage\Config\Block\System\Config\Form\Field\Table

2.2 Extends it with Magento\Config\Block\System\Config\Form\Field\FieldArray\AbstractFieldArray

2.3 Add method _prepareToRender

Ok, here let's move step by step. This is a minimum to get the table in the config

protected function _prepareToRender()

{

    $this->addColumn('column_1', []);

$this->addColumn('column_2', []);

}

Table admin magento

In parent class there are two properties:

_addButtonLabel - the label of a button. By default: Add.

__addAfter - show/hide the 'Add After' button. By default: true.

Let's rename the 'Add' button and hide the 'Add After' button.

protected function _prepareToRender()

{

$this->addColumn('column_1', []);

$this->addColumn('column_2', []);

$this->_addButtonLabel = 'Add Row';

$this->_addButton = false;

}

columns

Now let's add params to our column. There are five parameters of the column:

label - a label of column (Default: 'Column');

size - width of column;

style - css style;

class - css attribute 'class';

renderer => false.

$this->addColumn('column_1', [

    'label' => 'The First Column',

    'size' => '20%',

    'style' => 'background-color:blue',

    'class' => 'required-entry',

]);

$this->addColumn('column_2', [

    'label' => 'The Second Column',

    'size' => '80%',

    'style' => 'background-color:green',

    'class' => 'number',

]);

Columns  with color

That's enought to create and edit table. Good luck!



Ready to elevate your e-commerce business?

Discuss your business objectives with us. Get in touch today to explore ways we can assist in reaching them.

Copyright © 2021-2024 ArmMage LLC. All rights reserved.