Magento – how to use tinymce to admin custom module in magento2

adminmagento2moduletinymce

I have custom module with custom-template.phtml.

i custom-template.phtml i want use tinymce for tags texarea.

i tried code.

 <input type="button" class="action-default scalable" onClick="toggleEditor()" value="Show/Hide editor" />
    <input type='button' onClick='MediabrowserUtility.openDialog(&#39<?php echo $block->getImageUrl()?>target_element_id/custom-html-data&#39)' class='scalable action-default action-add-image plugin' value='Insert Image...' />
    <textarea  rows="15" id="custom-html-data"></textarea>
    <script type="text/javascript">
    function toggleEditor() {
      if (tinyMCE.getInstanceById('custom-html-data') == null) {
        tinyMCE.init({
            mode : "exact",
            elements: "custom-html-data",
            theme_advanced_toolbar_align : "left",
            theme_advanced_path_location : "bottom",
            extended_valid_elements : "a[name|href|target|title|onclick],img[class|src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name],hr[class|width|size|noshade],font[face|size|color|style],span[class|align|style]",
            theme_advanced_resize_horizontal : 'true',
            theme_advanced_resizing : 'true',
            apply_source_formatting : 'true',
            convert_urls : 'true',
            force_br_newlines : 'true',
            width : '100%',
            min_width: 0,
            doctype : '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'
               });
      }else{
        tinymce.getInstanceById('custom-html-data').remove();
      }
   }

when i insert image it return to textare

<img src="{{media url="wysiwyg/xam-o1.png"}}" alt="" />

but when i click show/hide editor url image error.
enter image description here
enter image description here

how to use true tinymce editor in magento2 and how to fix it?
Many thanks

Best Answer

It is better not to insert that block of code directly into HTML template file, but to use Magento native way to embed field:

$fieldset->addField(
    'full_content', 'editor', array(
        'label'    => __('Full Content'),
        'required' => true,
        'config'    => $this->config->getConfig(),
        'name'     => 'full_content',
    )
);

To make this work you also need to add dependency into the constructor:

/**
 * @var \Magento\Cms\Model\Wysiwyg\Config
 */
protected $config; // <-- add this variable inside the class

public function __construct(
    \Magento\Backend\Block\Template\Context $context,
    \Magento\Framework\Registry $registry,
    \Magento\Framework\Data\FormFactory $formFactory,
    \Magento\Cms\Model\Wysiwyg\Config $config, // <-- this new line
    array $data
) {
    parent::__construct($context, $registry, $formFactory, $data);
    $this->config = $config; // <-- and this new line
}
Related Topic