Question

I try to add this HTML (<span style='color:red'>*</span>)to the content of a field with type text.

enter image description here

But the html is getting stripped. How can I allow all secure html elements but disallow unsecure elements like script?

MODULE/etc/system.xml

...
<field id="methodTitle" translate="label" type="text" sortOrder="5" showInDefault="1" showInWebsite="1" showInStore="1" canRestore="1">
    <label>Method title</label>
</field>
...
Was it helpful?

Solution

system.xml:

  <field id="methodTitle" translate="label" type="text" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1">
           <label>Method title</label>
           <comment><![CDATA[Method title comment]]></comment>
           <frontend_model>\<vendor>\<module>\Block\Test</frontend_model>
  </field>

Block: test.php (Use your own class)

<?php

namespace <vendor>\<module>\Block;

use Magento\Framework\Escaper;

class Test extends \Magento\Config\Block\System\Config\Form\Field
{
    /**
     * @var \Magento\Framework\Escaper
     */
    private $escaper;

    public function __construct(\Magento\Backend\Block\Template\Context $context, Escaper $escaper, array $data = [])
    {
        parent::__construct($context, $data);
        $this->escaper = $escaper;
    }

    protected function _getElementHtml(\Magento\Framework\Data\Form\Element\AbstractElement $element)
    {
        if ($value = $element->getData('value')) {
             $element->setData($this->escaper->escapeHtml($value)) ;
        } else {
            $element->setData(
               'value',
               $this->escaper->escapeHtml("<span style='color:red' >*</span> Pro Paket bis 31kg |Express")
            );
        }

        return parent::_getElementHtml($element);
    }
}

NOTE: If you don't need hardcoded value then remove else condition.

Output: enter image description here Hope it helps :)

OTHER TIPS

I figured out that HTML is already allowed. But there was a place in the template where the HTML is getting escaped, so I thought html is not allowed.

I am also rewriting the method getStoreConfig in the file where I am loading the settings from the system.xml to make it whitelist the tags <div><br><strong><span><b><p><h1><h2><h3><h4><h5>

protected function getStoreConfig($key, $decrypt = false)
{
    if ($decrypt) { $this->_decrypt($data); }
    $data = strip_tags(
                $this->scopeConfig->getValue($key, \Magento\Store\Model\ScopeInterface::SCOPE_STORE),
                '<div><br><strong><span><b><p><h1><h2><h3><h4><h5>'
            );

    return $data;
}

private function _decrypt(&$data)
{
    $encryptor = $this->_encryptorFactory->create();
    return $encryptor->decrypt($data);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top