9

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.

13

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.

| improve this answer | |
  • 6
    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 '14 at 23:55
  • 1
    One further thing I'm not clear about - how do you define a RichText field in your plugin's defineSettings() method? – Phil Gyford Sep 2 '15 at 18:02
  • @PhilGyford You dont have to. The field has to be of type AttributeType::Text and in your settings view you initialize the textArea like Ben posted in JS. – Simon Franzen Apr 11 '18 at 11:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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