Our Journal, keeping you up-to-date on our latest news.

 

Adding WYSIWYGs to Custom Drupal Forms with FormAPI

One of the greatest assets in any Drupal developer's toolbox is the FormAPI. With the FormAPI, you can do just about anything. Form wizards, multistep forms, custom contact forms, image uploaders, there is no limit. Combining Drupal's FormAPI with CTools API grants even greated flexibility, such as object caching and advanced wizard forms.

Today, we're going to start off with something simple: adding a WYSIWYG to a custom Drupal 7 form with the FormAPI.

What you'll need (if you don't already have it):

  • WYSIWYG Module
  • CKEditor, FCKEditor, or TinyMCE
  • Restricted input formats (Filtered HTML, etc) with access permissions assigned to roles

Assuming you already have a form in progress with your custom module (or perhaps you are modifying an existing form with hook_form_alter):

$form['mytextarea'] = array(
  '#type' => 'textarea',
  '#title' => 'Basic Textarea'
  '#description' => 'This is a basic plain textarea. Boo.',
);

The above code will make a basic textarea appear in your form. With a couple of changes, we can easily add a WYSIWYG:

$form['mytextarea'] = array(
  '#type' => 'text_format',
  '#title' => 'WYSIWYG Textarea',
  '#base_type' => 'textarea',
  '#description' => 'Woohoo! I am a WYSIWYG now!',
  '#format' => 'filtered_html',
);

That's all it takes! Keep in mind roles will need access to different formats and editors before it will appear for them. For the #format declaration, you need to use the machine name of the input format- in my example it's filtered_html.

Sweet! Now we have a WYSIWYG on our form, and the input format will allow for text formatting.

But, what if we want to adjust the size of the WYSIWYG? CSS and Javascript not working? That's okay, we can set javascript directly from the FormAPI too with the #attached property. Let's say we want to adjust the height of the WYSIWYG area:

$form['mytextarea'] = array(
  '#type' => 'text_format',
  '#title' => 'WYSIWYG Textarea',
  '#base_type' => 'textarea',
  '#description' => 'Woohoo! I am a WYSIWYG now!',
  '#format' => 'filtered_html',
  '#attached' => array(
      'js' => array(
         'description = setInterval(function() {
            if (jQuery("#cke_contents_edit-mytextarea-value").length == 1) {
               jQuery("#cke_contents_edit-mytextarea-value").css("height", "200px");
            } },1);' => array('type' => 'inline', 'scope' => 'footer', 'weight' => 5)
            )
       )
);

Note that the above javascript is specific to CKEditor and will need minor adjustments for other editors. You can also change other properties of the WYSIWYG with this method too.

Badabing, now you have a WYSIWYG on your Drupal form!

Like what you're reading? Get started on your project easily.

PHPApacheMySQLDrupal