In Magento 1 I used the code below for value:

value="<?php echo $this->escapeHtml($this->getDefaultValue()) ?>

How could I set this code in Magento 2?


5 Answers 5

 * Escaper
 * @var \Magento\Framework\Escaper
protected $_escaper;

public function __construct(
\Magento\Framework\Escaper $_escaper
) {

Now you can easily use escapeHtml by

$this->_escaper->escapeHtml($data, $allowedTags);

Or If you are using any block or .phtml file then you can use this by

<?= $block->escapeHtml($block->getDefaultValue()); ?>

EDIT[As per requested]

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$escaper = $objectManager->create('Magento\Framework\Escaper')->escapeHtml($data);
  • thanks for reply how i use with object method in my template file Jan 23, 2017 at 13:38
  • I have updated my answer @Rahulocodewire
    – Keyur Shah
    Jan 23, 2017 at 13:42
  • thank you its work can you tell me please one thing how i load this in magento 2 $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $product = $objectManager->get('Magento\Catalog\Model\Product')->load($productId); its not work how i get the product id Jan 23, 2017 at 14:15
  • You should try with the $objectManager->create('Magento\Catalog\Model\Product')->load($‌​productId); @Rahulocodewire
    – Keyur Shah
    Jan 23, 2017 at 14:26
  • hi Keyur shah can you tell me please one thing how i get the custom option in the magento 2 this is my code $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $product = $objectManager->get('Magento\Catalog\Model\Product')->load($productId); echo count($product->getOptions()); die; foreach ($_product->getOptions() as $options) { $optionType = $options->getType(); $optionTitle = implode('_', explode(" ", $options->getTitle())); $options->getId(); Jan 24, 2017 at 5:27

With the latest version of Magento 2.4 now you can directly use $escaper variable to use class \Magento\Framework\Escaper. The $escaper local variable is available inside the any .phtml templates.

<?= $escaper->escapeHtml($block->getDefaultValue()); ?>

Read More at: XSS prevention strategies


You can use it in magento-2 like below

value="<?php echo $block->escapeHtml($block->getDefaultValue()) ?>"

Another way is to use the method "html_entity_decode"(http://php.net/manual/en/function.html-entity-decode.php) like this

echo html_entity_decode ( $_helper->productAttribute($_product, $_product->getName(), 'name') )

Since magento/framework 100.2.0 you can call escape methods using $block variable in template files.

All available escape methods can be found in \Magento\Framework\View\Element\AbstractBlock class.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.