WYSIWYG Editor: A How-to

Last modified by HumanBeing on Fri, June 25, 2010 10:32
Source|Old Revisions  

This is an old revision of the document!


Introduction

As of version 1.0 there is still no WYSIWYG functionality turned on by default in Magento. WYSIWYG editors are a convenient way to add content to products, content pages, and categories. WYSIWYGs also have the added advantage of being more human-readable.

That being said, there is a WYSIWYG editor installed with Magento: TinyMCE, developed by MoxieCode. If you’re not a big fan of TinyMCE or just want to try something new, you can also easily install and run FCKeditor.

TinyMCE

Since all the files are already there, TinyMCE is a snap to get up and running. The only drawback is that TinyMCE doesn’t work for Category description fields.

You may need to download the files from http://tinymce.moxiecode.com/download.php first and upload to your Magento installation. Use the directory /js/tiny_mce/ (take the directory tinymce/jscripts/tiny_mce/ from downloaded archive).

Getting it working

This wiki text does not work for latest version 1.1.4. Don’t bother. Added by firespire This wiki text works on the product page for latest version 1.1.6. Go ahead and try it.

Insert this code into the pages containing the textarea elements you wish to attach the WYSIWYG to. Make sure the path to the .js file is correct as well as the elements used in the tinyMCE init function.

Where to insert it
  • For products, add the code around line 54 (line 49 on 1.1.1) of app/design/adminhtml/defaut/default/template/catalog/product/edit.phtml. Then change the path to the javascript file in the code below to match your setup.
<script language="javascript" type="text/javascript" src="<?php echo $this->getJsUrl('tiny_mce/tiny_mce.js') ?>"></script>
<script language="javascript" type="text/javascript">
Event.observe(window, 'load', function() {
    tinyMCE.init({
        mode : "exact",
        theme : "advanced",
        strict_loading_mode : true, 
        elements : "description,short_description",
        theme_advanced_toolbar_location : "top",
        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 : "false",
        force_br_newlines : "true",
        doctype : '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'
    });  
});

</script>

  • For the CMS edit the function getElementHtml() around line 45 of lib/Varien/Data/Form/Element/Editor.php. The updated function:
    public function getElementHtml()
    {
        if( $this->getWysiwyg() === true )
        {
            $element = ($this->getState() == 'html') ? '' : $this->getHtmlId();

            $html = '
                <textarea name="'.$this->getName().'" title="'.$this->getTitle().'" id="'.$this->getHtmlId().'" class="textarea '.$this->getClass().'" '.$this->serialize($this->getHtmlAttributes()).' >'.$this->getEscapedValue().'</textarea>
        <script language="javascript" type="text/javascript" src="/js/tiny_mce/tiny_mce.js"></script>
        <script language="javascript" type="text/javascript">
        Event.observe(window, "load", function() {
            tinyMCE.init({
                mode : "exact",
                theme : "advanced",
                strict_loading_mode : true,
                elements : "'.$this->getHtmlId().'",
                theme_advanced_toolbar_location : "top",
                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 : "false",
                force_br_newlines : "true",
                doctype : "<!DOCTYPE html PUBLIC \\"-//W3C//DTD XHTML 1.0 Strict//EN\\" \\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\\">"
            });  
        });
        
        </script>';

            $html.= $this->getAfterElementHtml();
            return $html;
        }
        else
        {
            return parent::getElementHtml();
        }
    }

Remember to check the path to the js file. The getElementHtml function also has an if statement so the code you’ve added won’t be executed unless you change the field type to WYSIWYG.

        if( $this->getWysiwyg() === true)

You can do this in /magento/app/code/core/Mage/Adminhtml/Block/Cms/Page/Edit/Tab/Main.php, near the bottom:

        $fieldset->addField('content', 'editor', array(
            'name'      => 'content',
            'label'     => Mage::helper('cms')->__('Content'),
            'title'     => Mage::helper('cms')->__('Content'),
            'style'     => 'width:98%; height:600px;',
            'wysiwyg'   => true,
            'required'  => true,
        ));

When you get it working, TinyMCE should look like this:  TinyMCE in action

You can change width and height of the editor in /magento/skin/adminhtml/.../.../boxes.css in line 405 and 406 (v1.1.1). TinyMCE has a nice features that allows to change the size of the editor on the fly, so this is not absolutely needed.

FCKeditor

Where to get it

You can download FCKEditor from the FCKeditor website

How to install it

You can unzip the fckeditor folder wherever you like, however the best places for it are your Magento install’s root or inside the js folder.

Getting it working

To call FCKeditor on any page, insert the following code.

<script type="text/javascript" src="<?php echo $this->getJsUrl('fckeditor/fckeditor.js') ?>"></script>
<script type="text/javascript">
window.onload = function()
{
var oFCKeditor = new FCKeditor( 'id_of_element_where_you_want_to_attach_fckeditor' ) ;
oFCKeditor.BasePath = "path/to/fckeditor/" ;
oFCKeditor.ReplaceTextarea() ;
}
</script>

