Home > Enterprise >  CodeIgniter 4 - Cannot submit data with TinyMCE text editor but with normal text area data gets subm
CodeIgniter 4 - Cannot submit data with TinyMCE text editor but with normal text area data gets subm

Time:05-16

I am trying to integrate TinyMCE editor with CodeIgniter 4 application. However the data from the tinyMCE textarea is not getting submitted to database even when i click on submit button but with normal textarea the data is submitted to database easily.

Also when i edit & update the submitted data, it gets updated in the database but the text formatting from tinyMCE is erased and data is saved as normal text in the database.

Here is my code below

Add page controller

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");
    
}

Edit Page Controller

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");
    
}

Edit - Create Page View File

<?php

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

?>

  <!-- Content Wrapper. Contains page content -->
  <div >
    <!-- Content Header (Page header) -->
    <section >
      <div >
        <div >
          <div >
            <h1>Add New Page</h1>
          </div>
          <div >
            <ol >
              <li ><a href="<?= base_url(); ?>/admin">Home</a></li>
              <li ><a href="<?= base_url(); ?>/admin/pages">Page List</a></li>
              <li >Add New Page</li>
            </ol>
          </div>
        </div>
      </div><!-- /.container-fluid -->
    </section>

    <section >
      <div >
      <div >
                <div >
                    <div >
                        <?php if($page_session->getTempdata('success', 3)) : ?>
                            <div >
                                <?= $page_session->getTempdata('success', 3); ?>
                            </div>
                        <?php endif; ?>

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

    <!-- Main content -->
    <section >
        <div >
            <div >
                    <div >
                            <div >
                                <ul >
                                        <li >
                                                <a href="#details"  data-toggle="tab">Add Page</a>
                                        </li>
                                </ul>
                                <div >
                                        <div >
                                                <div id="details" >
                                                                <?= form_open('admin/addPage/'); ?>
                                                                <div >
                                                                        <div >
                                                                                <?= csrf_field(); ?>
                                                                        </div>
                                                                </div>
                                                                <div >
                                                                        <div >
                                                                                <label for="pTitle">Edit Title</label>
                                                                                <input type="text" name="p_name" value="<?= set_value('p_name'); ?>"  id="pTitle" placeholder="Page Name or Page Title" required>
                                                                                <span ><?= display_errors($validation, 'p_name'); ?></span>
                                                                        </div>
                                                                </div>
                                                                <div >
                                                                        <div >
                                                                                <label for="pContent">Edit Page Content</label>
                                                                                <textarea id="editor" name="p_description"  id="pContent" cols="10" rows="10" placeholder="Write something here.." required><?= set_value('p_description'); ?></textarea>
                                                                                <span ><?= display_errors($validation, 'p_description'); ?></span>
                                                                        </div>
                                                                </div>
                                                                <div >
                                                                        <div >
                                                                                <button type="submit" >Create Page</button>
                                                                                <a href="<?= base_url();?>/admin/pages" >Cancel</a>
                                                                        </div>
                                                                </div>
                                                        <?= form_close(); ?>
                                                </div>
                                        </div>
                                </div>
                            </div>
                    </div>
            </div>
        </div>
    </section>
    <!-- /.content -->
  </div>
  <!-- /.content-wrapper -->

init.js file - TinyMCE code to initiate the editor

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

Edited the addPage controller code - Still doesn't work

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());

                }
        }

Model for this entire code

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();
                
        }
}

Please help me on this one. Thanks everyone in advance!

CodePudding user response:

I believe this is the culprit in both controllers

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

According to PHP manual, FILTER_SANITIZE_STRING:

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

Since you want to keep the HTML markup, simply remove the FILTER_SANITIZE_STRINGS filter and you should be good to go.

Another problem with your view file is that your text editor has two id's: editor1 and pContent`

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

Remove the extra id, and everything should be fine.

Edit about the create code not working In your addPage controller, I noticed this:

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

Note that that's not the same as

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