CodeIgniter 4 - 无法使用 TinyMCE 文本编辑器提交数据,但可以提交正常文本区域数据

CodeIgniter 4 - Cannot submit data with TinyMCE text editor but with normal text area data gets submitted

我正在尝试将 TinyMCE 编辑器与 CodeIgniter 4 应用程序集成。然而,即使我点击提交按钮,来自 tinyMCE textarea 的数据也没有提交到数据库,但是使用普通的 textarea,数据很容易提交到数据库。

此外,当我编辑和更新提交的数据时,它会在数据库中更新,但 tinyMCE 的文本格式被删除,数据在数据库中保存为普通文本。

下面是我的代码

添加页面控制器

public function addPage() {

    if(!session()->has('logged_staff')) {

            return redirect()->to(base_url(). "/team");
    
    } 
    $data = [];
    $data['validation'] = null;
    $suid = session()->get('logged_staff');
    $data['staffdata'] = $this->adminModel->getLoggedStaffData($suid);
    $data['memrole'] =  $this->adminModel->getMemberRole($suid);
    $data['permission'] = $this->adminModel->getPermission($suid);

    $checkPermission = $this->adminModel->checkPermission($suid);
    $memrank = $this->adminModel->getMemberRank($suid);

    if(is_array($memrank)) {

            if($memrank['rank'] == 'Super Admin') {

            }
            elseif(isset($checkPermission)) {
                    if($checkPermission['pages'] == 'Not Allowed') {
    
                            return redirect()->back();
    
                    }
            }
    }

    if($this->request->getMethod() == 'post') {

            $rules = [
                    'p_name' => [

                            'rules' => 'required|min_length[3]|max_length[250]',
                            'errors' => [
    
                                    'required' => 'You cannot leave this field empty',
                                    'min_length' => 'Title is short',
                                    'max_length' => 'Title is too long',
                            ]
                            ],
                    'p_description' => [
    
                            'rules' => 'required',
                            'errors' => [
    
                                    'required' => 'You cannot leave this field empty',
                            ]
                            ],
            ];

            if($this->validate($rules)) {

                    $addContent = [

                            'p_name'        => $this->request->getVar('p_name', FILTER_SANITIZE_STRING),
                            'p_description' => htmlentities($this->request->getVar('p_description', FILTER_SANITIZE_STRING)),
                            'p_date'        => date("Y-m-d h:i:s"),
                            'p_slug'        => strtolower(url_title($this->request->getVar('p_name'))),

                    ];

                    if($this->pageModel->insertContent($addContent)) {

                            $this->session->setTempdata('success', 'Page updated successfully', 3);
                            return redirect()->to(base_url()."/admin/pages");

                    } else {

                            $this->session->setTempdata('error', 'Oops! could not update the page', 3);
                            return redirect()->to(current_url());

                    }
                    

            } else {

                    $data['validation'] = $this->validator;

           }

    } 

    echo view("team/Templates/header_panel");
    echo view("team/navigation", $data);
    echo view("team/sidebar", $data);
    echo view("team/addpage", $data);
    echo view("team/Templates/footer_panel");
    
}

编辑页面控制器

