How to Add Dynamically Generated Comment for a Backend Configuration Field in Magento 2
As a Magento 2 developer, you may need to add comments in the backend configuration of extensions for the ease of admin or store owner. The extension holder might not be an expert in Magento 2 and hence such comments can guide them through the extension configuration and use.
However, in particular cases, the comments can have links to the store’s URLs to show the output or redirect the admin to check the functionality implemented in the backend.
But, these links’ paths differ from one Magento 2 store to another. The extension that you are going to develop is not necessarily going to be used for a single store only. Hence you need to add dynamically generated comment for a backend configuration field in Magento 2.
The post shows how to do so programmatically.
Method to Add Dynamically Generated Comment for a Backend Configuration Field in Magento 2:
- Create system.xml at app\code\Vendor\Extension\etc\adminhtml
1234<field id="dynamic_comment" translate="label" type="text" sortOrder="22" showInDefault="1" showInWebsite="1" showInStore="1"><label>Dynamic Comment</label><comment model="Vendor\Extension\Block\Adminhtml\System\DynamicComment" /></field> - Create DynamicComment.php at app\code\Vendor\Extension\Block\Adminhtml\System folder
123456789101112131415<?phpnamespace Vendor\Extension\Block\Adminhtml\System;use Magento\Framework\View\Element\AbstractBlock;use Magento\Config\Model\Config\CommentInterface;class DynamicComment extends AbstractBlock implements CommentInterface{public function getCommentText($elementValue){$url = $this->_urlBuilder->getUrl('dynamic/dynamic/dynamic');return "This is a <a href='$url'>Dynamically</a> Generated Comment";}}
That’s it.
I’ve implemented the above method as shown here:
Now you can fill your backend configuration with dynamic comments 😄
Feel free to post your doubts in the Comments section below and I’d be happy to help.
I’d be very grateful if you helped share this helpful post on social media to fellow developers!
Thanks!
Sanjay Jethva
Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe.
His passion for Magento 2 and Shopify solutions has made him a trusted source for businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.
3 Comments
A very useful blog, Sanjay!
Hello Radhika,
We’re glad that our solution is helpful for you
Thank You
That’s great point. I will discuss with team definitely.