How to Add Dynamic Rows Components in Magento 2?

How to Add Dynamic Rows Components in Magento 2?

Need a better way to manage records in Magento 2? Dynamic Rows Components in Magento 2 simplify admin tasks. It allows quick edits, additions, and reordering without coding. It keeps product data, shipping rates, and tax rules organized.

This tutorial covers Dynamic Rows setup, benefits, and best practices.

Best Magento Hosting now

Key Takeaways

  • Overview of Dynamic Rows Components

  • Steps to Create Dynamic Rows Components in Magento 2

  • Options in Dynamic Rows Components of Magento Stores

  • Dynamic Rows Component Benefits in Magento

  • Troubleshooting Dynamic Rows Component Issues in Magento

What are Dynamic Rows Components?

Dynamic Rows Components in Magento 2 make record management simple. Magento admins can add new records, edit existing ones, and reorder them.

These features help with tasks like:

  • Adjusting product attributes

  • Shipping rates

  • Tax rules

The setup keeps data organized in the Magento 2 Admin Panel. Dynamic Rows improve flexibility and speed for admins. This tool allows quick changes without extra effort.

Admins see Dynamic Rows on several backend pages. It’s beneficial for managing multiple records. Drag-and-drop reordering keeps things easy. Each record is edited individually, lowering the chance of mistakes. This design saves time and avoids the need for coding. With Dynamic Rows, admins keep data updated and workflows smooth.

How to Create Dynamic Rows Components in Magento 2?

Step 1: Create Module BSS_DynamicRows

Create the module folder app/code/Bss/DynamicRows.

Register the module by adding a registration.php file:

\Magento\Framework\Component\ComponentRegistrar::register(

`\Magento\Framework\Component\ComponentRegistrar::MODULE,`

`'Bss_DynamicRows',`

`__DIR__`

);

Define the module configuration in etc/module.xml:

<?xml version="1.0" encoding="UTF-8"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">

`<module name="Bss_DynamicRows" setup_version="1.0.0"/>`

</config>

Step 2: Create a Model and Database

Define the Database Table: In Setup/InstallSchema.php, define the table structure with columns row_id, row_name, birthday, sex, and position:

namespace Bss\DynamicRows\Setup;

use Magento\Framework\Setup\InstallSchemaInterface;

use Magento\Framework\Setup\ModuleContextInterface;

use Magento\Framework\Setup\SchemaSetupInterface;

use Magento\Framework\DB\Ddl\Table as Table;

class InstallSchema implements InstallSchemaInterface {

`public function install(SchemaSetupInterface $setup, ModuleContextInterface $context) {`

    `$installer = $setup;`

    `$installer->startSetup();`

    `$table = $installer->getConnection()->newTable($installer->getTable('bss_dynamic_rows'))`

        `->addColumn('row_id', Table::TYPE_INTEGER, null, ['identity' => true, 'nullable' => false, 'primary' => true], 'ID')`

        `->addColumn('row_name', Table::TYPE_TEXT, null, ['nullable' => false], 'Row Name')`

        `->addColumn('birthday', Table::TYPE_DATE, null, ['nullable' => false], 'Date of birth')`

        `->addColumn('sex', Table::TYPE_SMALLINT, null, ['nullable' => false], 'Sex')`

        `->addColumn('position', Table::TYPE_INTEGER, null, ['nullable' => false], 'Position')`

        `->setComment('Bss Dynamic Rows');`

    `$installer->getConnection()->createTable($table);`

    `$installer->endSetup();`

`}`

}

Create Model: Define DynamicRows.php in Model to represent each dynamic row:

namespace Bss\DynamicRows\Model;

use Magento\Framework\Model\AbstractModel;

class DynamicRows extends AbstractModel {

`const CACHE_TAG = 'bss_dynamic_rows';`

`protected $_cacheTag = 'bss_dynamic_rows';`

`protected $_eventPrefix = 'bss_dynamic_rows';`

`protected function _construct() {`

    `$this->_init('Bss\DynamicRows\Model\ResourceModel\DynamicRows');`

`}`

}

Create Resource Model: In Model/ResourceModel/DynamicRows.php, define _construct and deleteDynamicRows() to delete all records.

namespace Bss\DynamicRows\Model\ResourceModel;

use Magento\Framework\Model\ResourceModel\Db\AbstractDb;

class DynamicRows extends AbstractDb {

`protected function _construct() {`

    `$this->_init('bss_dynamic_rows', 'row_id');`

`}`

`public function deleteDynamicRows() {`

    `$connection = $this->getConnection();`

    `$connection->delete($this->getMainTable(), ['row_id > ?' => 0]);`

`}`

}

Create Collection: In Model/ResourceModel/DynamicRows/Collection.php, set up a collection class:

