For Magento Developers, System configuration allows the developer to scale Magento to meet the unique need of store owners. These kinds of handy configurations feature allow the store owner to make changes in frontend and backend just by changing backend configuration settings.
In the past, we have written several blogs for adding and customizing different fields in the backend configuration. So, let’s just take it to the next level by adding a dynamic field block to the backend configuration that works as per need means there is no fixed amount of input is fetched. Several times, it happens that customer wants to manage some complex operation from the backend like hiding shipping method or payment method for a particular customer group or to add some costs to the particular type of product, etc.
For example, we want to add some cost to the product price like faster delivery charges, gift wrapping, addon charges based on frontend customer selection, so for that purpose we need to create a dynamic field in the backend configuration as per below image.
So, our backend field path will be like this: vendor/configuration/shippingcost
Here is the code for helper file that will help you to get dynamic generated row value of system configuration in Magento 2.
<?php namespace Vendor\Extension\Helper; class Data extends \Magento\Framework\App\Helper\AbstractHelper { const Shippingcost = ' vendor/configuration/shippingcost'; protected $_storeManager; protected $serialize; public function __construct( \Magento\Framework\App\Helper\Context $context, \Magento\Store\Model\StoreManagerInterface $storeManager, \Magento\Framework\Serialize\Serializer\Json $serialize) { $this->_storeManager = $storeManager; $this->serialize = $serialize; parent::__construct($context); } public function getStoreid() { return $this->_storeManager->getStore()->getId(); } public function getProductshippingCost() { $productcostconfig = $this->scopeConfig->getValue(self:: Shippingcost,ScopeInterface::SCOPE_STORE,$this->getStoreid()); if($productcostconfig == '' || $productcostconfig == null) return; $unserializedata = $this->serialize->unserialize($productcostconfig); $productcostarray = array(); foreach($unserializedata as $key => $row) { $productcostarray[] = $row['shippingcost']; } return $productcostarray; } }
Note that $row[‘shippingcost’] is the name of field which you have specified in _prepareToRender() function of ‘frontend_model’ control file.
Tadaa! You have successfully fetched dynamic field value now you are to code more according to your need. If you found this blog helpful, don’t forget to share it with your colleagues and Magento Friends.
And, Let us know if you are facing an issue while implementing this code.
Happy Fetching!