You are here:Home»KB»Web Design»General»TinyMCE - Installation instructions
Friday, 02 December 2016 20:43

TinyMCE - Installation instructions

Written by

This article was put together for a reference manual to all of the TinyMCE settings and what they mean in real life. I nver found one example with everything configured and labelled amking developing with TinyMCE difficult so I decide to make one. It is always easier to remove setting than add them. For those who will say there is a an online manual for TinyMCE, there is, but this is difficult as a newbie to use.

Once you have your editor up and running I agree the online manual is excellent as a reference guide, my article bridges the gap.

General Plugin notes

  • Advanced Code Editor (advcode) cannot be used when using the standard code editor as they both use code in the toolbar. Advanced Code Editor is a premium plugin.
  • Some plugins have associated buttons that need to be added to the 'Toolbar:' option in the 'Editor Appearance' section.
  • Code Sample Plugin (codesample) - You need to add prism.js and prism.css to a page for syntax highlighting to work.

Excluded Plugins

These plugins have been excluded from my examples for the reasons listed.

  • All Premium Plugins - Because they are paid for and I do not have a subscription.
  • Full Page Plugin (fullpage) this has been removed because it adds <!DOCTYPE html> <html> <head> and <body> etc.. to the textarea. Toolbar item has also been removed.
  • BBCode Plugin (bbcode) is removed because you sacrifice quite a lot of TinyMCE's functionality and since BBCode format doesn't support the whole HTML specification a lot of the HTML gets stripped.
  • Legacy Output Plugin (legacyoutput) is not used because it changes the code to an old standard for unique uses.,
  • Mentions Plugin (mentions) not added because of callback to lookup users and requires further configuration to a data source.
  • 3.x Compatibility Plugin - Is added by another Javascript file and not required unless you need to add old plugins which I do.

'entity_encoding' setting notes

This option controls how entities/characters get processed by TinyMCE. This setting can be quite confusing and it controls what characters are escaped or converted by TinyMCE. This keeps documents looking correct and can prevent some hacking opportunities.

The official documentation is here: TinyMCE | Content Filtering | entity_encoding

This option controls how entities/characters get processed by TinyMCE. The value can be set as shown in Encoding Types below. You can also mix named and numeric by setting this to "named+numeric" this way it will produce entity names of the ones found in the configured entities and numeric entities for other entities.

The base entities < > & ' and " will always be entity encoded into their named equivalents. Though ' and " will only be encoded within attribute values and < > will only be encoded within text nodes. This is correct according too the HTML and XML specs.