namespace Bss\DynamicRows\Model\ResourceModel\DynamicRows;

use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;

class Collection extends AbstractCollection {

`protected $_idFieldName = 'row_id';`

`protected function _construct() {`

    `$this->_init('Bss\DynamicRows\Model\DynamicRows', 'Bss\DynamicRows\Model\ResourceModel\DynamicRows');`

`}`

}

Step 3: Create Controller

Define Menu: In etc/adminhtml/menu.xml, create a menu entry for Dynamic Rows:

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Backend:etc/menu.xsd">

`<menu>`

    `<add id="Bss_DynamicRows::dynamic_rows" title="Dynamic Rows" module="Bss_DynamicRows" sortOrder="99" action="bss/row/index/scope/stores" parent="Magento_Backend::system_convert" resource="Bss_DynamicRows::dynamic_rows"/>`

`</menu>`

</config>

Set Permissions: In etc/acl.xml, define access permissions for Dynamic Rows:

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Acl/etc/acl.xsd">

`<acl>`

    `<resources>`

        `<resource id="Magento_Backend::admin">`

            `<resource id="Magento_Backend::system">`

                `<resource id="Magento_Backend::convert">`

                    `<resource id="Bss_DynamicRows::dynamic_rows" title="Dynamic Rows"/>`

                `</resource>`

            `</resource>`

        `</resource>`

    `</resources>`

`</acl>`

</config>

Declare Routes: In etc/adminhtml/routes.xml, declare the routing configuration:

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">

`<router id="admin">`

    `<route id="bss" frontName="bss">`

        `<module name="Bss_DynamicRows"/>`

    `</route>`

`</router>`

</config>

Create Controller to Display Form: In Controller/Adminhtml/Row/Index.php, display the UI form:

namespace Bss\DynamicRows\Controller\Adminhtml\Row;

use Magento\Framework\Controller\ResultFactory;

class Index extends \Magento\ImportExport\Controller\Adminhtml\Export\Index {

`public function execute() {`

    `$resultPage = $this->resultFactory->create(ResultFactory::TYPE_PAGE);`

    `$resultPage->setActiveMenu('Bss_DynamicRows::dynamic_rows');`

    `$resultPage->getConfig()->getTitle()->prepend(__('Dynamic Rows'));`

    `$resultPage->addBreadcrumb(__('Dynamic Rows'), __('Dynamic Rows'));`

    `return $resultPage;`

`}`

`protected function _isAllowed() {`

    `return $this->_authorization->isAllowed('Bss_DynamicRows::dynamic_rows');`

`}`

}

Step 4: Create UI Form

Define UI Form: In view/adminhtml/ui_component/dynamic_rows.xml, define fields (row_id, row_name, birthday, sex, position) and buttons:

<?xml version="1.0" encoding="UTF-8"?>

<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">

`<argument name="data" xsi:type="array">`

    `<item name="js_config" xsi:type="array">`

        `<item name="provider" xsi:type="string">dynamic_rows.dynamic_rows_data_source</item>`

    `</item>`

    `<item name="config" xsi:type="array">`

        `<item name="namespace" xsi:type="string">dynamic_rows</item>`

    `</item>`

`</argument>`

`<dataSource name="dynamic_rows_data_source">`

    `<argument name="dataProvider" xsi:type="configurableObject">`

        `<argument name="class" xsi:type="string">Bss\DynamicRows\Model\DataProvider</argument>`

    `</argument>`

`</dataSource>`

`<fieldset name="dynamic_rows_set">`

    `<container name="dynamic_rows_container">`

        `<field name="row_id">`

            `<argument name="data" xsi:type="array">`

                `<item name="config" xsi:type="array">`

                    `<item name="visible" xsi:type="boolean">false</item>`

                `</item>`

            `</argument>`

        `</field>`

        `<field name="row_name">`

            `<argument name="data" xsi:type="array">`

                `<item name="config" xsi:type="array">`

                    `<item name="label" xsi:type="string" translate="true">Name</item>`

                `</item>`

            `</argument>`

        `</field>`

    `</container>`

`</fieldset>`

</form>

Add Save Button: In Block/Adminhtml/DynamicRows/Edit/SaveButton.php, add a save button:

namespace Bss\DynamicRows\Block\Adminhtml\DynamicRows\Edit;

use Magento\Framework\View\Element\UiComponent\Control\ButtonProviderInterface;

class SaveButton implements ButtonProviderInterface {

`public function getButtonData() {`

    `$url = $this->getUrl('bss/row/save');`

    `return [`

        `'label' => __('Save Rows'),`

        `'class' => 'save primary',`

        `'on_click' => "setLocation('". $url ."')",`

    `];`

`}`

}

