Jan 06

Date published: 1-6-2014

Rails version: 4.0.0

Custom interface

One of my previous tutorials showed how to install and use CKEditor to give all textareas a graphical user interface. We only scratched the surface of what it’s possible to do with CKEditor, so I’m going to return to the subject and show how to customize the user interface.

The first thing we need to do is load up our previous project where we setup CKEditor. You can make a copy of the directory or create a new branch in Git, whichever you prefer. The source code for the previous tutorial can be found here:

http://github.com/wordplay/ckeditor_tutorial

The point where we need to make changes to customize the interface is the script that loads CKEditor into the textareas. Open app/views/layouts/application.html.erb, and you’ll find the script at the bottom of the file. Notice the commented line that says, “optional config.” This is where we’ll be making our changes. We’ll start with just a basic toolbar that lets us do changes like bold, italic, and strikethrough. Modify the script to look like this:

    <script type="text/javascript">
      $('textarea').ckeditor({
        // optional config
        toolbar: [
          { name: 'basicstyles', items: [ 'Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', 'RemoveFormat' ] }
        ]
      });
    </script>

Save the changes and start the Rails server. Go to the page to create a new message, and you’ll notice that all the items that used to be in the toolbar are now gone, and there is now just a small toolbar with a few options to modify the text. Try out a few of them, and also note that the last item in the list will clear any modifications to the text.

For reference, here is some example code from CKEditor’s documentation that includes all the options that could be on the toolbar:

[
    { name: 'document',    groups: [ 'mode', 'document', 'doctools' ], items: [ 'Source', 'Save', 'NewPage', 'DocProps', 'Preview', 'Print', 'Templates', 'document' ] },
    // On the basic preset, clipboard and undo is handled by keyboard.
    // Uncomment the following line to enable them on the toolbar as well.
    // { name: 'clipboard',   groups: [ 'clipboard', 'undo' ], items: [ 'Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', 'Undo', 'Redo' ] },
    { name: 'editing',     groups: [ 'find', 'selection', 'spellchecker' ], items: [ 'Find', 'Replace', 'SelectAll', 'Scayt' ] },
    { name: 'insert', items: [ 'CreatePlaceholder', 'Image', 'Flash', 'Table', 'HorizontalRule', 'Smiley', 'SpecialChar', 'PageBreak', 'Iframe', 'InsertPre' ] },
    { name: 'forms', items: [ 'Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton', 'HiddenField' ] },
    '/',
    { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ], items: [ 'Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', 'RemoveFormat' ] },
    { name: 'paragraph',   groups: [ 'list', 'indent', 'blocks', 'align' ], items: [ 'NumberedList', 'BulletedList', 'Outdent', 'Indent', 'Blockquote', 'CreateDiv', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', 'BidiLtr', 'BidiRtl' ] },
    { name: 'links', items: [ 'Link', 'Unlink', 'Anchor' ] },
    '/',
    { name: 'styles', items: [ 'Styles', 'Format', 'Font', 'FontSize' ] },
    { name: 'colors', items: [ 'TextColor', 'BGColor' ] },
    { name: 'tools', items: [ 'UIColor', 'Maximize', 'ShowBlocks' ] },
    { name: 'about', items: [ 'About' ] }
  ]

Feel free to modify the toolbar in your application to try out some of the other tools. When you’re done, continue on, and you’ll see how to add some powerful tools to be able to add divs with styles and classes and manually edit the HTML source code.

Adding divs and classes

The toolbar we’ve created is nice and simple, but now we want to add some real functionality to our editor. CKEditor has options to see the HTML source code and insert divs into the text we’re editing. Let’s add the items we need to the toolbar first. Modify the script to look like this:

    <script type="text/javascript">
      $('textarea').ckeditor({
        // optional config
        toolbar: [
          { name: 'basicstyles', items: [ 'Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', 'RemoveFormat' ] },
          { name: 'source', items: [ 'Source', 'CreateDiv' ] }
        ]
      });
    </script>

Reload the page, and you’ll see the two new items in the toolbar. Try writing some text and clicking on the DIV button. You can name a class to use or select a style. CKEditor already has a style called “Special Container” that you can use to see how it works. We don’t really want to use that style, so let’s create some custom styles of our own. We’re going to set the “stylesSet” property of CKEditor and use two styles of our own, one that is a style and one that uses a class to set the style. Modify the script to look like this:

    <script type="text/javascript">
      $('textarea').ckeditor({
        // optional config
        extraPlugins: 'stylesheetparser',

        // Stylesheet for the contents.
        contentsCss: '/assets/custom.css',

        stylesSet: [
          {
            name: 'Yellow Background',
            element: 'div',
            styles: {
              padding: '5px 10px',
              'background-color': 'Yellow',
              border: '1px solid #ccc'
            }
          },
          {
            name: 'Red Background',
            element: 'div',
            attributes: {
              'class': 'red-background'
            }
          }
        ],

        toolbar: [
          { name: 'basicstyles', items: [ 'Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', 'RemoveFormat' ] },
          { name: 'source', items: [ 'Source', 'CreateDiv' ] }
        ]
      });
    </script>

We tell CKEditor to load a plugin named “stylesheetparser” so that it will parse our CSS file to be able to show our red background in the editor. Then we tell it which CSS file we want to load and create the two styles we want to be able to use for divs. The only other thing we have to do is add the red-background class to app/assets/stylesheets/custom.css.scss:

.red-background {
  padding: 5px 10px;
  background-color: red;
  border: 1px solid #ccc;
}

That’s all the code changes we need to make. If you try to load up the page now, you’ll notice a Javascript error for stylesheetparser. This is because it is a plugin and isn’t included with CKEditor by default, which means we have to get the plugin and put it in a place where Rails will know to look for it. Download the plugin for version 4.2 here and extract it to /app/assets/javascripts/ckeditor/plugins/ then reload the page. It should load fine, and you can see that when you assign a div to be a red-background and look at the source, the div has a class assigned instead of a style.

Feel free to experiment with adding your own custom styles and modifying which icons you want to show up on your toolbar. That’s all for this tutorial. As always, the source code can be found at:

http://github.com/wordplay/ckeditor_customization

Leave a Reply

preload preload preload