• Home
  • -
  • Add wysiwyg editor (TinyMCE) in Magento Custom Module.

Add wysiwyg editor (TinyMCE) in Magento Custom Module.

In this short blog post I'm going to go through the steps on how to add a wysiwyg(TinyMCE) to a custom magento module form.

In the file app/code/local/{{module}}/{{module_name}}/Block/Adminhtml/Edit/Tab/Form.php which extends Mage_Adminhtml_Block_Widget_Form add the following method:

    /**
     * Load Wysiwyg on demand and Prepare layout
     */
    protected function _prepareLayout()
    {
        parent::_prepareLayout();
        if (Mage::getSingleton('cms/wysiwyg_config')->isEnabled()) {
            $this->getLayout()->getBlock('head')->setCanLoadTinyMce(true);
            $this->getLayout()->getBlock('head')->setCanLoadExtJs(true);
        }
    }

This allows the tinyMce setup script to be added to the page. Now in your _prepareForm() method add your new wysiwyg field.

$fieldset->addField("long_description", "editor", array(
    "label" => Mage::helper("adminhtml")->__("Long Description"),
    "class" => "required-entry",
    "required" => true,
    "style" => "height:30em",
    "name" => "long_description",
    "config"  => Mage::getSingleton('cms/wysiwyg_config')->getConfig(),
    "wysiwyg" => true,
));

You can pass paramaters to adjust the cms/wysiqyg_config @see Mage_Cms_Model_Wysiwyg_Config on line 112:

if (is_array($data)) {  
    $config->addData($data);
}

Next we need to add the the rest of the wysiwyg js files. To do this we are going to update our layout handle to use the editor layout handle. If you look at app/design/adminhtml/default/default/layout/main.xml under the editor layout handle you should be able to see that it adds all the relevant js and css files for the wysiwyg to work e.g: <action method="addJs"><script>mage/adminhtml/wysiwyg/widget.js</script></action>.

To add this to our custom module page we are going to add out own adminhtml layout file. In your module config file app/code/local/{{module}}/{{module_name}}/etc/config.xml we add the following:

 <adminhtml>
        <layout>
            <updates>
                <module_name>
                    <file>module_name.xml</file>
                </module_name>
            </updates>
        </layout>
    </adminhtml>

One you have created this file under app/design/adminhtml/default/default/layout/module_name.xml you can add the following:

<layout>  
    <adminhtml_module_edit>
        <update handle="editor" />
    </adminhtml_module_edit>
</layout>

And that's it your wysiwyg should now be working on your custom field!