There are a few settings

  • named (default) 
    • Characters will be converted into named entities based on the entities option. For example, a non-breaking space could be encoded as  . This value is default.
    • It will convert characters to their named counterpart as denoted in entities and TinyMCE's internal list (i.e. &nsbp;).
    • If you do not set a type via  entity_encoding TinyMCE will use this setting by default. Character Encoding in TinyMCE – Support Center
  • numeric
    • Characters will be converted into numeric entities. For example, a non-breaking space would be encoded as &#160;
    • It will convert all characters into their numerics representations (i.e. &#160;)
  • named+numeric
    • This will convert all characters named in the entities: '' to their named counterparts (i.e. &nsbp;). and the rest into their numerics representations (i.e. &#160;).
  • raw - I think this is a less restrictive option than now having this option enabled. raw is UTF-8 with a few exceptions.

'valid_elements' / 'extended_valid_elements' setting notes

  • TinyMCE | Content Filtering | valid_elements - This will give you the syntax for construction both valid_elements and extended_valid_elements.
  • You can use these settings to enable padding of empty elements i.e. extended_valid_elements: '#p', will pad all empty <p> tags.
  • extended_valid_elements is used to add more rules without wiping out the inbuilt rules of TinyMCE.
  • A lot more than padding can be done with these settings/rules.

Custom Packages

You can build your own custom package with only the plugins you want built into a single file. This reduces file requests and can speed load times up.

By trial and error I discovered I did not save much file space by only including the plugins I wanted so i just made a custom build with all plugins inlcuded and 'combine all js files' enabled (just leave everything selected). This also has the added beneifit of making it much easier to turn plugins on or off just by using the config file.

Create a customized build with only the features you need.Make TinyMCE even smaller and tailored on your project. - TinyMCE | Build Customizer

  • The builder does not always have the latest version of TinyMCE, but it is not that far behind.

Visual Warning for Empty Submission

This is an excellent way of preventing empty forms being entered with a visual warning just by adding a CSS class to the relevant <textarea>.

The following code adds a red border to a TinyMCE editor window if it is empty when the form is submitted and also prevents the form from being submitted (POST'ed)..

You need to add this code in to your tinymce.init statement as in the examples on this page and add the class wysiwyg-checkforcontent to the relevant <textarea>.

Some configurations of TinyMCE add in <p>&nbsp;</p> when the editor has no content. This is compensated for and is therefore still classed as empty by the code below.

editor.on('submit', function(e) {

    var placeholderElement = editor.getElement(); 
    var testClass = "mceCheckForContent";
     
    if(
        placeholderElement.classList.contains(testClass) &&
        (editor.getContent() === '' ||
         
        // This section might not be required on newer versions on TinyMCE and only when padding empty tags is enabled for <p> and <div>
        editor.getContent() === '<p><\/p>' || editor.getContent() === '<p>&nbsp;<\/p>' ||
        editor.getContent() === '<div><\/div>' || editor.getContent() === '<div>&nbsp;<\/div>')
         
    ) {
        editor.getContainer().style.border = '3px solid red';
        return false;
    }

});

TinyMCE Library

You need to include this javascript file on every page you want to use the editor.

<script src="/js/tinymce/tinymce.min.js"></script>

Configurations

The following example configurations will enable TinyMCE with most of it's functions enabled. The Basic config will use all default settings whereas the Full config has all of the main options pre-configured play about with. The QWcrm config is a real life example of a config file that I use in my software QWcrm.

  • When editing these config files make sure each statement has a comma at the end of it except the last statement, this is how Javascript separates the variables.
  • Delete or comment out the options you do not want. You can delete all of the extended comments if needed which will make the code neater but harder to follow.

Basic

This is the least amount of code required to get TinyMCE to work with most of its Free Plugins, Toolbar Buttons and Context Menu Items enabled. All settings are default.

tinymce.init({   
 
    selector: 'textarea',
     
    toolbar: [      
        'newdocument undo redo | bold italic underline | alignleft aligncenter alignright alignjustify | outdent indent | bullist numlist blockquote hr charmap insertdatetime | help',
        'styleselect formatselect fontselect fontsizeselect | searchreplace spellchecker visualblocks visualchars | removeformat',
        'subscript superscript strikethrough | forecolor backcolor | ltr rtl | link unlink anchor | table image media | nonbreaking pagebreak toc codesample template emoticons',           
        'cut copy paste | save restoredraft print | preview code fullscreen'           
    ],             
    contextmenu: 'cut copy paste | image | inserttable | cell row column deletetable | link',
    plugins: [
        'advlist anchor autolink autoresize autosave charmap code codesample colorpicker',
        'contextmenu directionality emoticons fullscreen help hr image imagetools importcss insertdatetime',
        'link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace',
        'spellchecker tabfocus table template textcolor textpattern toc visualblocks visualchars wordcount'
    ]    
   
});

Full

This is a config file with most of its FreePlugins, Toolbar Buttons and Context Menu Items enabled. Most settings are configured, the rest are default.

If you do not need anything or do not know what it is you can just remove it or coment the code out.

/**
 * @package   QWcrm
 * @author    Jon Brown https://quantumwarp.com/
 * @copyright Copyright (C) 2016 - 2017 Jon Brown, All rights reserved.
 * @license   GNU/GPLv3 or later; https://www.gnu.org/licenses/gpl.html
 */
 
tinymce.init({
      
    // https://www.tinymce.com/docs/ - TinyMCE Documentation
      
    // NB: There are many more options not covered here, these are just the main ones.
    // NB: Based on TinyMCE 4.7.12, apart from the mobile section should work on old versions as-well
      
    //// Integration and Setup ////
       
        // This option allows you to specify a CSS selector for the areas that TinyMCE should make editable.
        //selector: 'textarea',                                                                      // Select all textarea
        //selector: 'textarea.editme',                                                               // Select all textarea with the class editme
        selector : 'textarea:not(.mceNoEditor)',                                                     // Select all textarea excluding the mceNoEditor class
  
        // This option allows you to specify a URL based location of plugins outside of the normal TinyMCE plugins directory. TinyMCE will attempt to load these as per regular plugins when starting up.
        external_plugins: {
            'testing': 'http://www.testing.com/plugin.min.js',
            'maths': 'http://www.maths.com/plugin.min.js'
        },
          
    // On Submit if TinyMCE Editor is empty and has the class "wysiwyg-checkforcontent" on its placeholder, dont submit the form and put a red border around it
    setup: function(editor) {
 
        editor.on('submit', function(e) {
 
            var placeholderElement = editor.getElement(); 
            var testClass = "mceCheckForContent";
             
            if(
                placeholderElement.classList.contains(testClass) &&
                (editor.getContent() === '' ||
                 
                // This section might not be required on newer versions on TinyMCE and only when padding empty tags is enabled for <p> and <div>
                editor.getContent() === '<p><\/p>' || editor.getContent() === '<p>&nbsp;<\/p>' ||
                editor.getContent() === '<div><\/div>' || editor.getContent() === '<div>&nbsp;<\/div>')
                 
            ) {
                editor.getContainer().style.border = '3px solid red';
                return false;
            }
 
        });
    },
      
    //// Editor Appearance ////
      
        theme: 'modern',                                                                             // This option allows you to specify the theme that TinyMCE should use. The default theme included with TinyMCE is named "modern".
        skin: 'lightgray',                                                                           // This option allows you to specify the skin that TinyMCE should use. The default skin included with TinyMCE is named "lightgray"
        content_css: '/css/editor.css',                                                              // This option enables you to specify a custom CSS file that extends the theme content CSS. This CSS file is the one used within the editor (the editable area).  
          
        min_height: 500,                                                                             // This option allows you to set the minimum height that a user can stretch the entire TinyMCE interface (by grabbing the dragable area in the bottom right of the editor interface) when using the modern theme.
        min_width: 500,                                                                              // This option allows you to set the minimum width that a user can stretch the entire TinyMCE interface (by grabbing the dragable area in the bottom right of the editor interface) when using the modern theme.
        height: 300,                                                                                 // Set the height of the editable area in pixels. Note that this sets the height of the editable area only. It does not include the space required for the menubar, toolbars or status bar.
        width: 300,                                                                                  // Set the width of the editor in pixels.      
        max_height: 500,                                                                             // This option allows you to set the maximum height that a user can stretch the entire TinyMCE interface (by grabbing the dragable area in the bottom right of the editor interface) when using the modern theme.
        max_width: 500,                                                                              // This option allows you to set the maximum width that a user can stretch the entire TinyMCE interface (by grabbing the dragable area in the bottom right of the editor interface) when using the modern theme.   
        resize: false,                                                                               // This option gives you the ability to disable the resize handle or set it to resize both horizontal and vertically.
          
        statusbar: false,                                                                            // This option allows you to specify whether or not TinyMCE should display the status bar at the bottom of the editor.
        elementpath: false,                                                                          // This option allows you to disable the element path within the status bar at the bottom of the editor.
        branding: false,                                                                             // This option allows you to disable the "Powered by TinyMCE" branding.       
  
        menubar: 'file edit insert view format table tools',                                         // This option allows you to specify which menus should appear and the order that they appear in the menu bar at the top of TinyMCE. (true/false/'list').
        removed_menuitems: 'newdocument',                                                            // This option allows you to remove items from TinyMCE's drop down menus.      
  
        // Toolbar Buttons - This option allows you to specify the buttons and the order that they will appear on TinyMCE's toolbar.
        toolbar: [     
            'newdocument undo redo | bold italic underline | alignleft aligncenter alignright alignjustify | outdent indent | bullist numlist blockquote hr charmap insertdatetime | help',
            'styleselect formatselect fontselect fontsizeselect | searchreplace spellchecker visualblocks visualchars | removeformat',
            'subscript superscript strikethrough | forecolor backcolor | ltr rtl | link unlink anchor | table image media | nonbreaking pagebreak toc codesample template emoticons',          
            'cut copy paste | save restoredraft print | preview code fullscreen'          
        ],
          
    //// Content Filtering ////
      
        schema: 'html5-strict',                                                                      // The schema option enables you to switch between the HTML4 and HTML5 schema. This controls the valid elements and attributes that can be placed in the HTML.(html5, html4, html5-strict)
        entities: '160,nbsp,173,shy',                                                                // This option contains a comma separated list of entity names that is used instead of characters. Odd items are the character code and even items are the name of the character code.
        entity_encoding: 'raw',                                                                      // This option controls how entities/characters get processed by TinyMCE. (raw(UTF-8)/named/numeric)
        forced_root_block: 'p',                                                                      // This option enables you to make sure that any non block elements or text nodes are wrapped in block elements.
        valid_elements: '',                                                                          // The valid_elements option defines which elements will remain in the edited text when the editor saves. You can use this to limit the returned HTML to a subset.
        extended_valid_elements: '#p|hr[id|title|alt|class|width|size|noshade]',                     // This option is very similar to valid_elements. The only difference between this option and valid_elements is that this one gets added to the existing rule set. #p will pad empty <p> tags with &nbsp; This can help keep HTML structure.
        //This option instructs the editor to remove specific elements when TinyMCE executes a cleanup.
        invalid_elements: 'iframe,script,style,applet,body,bgsound,base,basefont,frame,frameset,head,html,id,ilayer,layer,link,meta,name,title,xml',
          
    //// Content Formatting ////
      
        fontsize_formats: '8pt 10pt 12pt 14pt 18pt 24pt 36pt',                                       // This option allows you to override the font sizes displayed in the font size select box using a space or comma separated list of font sizes
      
    //// Spelling ////
      
        browser_spellcheck: true,                                                                    // This option configures TinyMCE to use the browsers native spell checker.
          
    //// Localization ////
      
        directionality: 'ltr',                                                                       // This option allows you to set the base direction of directionally neutral text (i.e., text that doesnt have inherent directionality as defined in Unicode) within the editor.
        language: 'en_US',                                                                           // This option allows you to specify the language that TinyMCEs user interface will appear in. That is, the toolbar buttons and menu items.
    
    //// URL Handling ////
      
        document_base_url: '/quantumwarp/',                                                          // This option specifies the base URL for all relative URLs in the document. The default value is the directory of the current document.
        relative_urls: true,                                                                         // If this option is set to true, all URLs returned from the MCFileManager will be relative from the specified document_base_url.
        remove_script_host: false,                                                                   // If this option is enabled the protocol and host part of the URLs returned from the MCFileManager will be removed. This option is only used if the relative_urls option is set to false. 
      
    //// Plugin Settings ////
      
        // Autosave Plugin
        autosave_restore_when_empty: false,                                                          // This option enables you to specify if TinyMCE should automatically restore the content stored in local storage when the editor is empty on initialization.
              
        // Code Plugin
        code_dialog_height: 200,                                                                     // This configuration option sets the internal, editable area height of the code dialog box.
        code_dialog_width: 200,                                                                      // This configuration option sets the internal, editable area width of the code dialog box.
          
        // Context Menu Plugin
        contextmenu: 'cut copy paste | image | inserttable | cell row column deletetable | link',    // This plugin adds a configurable context menu that appears when a user right clicks in the editable area.
        contextmenu_never_use_native: true,                                                          // This option allows you to disable the browsers native context menu from appearing within the editor.      
  
        // Import CSS Plugin
        importcss_append: true,                                                                      // If set to true this option will append the imported styles to the end of the Format menu and will replace the default formats.
              
        // Insert Date/Time Plugin  - https://www.tinymce.com/docs/plugins/insertdatetime/
        insertdatetime_dateformat: '%Y-%m-%d',                                                       // This option allows you to override the default formatting rule for date formats inserted by the mceInsertDate command. - Default: %Y-%m-%d
        insertdatetime_formats: ['%H:%M:%S', '%Y-%m-%d', '%I:%M:%S %p', '%D'],                       // Allows you to specify a list of date/time formats to be used in the date menu or date select box. - Default: ['%H:%M:%S', '%Y-%m-%d', '%I:%M:%S %p', '%D']
        insertdatetime_timeformat: '%H:%M:%S',                                                       // This option allows you to override the default formatting rule for times inserted by the mceInsertTime command.  - Default: %H:%M:%S
        insertdatetime_element: true,                                                                // When this option is enabled HTML5 time elements gets generated when you insert dates/times.
          
        // Preview Plugin
        plugin_preview_height: 500,                                                                  // This option allows you to set the height of the preview window that appears when using the preview plugin.
        plugin_preview_width: 500,                                                                   // This option allows you to set the width of the preview window that appears when using the preview plugin.
          
        // Paste Plugin
        paste_as_text: true,                                                                         // This option enables you to set the default state of the Paste as text menu item, which is added by the paste plugin under the Edit menu dropdown. Its disabled by default.
        paste_data_images: true,                                                                     // This option specifies whether data:url images (inline images) should be removed or not from the pasted contents.
                  
        // Table of Contents Plugin - https://www.tinymce.com/docs/plugins/toc/
        toc_depth: 3,                                                                                // By default headers in the content will be inspected only three levels deep, so - H1 through H3. But it is possible to change this behaviour by setting toc_depth to any number in 1-9 range (H1 - H9).
        toc_header: 'div',                                                                           // Table of contents has a header and by default it will be marked up with H2 tag. With toc_header option you can change it to some other tag.
        toc_class: 'our-toc',                                                                        // With toc_class you can change the class name that gets assigned to the wrapper div. Please note that you will have to alter Boilerplate Content CSS accordingly. - default = 'mce-toc'
  
        // Table Plugin
        // This option allows you to specify the buttons and the order that they will appear on within TinyMCEs inline contextual toolbar for tables.
        table_toolbar: 'tableprops tabledelete | tableinsertrowbefore tableinsertrowafter tabledeleterow | tableinsertcolbefore tableinsertcolafter tabledeletecol',
  
    //// Intialise Plugins ////     
          
        // Enabled these Plugins
        plugins: [
            'advlist anchor autolink autoresize autosave charmap code codesample colorpicker',
            'contextmenu directionality emoticons fullscreen help hr image imagetools importcss insertdatetime',
            'link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace',
            'spellchecker tabfocus table template textcolor textpattern toc visualblocks visualchars wordcount'
        ]   
      
    //// Mobile ////
      
        // https://www.tinymce.com/docs/mobile/
          
        // TinyMCE mobile supports a small subset of the toolbar items supported by the main mode. The toolbar is specified in the mobile section also.
        mobile: {
            theme: 'mobile',
            plugins: [ 'autosave', 'lists', 'autolink' ],
            toolbar: [ 'undo', 'bold', 'italic', 'styleselect' ]
        }
   
});

QWcrm

This is the config file from my software QWcrm which is a nice simple setup for entering text. Only some of it'sFree Plugins, Toolbar Buttons and Context Menu Items enabled. Some settings are configured, the rest are default.

/**
 * @package   QWcrm
 * @author    Jon Brown https://quantumwarp.com/
 * @copyright Copyright (C) 2016 - 2017 Jon Brown, All rights reserved.
 * @license   GNU/GPLv3 or later; https://www.gnu.org/licenses/gpl.html
 */

tinymce.init( {
    
    selector : 'textarea:not(.mceNoEditor)',
    
    // On Submit if TinyMCE Editor is empty and has the class "wysiwyg-checkforcontent" on its placeholder, dont submit the form and put a red border around it
    setup: function(editor) {

        editor.on('submit', function(e) {

            var placeholderElement = editor.getElement();  
            var testClass = "mceCheckForContent";
            
            if(
                placeholderElement.classList.contains(testClass) &&
                (editor.getContent() === '' ||
                
                // This section might not be required on newer versions on TinyMCE and only when padding empty tags is enabled for <p> and <div>
                editor.getContent() === '<p><\/p>' || editor.getContent() === '<p>&nbsp;<\/p>' ||
                editor.getContent() === '<div><\/div>' || editor.getContent() === '<div>&nbsp;<\/div>')
                
            ) {
                editor.getContainer().style.border = '3px solid red';
                return false;
            }

        });
    },
    
    elementpath: false,
    branding: false,
    menubar: false,    
    toolbar: [       
        'undo redo | bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | outdent indent | blockquote hr charmap insertdatetime | help',
        'bullist numlist | table | link unlink | cut copy paste | removeformat | preview code fullscreen '                     
    ],    
    schema: 'html5-strict',
    invalid_elements: 'iframe,script,style,applet,body,bgsound,base,basefont,frame,frameset,head,html,id,ilayer,layer,link,meta,name,title,xml',
    browser_spellcheck: true,    
    contextmenu: 'cut copy paste | link',    
    insertdatetime_formats: ['{$date_format}', '%H:%M:%S', '%I:%M:%S %p'],    
    plugins: [
        'advlist autolink charmap code contextmenu fullscreen help hr insertdatetime link lists paste preview table textcolor visualchars'
    ]    

} );

 The curly braces are surrounded by whitespace so the Smarty Tempalte Engine does not try and parse it.

Read 1299 times Last modified on Friday, 11 May 2018 17:32