Skip to main content

CakePHP : Adding a file upload and adding a select list of URLs for users in a CMS

CakePHP automagically generates textboxes for users, but it's usually a project requirement that these boxes are "user friendly".

Adding CK editor to CakePHP is easy, but lets go a few steps further and give it the ability to allow users to upload images directly into their content and to select a list of pages when creating a link.

This article is based heavily on two articles (Adding file upload in CK editor and Adding a ‘Link to local page from site’ field) which I have simply modified to be CakePHP specific. So all credits to Ben Roberts and Zac.

Step 1 - Adding CK editor to CakePHP with the FileManager plugin
1) Download CK editor from the official site and unzip it into your /app/webroot/js directory. To make things easy I put it in /app/webroot/ckeditor directory.
2) Download FCK editor from the same site.  It was at the bottom of the CK downloads page (because it is deprecated).  Unzip it to a temporary directory and copy the filemanager directory (fckeditor/editor/) to /app/webroot/ckeditor/filemanager directory.  We will be using the FCK filemanager in CK editor.
3) Edit filemanager/connectors/php/config.php and enable the plugin and do whatever other configuration you may require. Take note of the document root option and remember that this is going through Javascript and not CakePHP, which means that you need to set it /app/webroot/userfiles and not the default of /userfiles
4) Open up filemanager/connectors/php/config.php and make the following changes:

Add this function:

function GetUrlParam( paramName )
{
 var oRegex = new RegExp( '[\?&]' + paramName + '=([^&]+)', 'i' ) ;
 var oMatch = oRegex.exec( window.top.location.search ) ;
 
 if ( oMatch && oMatch.length > 1 )
  return decodeURIComponent( oMatch[1] ) ;
 else
  return '' ;
}
Replace the OpenFile function with the below function:

function OpenFile( fileUrl )
{
 
 //PATCH: Using CKEditors API we set the file in preview window. 
 
 funcNum = GetUrlParam('CKEditorFuncNum') ;
 //fixed the issue: images are not displayed in preview window when filename contain spaces due encodeURI encoding already encoded fileUrl 
 window.top.opener.CKEDITOR.tools.callFunction( funcNum, fileUrl);
 
 ///////////////////////////////////
 window.top.close() ;
 window.top.opener.focus() ;
}
Create a new helper in your helpers directory called fck.php and include the code below. Remember to use this helper in the controller you want to be able to use CK editor. This helper is based on the one available in the bakery but I have modified the code so that it uses the file manager we copied in from FCK.

// file /app/views/helpers/fck.php
class FckHelper extends Helper { 

    var $helpers = Array('Html', 'Javascript'); 

    function load($id) { 
        $did = ''; 
        foreach (explode('.', $id) as $v) { 
            $did .= ucfirst($v); 
        }  
        // filebrowser patch   
        $here = 'http://' .  $_SERVER['HTTP_HOST'] . $this->webroot; 

        $fileBrowser = "{\n
            filebrowserBrowseUrl :'".$here."js/ckeditor/filemanager/browser/default/browser.html?Connector=".$here."js/ckeditor/filemanager/connectors/php/connector.php',\n
            filebrowserImageBrowseUrl : '".$here."js/ckeditor/filemanager/browser/default/browser.html?Type=Image&Connector=".$here."js/ckeditor/filemanager/connectors/php/connector.php',\n
            filebrowserFlashBrowseUrl :'".$here."js/ckeditor/filemanager/browser/default/browser.html?Type=Flash&Connector=".$here."js/ckeditor/filemanager/connectors/php/connector.php'}\n";

        $code = "CKEDITOR.replace( '".$did."', $fileBrowser );"; 
        return $this->Javascript->codeBlock($code);  
    } 
} 

When you want to include CK editor in a view you can now use the code provided in the bakery. I'm just quoting a snippet, but you can view the full source here

echo $javascript->link('ckeditor/ckeditor', NULL, false);  
 echo $form->input('body', array('cols' => '60', 'rows' => '3')); 
 echo $fck->load('News.body'); 

We should now be able to include CK editor and make use of the File Manager.

Step 2 - Allowing users to select a list of URL's on the site

This section is a CakePHP specific implementation of the guide published online here.

I'm using a menu table in my database to list a menu name and url. It doesn't really matter how you want to handle your pages just so long as you can get them into JSON formatted string of description/url pairs.