This is what FCKeditor looks like on the category page without any customization:  FCKeditor in action

Getting it working with CMS pages

Go in /app/code/core/Mage/Adminhtml/Block/CMS/Page/Edit/Tab/Main.php and modify

        $fieldset->addField('content', 'editor', array(
            'name'      => 'content',
            'label'     => Mage::helper('cms')->__('Content'),
            'title'     => Mage::helper('cms')->__('Content'),
            'style'     => 'width: 98%; height: 600px;',
            'wysiwyg'   => false,
            'required'  => true,
        ));

by

        $fieldset->addField('content', 'editor', array(
            'name'      => 'content',
            'label'     => Mage::helper('cms')->__('Content'),
            'title'     => Mage::helper('cms')->__('Content'),
            'style'     => 'width: 98%; height: 600px;',
            'wysiwyg'   => true,
            'required'  => true,
        ));

Go in /lib/Varien/Data/Form/Element/Editor.php and replace $html = ‘...’; by

            $html = '<textarea name="'.$this->getName().'" title="'.$this->getTitle().'" id="'.$this->getHtmlId().'" class="textarea '.$this->getClass().'" '.$this->serialize($this->getHtmlAttributes()).' >'.$this->getEscapedValue().'</textarea>
               <script type="text/javascript" src="/js/fckeditor/fckeditor.js"></script>
               <script type="text/javascript">
                   window.onload = function() {
                       var oFCKeditor = new FCKeditor( "' . $element .'" ) ;
                       oFCKeditor.BasePath = "/js/fckeditor/" ;
                       oFCKeditor.ReplaceTextarea() ;
                   }
               </script>';

Without touching the core files

These are workarounds so you dont have to touch the core files of Magento.

Method 1:

Add the code around line 12 of “app/design/adminhtml/default/default/template/page/head.phtml”.

After:

<script type="text/javascript">
    var BLANK_URL = '<?php echo $this->getJsUrl() ?>blank.html';
    var BLANK_IMG = '<?php echo $this->getJsUrl() ?>spacer.gif';
    var BASE_URL = '<?php echo $this->getUrl('*') ?>';
    var SKIN_URL = '<?php echo $this->getSkinUrl() ?>';
</script>

Code:

<?
if(stristr($_SERVER["REQUEST_URI"], 'cms_page/edit') == true or stristr($_SERVER["REQUEST_URI"], 'cms_page/new') == true) {
?>
<script type="text/javascript" src="/js/fckeditor/fckeditor.js"></script>
<script type="text/javascript">
    window.onload = function(){
        var oFCKeditor = new FCKeditor( 'page_content' ) ;
            oFCKeditor.BasePath = "/js/fckeditor/" ;
            oFCKeditor.Height    = 300 ;
            oFCKeditor.Width    = 600 ;
            oFCKeditor.ReplaceTextarea() ;
    }
</script>
<? }?>
Method 2:

Insert the following code into magento/app/design/adminhtml/default/default/template/page/head.phtml:

<script type="text/javascript" src="http://www.yoursite.com/js/fckeditor/fckeditor.js"></script>
<script type="text/javascript">
window.onload = function()
{
    if(document.getElementById('description')){
        if(document.getElementById('description').value == ''){
            document.getElementById('description').value = "<p>Enter description</p>";
            document.getElementById('short_description').value = "<p>Enter short description</p>";
        }
        var oFCKeditor = new FCKeditor( 'description' );
        oFCKeditor.BasePath = "http://www.yoursite.com/js/fckeditor/";
        oFCKeditor.ReplaceTextarea();
        
        var pFCKeditor = new FCKeditor( 'short_description' ) ;
        pFCKeditor.BasePath = "http://www.yoursite.com/js/fckeditor/" ;
        pFCKeditor.ReplaceTextarea() ;
        }
    
    
    if(document.getElementById('_generaldescription')){
        if(document.getElementById('_generaldescription').value == ''){
                document.getElementById('_generaldescription').value = "<p>Enter category description</p>";
            }
        var qFCKeditor = new FCKeditor( '_generaldescription');
        qFCKeditor.BasePath = "http://www.yoursite.com/js/fckeditor/";
        qFCKeditor.ReplaceTextarea();
    }
    
    if(document.getElementById('page_content')){
        if(document.getElementById('page_content').value == ''){
                document.getElementById('page_content').value = "<p>Enter CMS content</p>";
            }
        var rFCKeditor = new FCKeditor( 'page_content');
        rFCKeditor.BasePath = "http://www.yoursite.com/js/fckeditor/";
        rFCKeditor.ReplaceTextarea();
    }
}
</script>
Method 3:

Insert the following code into magento/app/design/adminhtml/default/default/template/page/head.phtml: Start on the ?> line and insert this