public function editPage($id=null) {

    if(!session()->has('logged_staff')) {

            return redirect()->to(base_url(). "/team");
    
    } 
    $data = [];
    $data['validation'] = null;
    $suid = session()->get('logged_staff');
    $data['staffdata'] = $this->adminModel->getLoggedStaffData($suid);
    $data['memrole'] =  $this->adminModel->getMemberRole($suid);
    $data['permission'] = $this->adminModel->getPermission($suid);

    $checkPermission = $this->adminModel->checkPermission($suid);
    $memrank = $this->adminModel->getMemberRank($suid);

    if(is_array($memrank)) {

            if($memrank['rank'] == 'Super Admin') {

            }
            elseif(isset($checkPermission)) {
                    if($checkPermission['pages'] == 'Not Allowed') {
    
                            return redirect()->back();
    
                    }
            }
    }

    $data['p_data'] = $this->db->table('tblpages')
                                    ->select('*')
                                    ->where(["id" => $id])
                                    ->get()
                                    ->getRow();

    if($this->request->getMethod() == 'post') {

            $rules = [
                    'p_name' => [

                            'rules' => 'required|min_length[3]|max_length[250]',
                            'errors' => [
    
                                    'required' => 'You cannot leave this field empty',
                                    'min_length' => 'Title is short',
                                    'max_length' => 'Title is too long',
                            ]
                            ],
                    'p_description' => [
    
                            'rules' => 'required',
                            'errors' => [
    
                                    'required' => 'You cannot leave this field empty',
                            ]
                            ],
            ];

            if($this->validate($rules)) {

                    $pageContent = [

                            'p_name'        => $this->request->getVar('p_name', FILTER_SANITIZE_STRING),
                            'p_description' =>  htmlentities($this->request->getVar('p_description', FILTER_SANITIZE_STRING)),
                            'p_slug'        => strtolower(url_title($this->request->getVar('p_name'))),

                    ];

                    if($this->pageModel->updateContent($pageContent, $id)) {

                            $this->session->setTempdata('success', 'Page updated successfully', 3);
                            return redirect()->to(base_url()."/admin/pages");

                    } else {

                            $this->session->setTempdata('error', 'Oops! could not update the page', 3);
                            return redirect()->to(current_url());

                    }
                    

            } else {

                    $data['validation'] = $this->validator;

           }

    } 

    echo view("team/Templates/header_panel");
    echo view("team/navigation", $data);
    echo view("team/sidebar", $data);
    echo view("team/editpage", $data);
    echo view("team/Templates/footer_panel");
    
}

编辑 - 创建页面视图文件

<?php

$page_session = \Config\Services::session();

?>

  <!-- Content Wrapper. Contains page content -->
  <div class="content-wrapper">
    <!-- Content Header (Page header) -->
    <section class="content-header">
      <div class="container-fluid">
        <div class="row mb-2">
          <div class="col-sm-6">
            <h1>Add New Page</h1>
          </div>
          <div class="col-sm-6">
            <ol class="breadcrumb float-sm-right">
              <li class="breadcrumb-item"><a href="<?= base_url(); ?>/admin">Home</a></li>
              <li class="breadcrumb-item"><a href="<?= base_url(); ?>/admin/pages">Page List</a></li>
              <li class="breadcrumb-item active">Add New Page</li>
            </ol>
          </div>
        </div>
      </div><!-- /.container-fluid -->
    </section>

    <section class="content">
      <div class="container-fluid">
      <div class="row">
                <div class="col-lg-12">
                    <div class="contact__form__title">
                        <?php if($page_session->getTempdata('success', 3)) : ?>
                            <div class="alert alert-success">
                                <?= $page_session->getTempdata('success', 3); ?>
                            </div>
                        <?php endif; ?>

                        <?php if($page_session->getTempdata('error', 3)) : ?>
                            <div class="alert alert-danger">
                                <?= $page_session->getTempdata('error', 3); ?>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
      </div>
    </section>

    <!-- Main content -->
    <section class="content">
        <div class="container-fluid">
            <div class="row">
                    <div class="col-md-12">
                            <div class="card card-primary">
                                <ul class="nav nav-tabs nav-pills nav-fill">
                                        <li class="nav-item">
                                                <a href="#details" class="nav-link active" data-toggle="tab">Add Page</a>
                                        </li>
                                </ul>
                                <div class="card-body">
                                        <div class="tab-content">
                                                <div id="details" class="tab-pane active">
                                                                <?= form_open('admin/addPage/'); ?>
                                                                <div class="form-group row">
                                                                        <div class="col-sm-12">
                                                                                <?= csrf_field(); ?>
                                                                        </div>
                                                                </div>
                                                                <div class="form-group row">
                                                                        <div class="col-sm-12">
                                                                                <label for="pTitle">Edit Title</label>
                                                                                <input type="text" name="p_name" value="<?= set_value('p_name'); ?>" class="form-control" id="pTitle" placeholder="Page Name or Page Title" required>
                                                                                <span class="text-danger"><?= display_errors($validation, 'p_name'); ?></span>
                                                                        </div>
                                                                </div>
                                                                <div class="form-group row">
                                                                        <div class="col-sm-12">
                                                                                <label for="pContent">Edit Page Content</label>
                                                                                <textarea id="editor" name="p_description" class="form-control" id="pContent" cols="10" rows="10" placeholder="Write something here.." required><?= set_value('p_description'); ?></textarea>
                                                                                <span class="text-danger"><?= display_errors($validation, 'p_description'); ?></span>
                                                                        </div>
                                                                </div>
                                                                <div class="form-group row">
                                                                        <div class="col-sm-12">
                                                                                <button type="submit" class="btn btn-primary">Create Page</button>
                                                                                <a href="<?= base_url();?>/admin/pages" class="btn btn-dark text-white">Cancel</a>
                                                                        </div>
                                                                </div>
                                                        <?= form_close(); ?>
                                                </div>
                                        </div>
                                </div>
                            </div>
                    </div>
            </div>
        </div>
    </section>
    <!-- /.content -->
  </div>
  <!-- /.content-wrapper -->