Here is an example of the desired output in your controller:

[['Home Page','home'],['About Us','about'],['Contact','contact']]

I used code like the following snippet, because for this project I am using a "slug" field to be the same as the page title (project specification). Slugs are stored in my database with a hyphen which is simply stripped to get the page title.

// get pages for ckEditor
$this->ContentItem->recursive = -1;
$contentItems = $this->ContentItem->find('all',array('fields'=>array('slug')));
$json_links = array();
    foreach ($contentItems as $contentItem) {
        $slug = $contentItem['ContentItem']['slug'];                                      
        $description = str_replace('-',' ',$slug);
        $json_links[] .= "['" . $description . "','". $slug ."']";
    }     
    $json_links = '[' . implode(',',$json_links) . ']';               
    $this->set(compact('json_links'));

You will no doubt need to modify this to suit your needs, either in your model or controller depending on your coding style.

Open up the view and add a dummy input box like the tutorial suggests:

<input type='hidden' id='pageListJSON' value="<?php echo $json_links; ?>" >

Personally I feel that there is probably a better way to do this, but since this method works I'm not going to bother trying to improve on it. The only reason the author of the tutorial uses the input is to use a Javascript query on it later. So I wonder if setting a variable there and replacing this look-up later would be a better approach? Comments anybody? Anyway, back to work...

You can now follow the rest of the tutorial that this section is based on from step 3 as this all deals with the Javascript and so can be directly applied to Cake.

When following the tutorial make sure that you take note of the comment made by amosmos on 01.01.11 regarding the code addition in step 5... if you are using a database to pull your pages you may need to add a prefix to your URL (or you can do it in your Model/Controller when you encode in JSON):

attributes[ 'data-cke-saved-href' ] = 'pages/' + data.localPage; 

You should now have a workable CK Editor for your CakePHP CMS.

Comments

Popular posts from this blog

Separating business logic from persistence layer in Laravel

There are several reasons to separate business logic from your persistence layer.  Perhaps the biggest advantage is that the parts of your application which are unique are not coupled to how data are persisted.  This makes the code easier to port and maintain. I'm going to use Doctrine to replace the Eloquent ORM in Laravel.  A thorough comparison of the patterns is available  here . By using Doctrine I am also hoping to mitigate the risk of a major version upgrade on the underlying framework.  It can be expected for the ORM to change between major versions of a framework and upgrading to a new release can be quite costly. Another advantage to this approach is to limit the access that objects have to the database.  Unless a developer is aware of the business rules in place on an Eloquent model there is a chance they will mistakenly ignore them by calling the ActiveRecord save method directly. I'm not implementing the repository pattern in all its glory in this demo.  

Fixing puppet "Exiting; no certificate found and waitforcert is disabled" error

While debugging and setting up Puppet I am still running the agent and master from CLI in --no-daemonize mode.  I kept getting an error on my agent - ""Exiting; no certificate found and waitforcert is disabled". The fix was quite simple and a little embarrassing.  Firstly I forgot to run my puppet master with root privileges which meant that it was unable to write incoming certificate requests to disk.  That's the embarrassing part and after I looked at my shell prompt and noticed this issue fixing it was quite simple. Firstly I got the puppet ssl path by running the command   puppet agent --configprint ssldir Then I removed that directory so that my agent no longer had any certificates or requests. On my master side I cleaned the old certificate by running  puppet cert clean --all  (this would remove all my agent certificates but for now I have just the one so its quicker than tagging it). I started my agent up with the command  puppet agent --test   whi

Redirecting non-www urls to www and http to https in Nginx web server

Image: Pixabay Although I'm currently playing with Elixir and its HTTP servers like Cowboy at the moment Nginx is still my go-to server for production PHP. If you haven't already swapped your web-server from Apache then you really should consider installing Nginx on a test server and running some stress tests on it.  I wrote about stress testing in my book on scaling PHP . Redirecting non-www traffic to www in nginx is best accomplished by using the "return" verb.  You could use a rewrite but the Nginx manual suggests that a return is better in the section on " Taxing Rewrites ". Server blocks are cheap in Nginx and I find it's simplest to have two redirects for the person who arrives on the non-secure non-canonical form of my link.  I wouldn't expect many people to reach this link because obviously every link that I create will be properly formatted so being redirected twice will only affect a small minority of people. Anyway, here's