Step 5: Create an Action to Save the Data

Create Save Controller: In Controller/Adminhtml/Row/Save.php, handle form submission and save data to the database:

namespace Bss\DynamicRows\Controller\Adminhtml\Row;

class Save extends \Magento\Backend\App\Action {

`protected $dynamicRow;`

`protected $dynamicRowResource;`

`public function __construct(`

    `\Magento\Backend\App\Action\Context $context,`

    `\Bss\DynamicRows\Model\DynamicRowsFactory $dynamicRowFactory,`

    `\Bss\DynamicRows\Model\ResourceModel\DynamicRowsFactory $dynamicRowResource`

`) {`

    `parent::__construct($context);`

    `$this->dynamicRow = $dynamicRowFactory;`

    `$this->dynamicRowResource = $dynamicRowResource;`

`}`

`public function execute() {`

    `try {`

        `$dynamicRowResource = $this->dynamicRowResource->create();`

        `$dynamicRowData = $this->getRequest()->getParam('dynamic_rows_container');`

        `$dynamicRowResource->deleteDynamicRows();`

        `if (is_array($dynamicRowData) && !empty($dynamicRowData)) {`

            `foreach ($dynamicRowData as $dynamicRowDatum) {`

                `$model = $this->dynamicRow->create();`

                `unset($dynamicRowDatum['row_id']);`

                `$model->addData($dynamicRowDatum);`

                `$model->save();`

            `}`

        `}`

        `$this->messageManager->addSuccessMessage(__('Rows have been saved successfully'));`

    `} catch (\Exception $e) {`

        `$this->messageManager->addErrorMessage(__($e->getMessage()));`

    `}`

    `$this->_redirect('*/*/index/scope/stores');`

`}`

`protected function _isAllowed() {`

    `return $this->_authorization->isAllowed('Bss_DynamicRows::dynamic_rows');`

`}`

}

Different Options in Dynamic Rows Component

Option Description Type Default
template Defines the path to the main component’s HTML Magento template. String ui/dynamic-rows/templates/default
recordTemplate Sets the template path for each record row displayed in the component. String record
defaultRecord Displays a default row when there’s no existing data. Boolean false
addButton Shows a button for adding new rows. Boolean -
addButtonLabel Defines the label text for the "Add" button. String 'Add'
columnsHeader Toggles display of column headers. Boolean true
columnsHeaderClasses Adds custom classes to column headers if they are enabled. String ''
collapsibleHeader Enables the collapsible function for the header when column headers are visible. Boolean false
deleteProperty Adds a delete marker to a record’s data object when deletion is enabled. String 'delete'
deleteValue Activates the delete marker for records marked as deleted. Boolean false
dndConfig Configures drag-and-drop options for dynamic rows. Object {enabled: true}
additionalClasses Adds custom CSS classes to the component's DOM structure. Object {}
pageSize Sets the number of records per page displayed in the component. Number 20
currentPage Defines the current page number in paginated records. Number 1
disabled Sets the component’s initial state to disabled, blocking user interactions. Boolean false
fallbackResetTpl Specifies the HTML template path for the fallback reset button. String ui/form/element/helper/fallback-reset-link
identificationProperty Adds a unique identifier property for each record in the data object. String 'record_id'
visible It controls initial visibility and hides components if set to false. Boolean true
component Specifies the JavaScript constructor path used by RequireJS for the component. String Magento_Ui/js/dynamic-rows/dynamic-rows

Benefits of Using Dynamic Rows in System Configuration in Magento 2

1. Efficient Record Management

  • Add and edit records directly in the admin panel.

  • Modify multiple records without navigating away.

  • Reorder records to reflect business needs instantly.

  • Manage data changes in real time.

  • Avoid errors with individual record editing.

2. Simplified Data Organization

Simplified Data Organization via Dynamic Rows Components in Magento 2

  • Sort and arrange rows for easy access.

  • Use drag-and-drop for flexible record management.

  • Enable collapsible headers for a cleaner layout.

  • Set custom classes to enhance organization.

  • Apply columns header for better data visibility.

3. Improved Usability

  • Add buttons to streamline row additions.

  • Provide custom labels to guide admin actions.

  • Include default records for a quick start.

  • Toggle visibility of unnecessary rows.

  • Use responsive templates for a consistent UI.

4. Enhanced Customization

  • Configure templates to match specific needs.

  • Use custom classes to style rows uniquely.

  • Adjust page size for efficient data viewing.

  • Customize identification properties for each row.

  • Define default record templates for uniformity.

5. Optimized Performance

  • Load only visible rows to improve speed.

  • Paginate rows to prevent data overload.

  • Minimize database load with efficient record handling.

  • Disable components when not needed to conserve resources.

  • Delete unused rows for cleaner data management.

