You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CodeIgniter技术问题:保存WYSIWYG编辑器HTML内容至数据库

Hey there! Let's walk through how to implement the save/edit functionality for your Trumbowyg-based email templates in CodeIgniter. I've built similar features before, so here's a step-by-step breakdown that should work for your setup:


Step 1: Database Setup

First, create a table to store user-specific templates. This ensures each user only accesses their own templates:

CREATE TABLE email_templates (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT NOT NULL, -- Links to your users table
    template_name VARCHAR(255) NOT NULL,
    template_content TEXT NOT NULL, -- Stores Trumbowyg's HTML output
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);
Step 2: Create a Template Model

Make a Template_model.php in application/models/ to handle database operations:

<?php
class Template_model extends CI_Model {

    // Get all templates for the logged-in user
    public function get_user_templates($user_id) {
        return $this->db->where('user_id', $user_id)->get('email_templates')->result();
    }

    // Get a single template by ID (user-restricted)
    public function get_template($template_id, $user_id) {
        return $this->db->where(['id' => $template_id, 'user_id' => $user_id])->get('email_templates')->row();
    }

    // Save a new template
    public function create_template($data) {
        return $this->db->insert('email_templates', $data);
    }

    // Update an existing template
    public function update_template($template_id, $user_id, $data) {
        return $this->db->where(['id' => $template_id, 'user_id' => $user_id])->update('email_templates', $data);
    }
}
?>
Step 3: Build the Templates Controller

Create Templates.php in application/controllers/ to handle user requests. Make sure to add login validation (adjust this to match your auth system):

<?php
class Templates extends CI_Controller {

    public function __construct() {
        parent::__construct();
        // Check if user is logged in - replace with your auth check
        if (!$this->session->userdata('logged_in')) {
            redirect('auth/login');
        }
        $this->load->model('Template_model');
        $this->load->library('form_validation');
    }

    // Show user's template list
    public function index() {
        $user_id = $this->session->userdata('user_id');
        $data['templates'] = $this->Template_model->get_user_templates($user_id);
        $this->load->view('templates/list', $data);
    }

    // Show create template form
    public function create() {
        $this->load->view('templates/create');
    }

    // Handle new template submission
    public function save() {
        $this->form_validation->set_rules('template_name', 'Template Name', 'required|trim');
        
        if ($this->form_validation->run() === FALSE) {
            $this->load->view('templates/create');
        } else {
            $user_id = $this->session->userdata('user_id');
            $data = [
                'user_id' => $user_id,
                'template_name' => $this->input->post('template_name'),
                'template_content' => $this->input->post('template_content', FALSE) // Disable XSS filter for HTML content
            ];
            
            if ($this->Template_model->create_template($data)) {
                $this->session->set_flashdata('success', 'Template saved successfully!');
                redirect('templates');
            } else {
                $this->session->set_flashdata('error', 'Failed to save template.');
                redirect('templates/create');
            }
        }
    }

    // Show edit template form
    public function edit($template_id) {
        $user_id = $this->session->userdata('user_id');
        $data['template'] = $this->Template_model->get_template($template_id, $user_id);
        
        if (!$data['template']) {
            $this->session->set_flashdata('error', 'Template not found.');
            redirect('templates');
        }
        
        $this->load->view('templates/edit', $data);
    }

    // Handle template update
    public function update($template_id) {
        $user_id = $this->session->userdata('user_id');
        $template = $this->Template_model->get_template($template_id, $user_id);
        
        if (!$template) {
            $this->session->set_flashdata('error', 'Template not found.');
            redirect('templates');
        }

        $this->form_validation->set_rules('template_name', 'Template Name', 'required|trim');
        
        if ($this->form_validation->run() === FALSE) {
            $data['template'] = $template;
            $this->load->view('templates/edit', $data);
        } else {
            $data = [
                'template_name' => $this->input->post('template_name'),
                'template_content' => $this->input->post('template_content', FALSE)
            ];
            
            if ($this->Template_model->update_template($template_id, $user_id, $data)) {
                $this->session->set_flashdata('success', 'Template updated successfully!');
                redirect('templates');
            } else {
                $this->session->set_flashdata('error', 'Failed to update template.');
                redirect('templates/edit/' . $template_id);
            }
        }
    }
}
?>
Step 4: Frontend Views with Trumbowyg

