Magento2 Dynamic System->Configuration Comments
-
12-12-2019 - |
Frage
In Magento 1.x you could have dynamic comments on system->configuration
fields by declaring your field in system.xml
like this:
<field_code_here translate="label">
<label>Label Here</label>
<frontend_type>text</frontend_type>
<sort_order>10</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
<comment>
<model>[module]/field_comment</model><!-- this made it dynamic -->
</comment>
</field_code_here>
Then you just need to create the [Namespace]/[Module]/Model/Field/Comment.php
file with this content:
class [Namespace]_[Module]_Model_Field_Comment
{
public function getCommentText() //the method has to be named getCommentText
{
//do some calculations here
return 'Some string based on the calculations';
}
}
This way the field would have as comment what the getCommentText
method from above returned.
Is there an alternative for Magento 2? It seams that I cannot attach a model to a comment tag. The system.xml
is not validated by Magento/Backend/etc/system_file.xsd
if I do.
Lösung
[EDIT]
In the latest magento version this is possible in a similar way as in M2. I fixed it :)
[Original Answer]
It seams that this feature is partially implemented in Magento 2. It doesn't work yet.
In the code that generates the configuration form there is the method Magento\Backend\Model\Config\Structure\Element\Field::getComment
:
public function getComment($currentValue = '')
{
$comment = '';
if (isset($this->_data['comment'])) {
if (is_array($this->_data['comment'])) {
if (isset($this->_data['comment']['model'])) {
$model = $this->_commentFactory->create($this->_data['comment']['model']);
$comment = $model->getCommentText($currentValue);
}
} else {
$comment = parent::getComment();
}
}
return $comment;
}
This method should handle the case when the comment is generated by a model, but the validation schema does not allow a model
tag inside the comment tag because the comment is defined like this:
<xs:element name="comment" type="xs:string" />