6. Flexible Permissions and Access Control

Flexible Permissions via Dynamic Rows Components in Magento 2

  • Set permissions for individual components.

  • Restrict access to sensitive records.

  • Configure admin roles for controlled data editing.

  • Customize visibility based on user roles.

  • Add secure data management options with permission settings.

7. Intuitive User Interface

  • Drag-and-drop functionality for easy reordering.

  • Provide action buttons like save and delete.

  • Display tooltips for easier understanding.

  • Enable fallback reset options for quick default restores.

  • Ensure clear, simple navigation within records.

Troubleshooting Common Issues with Dynamic Rows Components in Magento 2

Issue Solution
Rows Not Displaying Enable the Dynamic Rows component in the configuration. Verify data source settings are correct. Set page size and visibility to display rows. Ensure template paths are accurate.
Add Button Not Working Set addButton to true in the settings. Confirm JavaScript dependencies are loading. Define addButtonLabel to show the label. Check the browser console for JavaScript errors.
Drag-and-Drop Not Functioning Enable dndConfig settings. Ensure JavaScript components for drag-and-drop load properly. Verify template path for drag-and-drop. Check for conflicting scripts.
Records Not Saving Ensure the Save button is active in the UI. Verify the DataProvider setup for data handling. Check permissions in ACL to allow saving. Inspect server logs for errors.
Delete Function Not Working Assign deleteProperty in settings correctly. Set deleteValue to true to enable deletion. Verify permissions allow delete actions. Include the delete template in the component.
Rows Not Sorting Properly Check drag-and-drop configuration. Ensure position property exists in the database. Verify sorting order saves correctly. Review component configurations for conflicts.
Collapsible Header Not Responding Enable collapsibleHeader in settings. Ensure column headers are visible. Check for JavaScript errors affecting the collapsible feature. Ensure no CSS overrides disable it.
Pagination Not Displaying Correctly Set pageSize correctly for the data. Confirm currentPage value is accurate. Align pagination settings with layout. Check if page load speeds affect pagination.
Fields Not Editable Set disabled option to false to allow edits. Define identificationProperty correctly. Check ACL for permissions blocking edits. Confirm JavaScript components load for editing.
Template Not Loading Set the template path correctly. Clear Magento cache after changes. Ensure the template file is in the specified directory. Check for RequireJS errors.

FAQs

1. What are Dynamic Rows Components in Magento 2?

Dynamic Rows components help in adding and managing rows in Magento 2 admin easily. Admins can reorder, edit, or delete records without coding. They enhance flexibility in the UI component and make record management faster.

2. How can I add Dynamic Rows in System Configuration in Magento 2?

To add dynamic rows to the system configuration of Magento 2, set up the Bss_DynamicRows module. Define your rows in PHP namespace with properties like row_id and row_name. It allows easier row management for admins.

3. What benefits do Dynamic Rows provide in the Magento 2 Admin?

Dynamic rows in admin allow individual record editing, reducing errors. With drag-and-drop reordering and default records, they improve efficiency and workflow. Adobe Commerce users also benefit from streamlined admin management.

4. How do you register the PHP Namespace for Dynamic Rows in Magento 2?

Register the PHP namespace by creating registration.php and module.xml in app/code/Bss/DynamicRows. Use Bss\DynamicRows\Model for each dynamic row. This namespace setup is required for Magento to recognize the module.

5. What permissions are needed to manage Dynamic Rows in Magento 2 Admin?

Set permissions in acl.xml for dynamic rows in admin. Configure roles for secure data access and ensure user-specific access in Adobe Commerce and Magento Open Source. It, with dedicated Magento hosting, lets admins control sensitive records.

6. Why use Dynamic Rows UI Components in Magento 2?

Dynamic Rows UI components simplify data organization in Magento 2. They allow flexible customization with options like template paths, custom classes, and pagination. This setup makes managing complex data quicker and more efficient.

CTA

Summary

Dynamic Rows Components in Magento 2 simplify record management. Admins can edit, add, and reorder data with ease. Key benefits are:

  • Efficient Data Handling: Add and manage records fast.

  • Flexible Customization: Tailor views with UI components.

  • Easy Navigation: Use drag-and-drop for simple ordering.

  • Improved Workflow: Edit records individually to avoid errors.

  • Secure Access: Control data with custom permissions.

Consider managed Magento hosting to accurately configure dynamic rows components in Magento stores.

Shivendra Tiwari
Shivendra Tiwari
Technical Writer

Shivendra has over ten years of experience creating compelling content on Magento-related topics. With a focus on the Magento community, he shares valuable tips and up-to-date trends that provide actionable insights.


Get the fastest Magento Hosting! Get Started