Create Template View (application/views/templates/create.php)

Include Trumbowyg assets (use local copies or CDNs) and set up the form:

<!DOCTYPE html>
<html>
<head>
    <title>Create Email Template</title>
    <link rel="stylesheet" href="path/to/trumbowyg.min.css">
</head>
<body>
    <h1>Create New Template</h1>
    <?= form_open('templates/save') ?>
        <?= csrf_field() ?> <!-- Important for CodeIgniter CSRF protection -->
        
        <div>
            <label>Template Name:</label>
            <input type="text" name="template_name" value="<?= set_value('template_name') ?>" required>
            <?= form_error('template_name') ?>
        </div>

        <div>
            <label>Template Content:</label>
            <textarea id="editor" name="template_content"><?= set_value('template_content') ?></textarea>
        </div>

        <button type="submit">Save Template</button>
    <?= form_close() ?>

    <script src="path/to/jquery.min.js"></script>
    <script src="path/to/trumbowyg.min.js"></script>
    <script>
        $(document).ready(function() {
            $('#editor').trumbowyg({
                // Add your preferred Trumbowyg options here
                btns: [
                    ['viewHTML'],
                    ['undo', 'redo'],
                    ['formatting'],
                    ['strong', 'em', 'del'],
                    ['link'],
                    ['insertImage'],
                    ['justifyLeft', 'justifyCenter', 'justifyRight', 'justifyFull'],
                    ['unorderedList', 'orderedList'],
                    ['horizontalRule'],
                    ['removeformat'],
                    ['fullscreen']
                ]
            });
        });
    </script>
</body>
</html>

Edit Template View (application/views/templates/edit.php)

Similar to create, but pre-populate the editor with existing template content:

<!DOCTYPE html>
<html>
<head>
    <title>Edit Email Template</title>
    <link rel="stylesheet" href="path/to/trumbowyg.min.css">
</head>
<body>
    <h1>Edit Template: <?= $template->template_name ?></h1>
    <?= form_open('templates/update/' . $template->id) ?>
        <?= csrf_field() ?>
        
        <div>
            <label>Template Name:</label>
            <input type="text" name="template_name" value="<?= set_value('template_name', $template->template_name) ?>" required>
            <?= form_error('template_name') ?>
        </div>

        <div>
            <label>Template Content:</label>
            <textarea id="editor" name="template_content"><?= set_value('template_content', $template->template_content) ?></textarea>
        </div>

        <button type="submit">Update Template</button>
    <?= form_close() ?>

    <script src="path/to/jquery.min.js"></script>
    <script src="path/to/trumbowyg.min.js"></script>
    <script>
        $(document).ready(function() {
            $('#editor').trumbowyg({
                // Same options as create view
            });
        });
    </script>
</body>
</html>
Step 5: Key Security & Validation Tips
  • XSS Protection: Since we're saving HTML content, we disabled XSS filtering for template_content in the controller. To prevent malicious scripts, consider integrating a library like HTMLPurifier to sanitize the HTML before saving.
  • User Permissions: All Model queries include a user_id check, so users can't access or modify templates that don't belong to them.
  • CSRF Protection: Always include <?= csrf_field() ?> in your forms to prevent cross-site request forgery attacks (CodeIgniter enables this by default in newer versions).
Troubleshooting Common Issues
  • Empty Template Content: Ensure you're not filtering the HTML content with CodeIgniter's global XSS filter. The FALSE parameter in $this->input->post('template_content', FALSE) is crucial here.
  • Trumbowyg Initialization Errors: Double-check that jQuery is loaded before Trumbowyg, and that the asset paths are correct.
  • Template Not Found: Verify that the user_id is correctly passed to the Model methods, and that the template ID exists for that user.

内容的提问来源于stack exchange,提问作者Jim123

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 07:48:27