M
M
Maxim Maximov2015-03-22 16:54:31
Zend Framework
Maxim Maximov, 2015-03-22 16:54:31

How to replace the default escapeHtmlHelper on a form (textarea element) in zf2?

Good afternoon! I want to implement the ability to show code in the html view. Accordingly, in order to edit the code, you need to allow tags in the form as well. Haven't found any standard ways to replace the default html escaping form helper with htmlPurifier to allow certain tags. I decided to override the method in the FormTextarea class

public function render(ElementInterface $element)
    {
        $name   = $element->getName();
        if (empty($name) && $name !== 0) {
            throw new Exception\DomainException(sprintf(
                '%s requires that the element has an assigned name; none discovered',
                __METHOD__
            ));
        }

        $attributes         = $element->getAttributes();
        $attributes['name'] = $name;
        $content            = (string) $element->getValue();
        
        $escapeHtml         = $this->getEscapeHtmlHelper();

        return sprintf(
            '<textarea %s>%s</textarea>',
            $this->createAttributesString($attributes),
            $escapeHtml($content)
        );
    }

Do I understand correctly what needs to be done here?
$escapeHtml         = $this->getEscapeHtmlHelper();

Is there any standard way? And first you need to create an HTMLPurifier object with all the settings. Where to do it? Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
C
Cat Anton, 2015-03-22
@micromax

namespace Application\View\Helper;

use Zend\View\Helper\AbstractHelper;
use Zend\Form\View\Helper\FormTextarea;
use Zend\Form\ElementInterface;

use HTMLPurifier;
use HTMLPurifier_Config;
use HTMLPurifier_ConfigSchema;
use Soflomo\Purifier\View\Helper\Purifier;

use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorAwareTrait;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\ServiceManager\AbstractPluginManager;

class PurefierFormTextarea extends FormTextarea implements ServiceLocatorAwareInterface
{
    protected $serviceLocator = null;

    public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
    {
        $this->serviceLocator = $serviceLocator;
        return $this;
    }

    public function getServiceLocator()
    {
        return $this->serviceLocator;
    }

    public function getMainServiceLocator()
    {
        if ($this->serviceLocator instanceof AbstractPluginManager) {
            return $this->serviceLocator->getServiceLocator();
        }
        return $this->serviceLocator;
    }

    public function render(ElementInterface $element)
    {
        // ...

        $this->getMainServiceLocator()->get('HTMLPurifier'); 

        // ...
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question