1

Within silverstripe I've got a need to use tabs within TextareaField - currently it would navigate away from the field but I'd like it to write a tab there instead.

UPDATE Based on the comment below I've added this code...

_config.yml

TextareaField:
  extensions:
    - TextareaFieldExtension

TextareaFieldExtension.php

class TextareaFieldExtension extends DataExtension {

    public function onBeforeRender() {

        Requirements::customScript(<<<JS
            $(document).delegate('#textbox', 'keydown', function(e) {
              var keyCode = e.keyCode || e.which;

              if (keyCode == 9) {
                e.preventDefault();
                var start = $(this).get(0).selectionStart;
                var end = $(this).get(0).selectionEnd;

                // set textarea value to: text before caret + tab + text after caret
                $(this).val($(this).val().substring(0, start) + "\t" + $(this).val().substring(end));

                // put caret at right position again
                $(this).get(0).selectionStart =
                $(this).get(0).selectionEnd = start + 1;
              }
            });
JS
        );
    }
}

I know that onBeforeRender is being called as I've used a die('hello world') to check. However there is no change in the use of Tab within any TextareaField. Where am I going wrong?

Barry
  • 3,303
  • 7
  • 23
  • 42

1 Answers1

2

We can achieve this with entwine like so:

mysite/javascript/cms.js

(function($) {
    jQuery.entwine('ss', function($) {

        $('.field.textarea textarea').entwine({
            onkeydown: function(e) {
                var keyCode = e.keyCode || e.which;

                if (keyCode == 9) {
                    e.preventDefault();
                    var start = $(this).get(0).selectionStart;
                    var end = $(this).get(0).selectionEnd;

                    // set textarea value to: text before caret + tab + text after caret
                    $(this).val($(this).val().substring(0, start) + "\t" + $(this).val().substring(end));

                    // put caret at right position again
                    $(this).get(0).selectionStart = $(this).get(0).selectionEnd = start + 1;
                }
            }
        });
    });
})(jQuery);

We load this JavaScript file for all the CMS by putting this in our config yml file:

mysite/_config/config.yml

LeftAndMain:
  extra_requirements_javascript:
    - 'mysite/javascript/cms.js'
3dgoo
  • 15,716
  • 6
  • 46
  • 58
  • I put this in ModelAdmin init as it didn't' work (i.e. js code wasn't included in page source) by following this and I did dev build flush... could be my mistake... but I thought I'd comment – Barry May 14 '16 at 07:32