$baseUrl = $this->getJsUrl("fckeditor");
$server = $_SERVER['SERVER_NAME'];
$basePath = substr($baseUrl,stripos($baseUrl,$server) + strlen($server));
?>

<script type="text/javascript" src="<?php echo $baseUrl; ?>/fckeditor.js"></script>

<script type="text/javascript">

  Event.observe(window, 'load', function() {
    winOb = $$('textarea');
    winOb.each( function(item) {
      var nbutton = document.createElement('a');
      nbutton.innerHTML="Rich Edit";
      item.up(1).appendChild(nbutton);
      Event.observe(nbutton,"click", function() {
        nbutton.hide();
        var oFCKeditor = new FCKeditor( item.id );
        oFCKeditor.BasePath = "<?php echo $basePath; ?>/";
        oFCKeditor.ReplaceTextarea();
        return false;
      });
    });
  });

</script>

Benefits: All text areas in the admin area will have now have a “Rich Text” link beside them. Clicking this link will invoke the fckeditor for this fields.

Make it BIGGER

For magento 1.0 release for WYSIWYG on CMS, replace in skin/adminhtml/default/default/boxes.css:

columns .form-list td.value             { width:auto; padding-right:5px; }

by

/* @hack FCKEditor */
.columns .form-list td.value             { width:270px; padding-right:5px; }
#page_tabs_main_section_content  td.value  { width:100%; padding-right:5px; }

You can optionally replace in /js/fckeditor/fckeditor.js :

    this.Height            = height        || '200' ;

by

    this.Height            = height        || '600' ;

For earlier releases:

Add the following code in skin/adminhtml/default/default/boxes.css:

...
#_generaldescription___Frame{
width: 550px;
height: 600px;
}
...

Additional Tips and Tricks

Use fckEdit to upload images

1. Create directory to store uploaded files. I’ve created one under media/upload

2. ChMod newly created dir to 777

3. Edit connector files under /js/fckeditor/editor/filemanager/connectors/php/config.php

Change:

$Config['Enabled'] = true ;
$Config['UserFilesPath'] = '/media/upload/' ;

Description apply to Apache/PHP installation. For Windows/other look at others catalogues to find proper connector.

Unable to create new product/category/cms page?

I had a problem when creating new products, categories, and cms pages. Magento wouldn’t recognize the information enterted into FCK’s editing field. To get around this I added the following javascript, which injects some text into the textarea prior to being converted to FCKEditor.

...
if(document.getElementById('description').value == ''){
            document.getElementById('description').value = "<p>Enter description</p>";
}
...

For people, like me, which dont have any idea where to put above code theres other solution for saving new files created in fckEditor. Please look at: http://www.magentocommerce.com/boards/viewthread/7596/

In newly created pages use fckEditor build-in SAVE button first


I (dieter21) am using Magento versie 1.0.19870.4 and couldn’t get things working using the above tutorial. So here is what I did to make things work for editing CMS pages.

For some reason I didn’t had the tinyMCE folder in the js folder so I manually downloaded TinyMCE 3.1.0.1 from http://tinymce.moxiecode.com/ and put the javascript files in a selfmade /js/tiny_mce folder. (The javascript files are in the folder where the file ‘tiny_mce.js’ is located)

Change file app/code/core/Mage/Admin/html/Block/Cms/Page/Edit/Tab/Main.php and put the wysiwyg value on line 100 to true so it looks like this:

        $fieldset->addField('content', 'editor', array(
            'name'      => 'content',
            'label'     => Mage::helper('cms')->__('Content'),
            'title'     => Mage::helper('cms')->__('Content'),
            'style'     => 'width:98%; height:600px;',
            'wysiwyg'   => true,
            'required'  => true,
        ));

Change file lib/Varien/Data/Form/Element/Editor.php and replace everything between the <script>...</script> tags in the $html variable with this:

                <script language="javascript" type="text/javascript">
                tinyMCE.init({
        // General options
        mode : "textareas",
        theme : "advanced",
        plugins : "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",

        // Theme options
        theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",
        theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
        theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
        theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak",
        theme_advanced_toolbar_location : "top",
        theme_advanced_toolbar_align : "left",
        theme_advanced_statusbar_location : "bottom",
        theme_advanced_resizing : true,

        // Example content CSS (should be your site CSS)
        content_css : "http://www.your-domain.com/skin/frontend/interface/theme/css/styles.css"

        }); 
                </script>

Notice the url http://www.your-domain.com/skin/frontend/interface/theme/css/styles.css which U should replace with the correct values to see the right styles.

Change file app/design/admin/html/default/default/template/page.phtml and add the following code after line 37:

<script type="text/javascript" src="<?php echo $this->getJsUrl('tiny_mce/tiny_mce.js') ?>" language="javascript"></script>

Warning: This is not the most correct way to include the javascript, but it was the only solution I found to include it in the right place and the right way.




 

Magento 2 GitHub Repository

Magento Job Board - Some sort of tag line goes here

Latest Posts| View all Jobs