Add TinyMCE to HTML Element in CodeIgniter

TinyMCE is a WYSIWYG editor which enables HTML textarea or other HTML elements to accept formatted input and media files.

It previews the content while adding and editing.

In this tutorial, I show how you can add TinyMCE editor to HTML control and read it on the form submit in CodeIgniter Project.

Add TinyMCE to HTML element in CodeIgniter


Contents

  1. Configuration
  2. Download TinyMCE & Create directory
  3. Controller
  4. View
  5. Demo
  6. Conclusion

1. Configuration

Open application/config/routes.php and edit default_controller value to User.

$route['default_controller'] = 'User';

2. Download TinyMCE & Create directory

  • Download TinyMCE.
  • Create a resources directory at project root.
  • Extract the TinyMCE zip.

Add TinyMCE to HTML Element in CodeIgniter


3. Controller

Create a User.php file in application/controllers/ directory.

Create two methods –

  • __construct() – Load url helper.
  • index() – Initialize $data['content'] with post content on <form> submit and pass in user_view view.

Completed Code

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class User extends CI_Controller {

  public function __construct() {

    parent::__construct();

    // load base_url
    $this->load->helper('url');
  }

  public function index(){

    $data = array();
    if($this->input->post('submit') != NULL ){ 
			
	$content = $this->input->post('content');
	$data['content'] = $content;
			
    }

    $this->load->view('user_view',$data);
 
  }

}

4. View

Create a user_view.php file in application/views/ directory.

Load tinymce.min.js script in the <head> section.

Create <textarea> and submit button in the <form>. Display $content in the <textarea> if isset($content).

Initialize tinymce by calling tinymce.init() method.

Completed Code

<!doctype html>
<html>
  <head>
    <!-- TinyMCE script -->
    <script src='<?= base_url() ?>resources/tinymce/tinymce.min.js'></script>
  </head>
  <body>
    <!-- Form -->
    <form method='post' action=''>
      <!-- Textarea -->
      <textarea class='editor' name='content'>
      <?php if(isset($content)){ echo $content; } ?> 
      </textarea>
      <br>
      <input type='submit' value='Submit' name='submit'>
    </form>

    <!-- Script -->
    <script>
    tinymce.init({ 
      selector:'.editor',
      theme: 'modern',
      height: 200
    });
    </script>
 </body>
</html>

5. Demo

Enter text in the editor and click submit button. Open in a new tab.


6. Conclusion

Download and Include TinyMCE script file in your view file and initialize it on the HTML element.

You can also create a separate script file and include it in the view.

If you found this tutorial helpful then don't forget to share.