Magento2 Admin – Add WYSIWYG Editor to Block Form

adminadminformblocksmagento2wysiwyg

How do you add a WYSIWYG editor to a custom form which you create through a block? I have found this article for doing this through UI components but need this for a block.

I've tried the following:

$fieldset->addField(
            'content',
            'editor',
            [
                'name' => 'content',
                'label' => __('Body'),
                'title' => __('Body'),
                'rows' => '5',
                'cols' => '30',
                'wysiwyg' => true,
                'required' => true
            ]
        );

Best Answer

Discovered I was missing the Config setting:

/**
 * @var \Magento\Cms\Model\Wysiwyg\Config
 */
protected $_wysiwygConfig;

/**
 * @param \Magento\Backend\Block\Template\Context $context
 * @param \Magento\Framework\Registry $registry
 * @param \Magento\Framework\Data\FormFactory $formFactory
 * @param \Magento\Cms\Model\Wysiwyg\Config $wysiwygConfig
 * @param \Magento\Store\Model\System\Store $systemStore
 * @param array $data
 */
public function __construct(
    \Magento\Backend\Block\Template\Context $context,
    \Magento\Cms\Model\Wysiwyg\Config $wysiwygConfig,
    array $data = []
) {
    $this->_wysiwygConfig = $wysiwygConfig;
    parent::__construct($context, $data);
}

Meaning I could do the following:

$fieldset->addField(
    'content',
    'editor',
    [
        'name' => 'content',
        'label' => __('Body'),
        'title' => __('Body'),
        'rows' => '5',
        'cols' => '30',
        'wysiwyg' => true,
        'config' => $this->_wysiwygConfig->getConfig(),
        'required' => true
    ]
);

Type must be set to editor and wysiwyg set to true for this to work.