Take the 2-minute tour ×
Craft CMS Stack Exchange is a question and answer site for administrators, end users, developers and designers for Craft CMS. It's 100% free, no registration required.

I'm trying to add a redactor richtext field to one of my plugin templates in the CP.

I found macros for every field in craft/app/templates/_includes/forms, but a richtext macro is missing. I assume that I have to use a normal textarea-field and add some code to the controller or init()-function, but couldn't find anything by inspecting Craft's CP code.

share|improve this question

1 Answer 1

up vote 5 down vote accepted

To do this you'll need to take a few steps:

  1. Load the necessary resources which include the redactor.css and redactor.js file. And if you are using Craft's macros for your fields, the form macro file.

    {% includeCssResource "lib/redactor/redactor.css" %}
    {% includeJsResource "lib/redactor/redactor.js" %}
    
    {% import "_includes/forms" as forms %}
    
  2. Add a class to your field that you will use to initialize your Redactor toolbar. Here's a simplified textarea macro:

    {{ forms.textareaField({
        class: 'myFieldsRedactorClass',
        name: name,
        value: (value is defined) ? value : ''
    }) }}
    
  3. Initialize the redactor field type with your desired toolbar.

    (function() {
        $('.myFieldsRedactorClass').redactor({
            buttons: ['bold', 'italic'] 
        });
    })();
    

Here's a related article on customizing Redactor toolbars from Straight Up Craft: Custom Redactor Toolbars for the Rich Text Field in Craft CMS

Note: One thing to be mindful of, which I'm not sure what to say about, is that if you have other Rich Text fields in your section with you custom field type, Craft is probably already loading these resources. I don't know if there is some way to check to see if these are loaded and only load the redactor css and js assets if they are not being loaded elsewhere.

share|improve this answer
4  
Craft keeps track of the queued-up JS/CSS resources, so if the same file is included twice in the same request, it will still only get one <script> or <link> tag ;) –  Brandon Kelly Jun 21 at 23:55
    
Thanks for the help, you both helped me a lot :) –  Victor In Jun 22 at 10:35

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.