init.js 文件 - 启动编辑器的 TinyMCE 代码

tinymce.init({
  selector: '#editor',
  valid_elements : '*[*]',
});

编辑了 addPage 控制器代码 - 仍然不起作用

if(!$this->validate([

                'p_name'        => 'required|min_length[3]|max_length[250]',
                'p_description' => 'required',
        ])){
                echo view("team/Templates/header_panel");
                echo view("team/navigation", $data);
                echo view("team/sidebar", $data);
                echo view("team/addpage", $data);
                echo view("team/Templates/footer_panel");
        }
        else {
                if($this->pageModel->save) {(
                        [
                                'p_name'        => $this->request->getVar('p_name', FILTER_SANITIZE_STRING),
                                'p_description' => $this->request->getVar('p_description'),
                                'p_date'        => date("Y-m-d h:i:s"),
                                'p_slug'        => strtolower(url_title($this->request->getVar('p_name'))),

                        ]

                );

                        $this->session->setTempdata('success', 'Page Created successfully', 3);
                        return redirect()->to(base_url()."/admin/pages");

                }
                else {

                        $this->session->setTempdata('error', 'Unable to create page', 3);
                        return redirect()->to(current_url());

                }
        }

整个代码的模型

namespace App\Models;

use CodeIgniter\Model;

class PageModel extends Model {

        protected $table = 'tblpages';
        protected $allowedFields = ['p_name', 'p_description', 'p_date', 'p_slug'];

        public function getPages($slug = null) {
                
                if(!$slug) {

                        return $this->findAll();
                }

                return $this->asArray()
                            ->where(['p_slug' => $slug])
                            ->first();
        }

        public function updateContent($pageContent, $id) {

                $builder =  $this->db->table('tblpages');
                $builder->where('id', $id);
                $result = $builder->update($pageContent);

                if($this->db->affectedRows() > 0) {

                        return true;

                } else {

                        return false;
                }
        }

        // Delete Page
        public function deletePage($id) {

                $builder = $this->db->table('tblpages');
                $builder->where('id', $id);
                $builder->delete();
                
        }
}

请帮我解决这个问题。提前谢谢大家!

我相信这是两个控制器的罪魁祸首

'p_description' => htmlentities($this->request->getVar('p_description', FILTER_SANITIZE_STRING))

根据PHP manual,FILTER_SANITIZE_STRING:

Strip tags and HTML-encode double and single quotes, optionally strip or encode special characters.

由于您想保留 HTML 标记,只需删除 FILTER_SANITIZE_STRINGS 过滤器即可。

您的视图文件的另一个问题是您的文本编辑器有两个 ID:editor1 and pContent`

<textarea id="editor" name="p_description" class="form-control" id="pContent" cols="10" rows="10" placeholder="Write something here.." required><?= set_value('p_description'); ?></textarea>                                                                               

去掉多余的id,一切都应该没问题。

编辑创建代码无效 在您的 addPage 控制器中,我注意到了这一点:

if($this->pageModel->save) {([
    'p_description' => ...,
])
}

请注意,这与

不同
if($this->pageModel->save([
    'p_description' => '...',
])) {
  // ...
}