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 ...

Using Azure Active directory as an OAuth2 provider for Django

Azure Active Directory is a great product and is invaluable in the enterprise space. In this article we'll be setting it up to provide tokens for the OAuth2 client credentials grant. This authorization flow is useful when you want to authorize server-to-server communication that might not be on behalf of a user. This diagram, by Microsoft, shows the client credentials grant flow. From Microsoft documentation  The flow goes like this: The client sends a request to Azure AD for a token Azure AD verifies the attached authentication information and issues an access token The client calls the API with the access token. The API server is able to verify the validity of the token and therefore the identity of the client. The API responds to the client Setting up Azure AD as an OAuth2 identity provider The first step is to create applications in your AD for both your API server and the client. You can find step-by-step instructions on how to register the applications o...

"Word of the Day" PHP script (with word list)

I was looking around for a way to generate a word of the day on the web and didn't find anything. So I coded a quick and dirty script to do it. Just in case anybody does a Google search and manages to find my blog: here is my Word of the Day PHP script : Copy this code snippet into a wordoftheday.php file: $file = fopen("interesting_words.txt","r"); $raw_string = fread($file,filesize("interesting_words.txt")); fclose($file); $words_array = explode("|",$raw_string); echo $words_array[array_rand($words_array)]; Of course the real issue I had was finding a list of interesting words in the right format. Here is the list of interesting words that I used: Copy this into a file called interesting_words.txt : ubiquitous : being or seeming to be everywhere at the same time; omnipresent| ecdysiast : a striptease artist| eleemosynary : of, relating to, or dependent on charity| gregious : c...