CakePHP tricks: Getting your scaffold ready for AJAX views

Warning! What follows is a lot more technical than our usual posts and will take some working knowledge of PHP, AJAX and MVC frameworks. Want to see more of this kind of post? Let us know what you think in the comments.

CakePHP is a great tool for rapid development and testing out ideas, however we often find that the basis of a good idea relies on a great interface, and in this day and age, that often means employing varying degrees of AJAX (Asynchronous Javascript and XML) in the user interface (or in CakePHP/MVC framework lingo, the view).

Scaffold is a great way to add a quick front end to a database and start seeing how everything links together and how it might look, however in more involved concepts it falls down on usability, and it doesn’t come with support for AJAX requests out of the box, so to speak. While the general consensus is that you shouldn’t use scaffold in production environments (and we would agree with that assertion), building AJAX support into the scaffold would certainly help to work out the concept of an involved front end in the initial stages.

So without further ado, let’s see how we can do a quick and dirty change to the scaffold ready to provide us with responses that we can use for AJAX calls from the view. The example below uses the CakePHP 2.0 release, available from

First, we will need to tell the CakePHP install to pay attention to the extensions we ask for, so that we can request for example /ourmodel/add.json, and it will provide us with information different to that shown at /ourmodel/add. This is fairly straight forward. Just crack open


and add the following to the bottom of the file:

//read extensions of requested URL's

Next we need to modify the standard scaffold which lives at:


Don’t edit the file here though, as Cake has a way for you to override this file (and indeed every other file in a similar way) by creating a file in the app directory. This means you won’t mangle any of the core files, making it difficult to upgrade the core at a later date. So, in order to override the original Scaffold.php, we will copy it to:


Next, let’s decide on a format for the JSON we are going to output to our views when we request a JSON file. For the purpose of this tweak let’s return the following:

  • A “success” field that is either true or false so we can make decisions on how to treat the data in the view, such as changing the class of the response to red or green based on success or failure.
  • A “data” field containing the data we’ve added to the database if the action has been a success should we need to display it in some way
  • An “error” field containing any errors we have encountered if the action has not been a success so that we can alert the user to the specific area that is the problem
  • A “flash_message” field containing the friendly message to display to the user telling them what happened when the action was executed.

Now all that remains is to make some adjustments to the relevant parts of the scaffold file. Comments are included so hopefully you can see the parts of the code that have been added over and above the original file. First off, let’s change the function that would normally return a message to the user and render the next view, _sendMessage.

	protected function _sendMessage($message) {	
		if ($this->_validSession) {
			//Spot an AJAX request
			if ($this->request->is('ajax')) {
				//Set the content type, dump the data and the message into a JSON string to be parsed by the javascript and die
				$jsonDataArray['success'] = true;
				$jsonDataArray['data'] = $this->ScaffoldModel->read();
				$jsonDataArray['flash_message'] = $message;
				die(json_encode($jsonDataArray)); //the cake way would be to disable autoRender, however this causes warnings
			} else { 
				//we don't have AJAX so do the normal scaffold actions
		} else {
			$this->controller->flash($message, $this->redirect);

And finally we need to make a change to the function that saves or updates the model – _scaffoldSave.

	protected function _scaffoldSave(CakeRequest $request, $action = 'edit') {
		$formAction = 'edit';
		$success = __d('cake', 'updated');
		if ($action === 'add') {
			$formAction = 'add';
			$success = __d('cake', 'saved');
		if ($this->controller->beforeScaffold($action)) {
			if ($action == 'edit') {
				if (isset($request->params['pass'][0])) {
					$this->ScaffoldModel->id = $request['pass'][0];
				if (!$this->ScaffoldModel->exists()) {
					throw new NotFoundException(__d('cake', 'Invalid %s', Inflector::humanize($this->modelKey)));
			if (!empty($request->data)) {
				if ($action == 'create') {
				if ($this->ScaffoldModel->save($request->data)) {
					if ($this->controller->afterScaffoldSave($action)) {
						$message = __d('cake',
							'The %1$s has been %2$s',
						return $this->_sendMessage($message);
					} else {
						return $this->controller->afterScaffoldSaveError($action);
				} else {
					if ($this->_validSession) {
						//Spot an AJAX request
						if ($this->request->is('ajax')) {
							//Set the content type to return, dump the error data and the message into a JSON string to be parsed by the javascript and die
							$jsonDataArray['success'] = false;
							$jsonDataArray['error'] = $this->ScaffoldModel->validationErrors;
							$jsonDataArray['flash_message'] = 'Please correct errors below.';
							die(json_encode($jsonDataArray)); //the cake way would be to disable autoRender, however this causes warnings
						//We don't have AJAX so perform the original function
						$this->controller->Session->setFlash(__d('cake', 'Please correct errors below.'));
			if (empty($request->data)) {
				if ($this->ScaffoldModel->id) {
					$this->controller->data = $request->data = $this->ScaffoldModel->read();
				} else {
					$this->controller->data = $request->data = $this->ScaffoldModel->create();
			foreach ($this->ScaffoldModel->belongsTo as $assocName => $assocData) {
				$varName = Inflector::variable(Inflector::pluralize(
					preg_replace('/(?:_id)$/', '', $assocData['foreignKey'])
				$this->controller->set($varName, $this->ScaffoldModel->{$assocName}->find('list'));
			foreach ($this->ScaffoldModel->hasAndBelongsToMany as $assocName => $assocData) {
				$varName = Inflector::variable(Inflector::pluralize($assocName));
				$this->controller->set($varName, $this->ScaffoldModel->{$assocName}->find('list'));
			return $this->_scaffoldForm($formAction);
		} elseif ($this->controller->scaffoldError($action) === false) {
			return $this->_scaffoldError();

And that’s it! Let us know if you have other ways of achieving similar goals or whether this helps with your next CakePHP project in the comments.

Tagged , , , , , , , | Leave a comment

Supercharges Website Development – A Case Study

Recently, a large part of our business (mobile phone, utility, finance, insurance and other comparison software solutions for businesses) has become so important that we had to split it off as a separate business, necessitating the need for a new website to showcase what we can do, so I wanted to do a quick run down of what we did that allowed the site to go together in less than two days, and, just as importantly, the things we didn’t do.

  • First and most importantly – we needed to plan out all the content that will be available on the site, which informs the design. Once we had worked out what we wanted to say it became clear that a single page site would suffice.
  • As always, the blueprint CSS framework was used as a starting point and to allow quick development of the look and feel.
  • We wanted some effects to add to what was essentially a simple site – the library we like for this is jQuery.
  • We wanted a carousel effect to jam more information into the initial screen – there are plenty out there but the best for us was Slides.
  • In order to switch between sections we wanted a smooth scrolling effect – the leading jQuery plugin here was localScroll.
  • We usually like frameworks, particularly CakePHP, however although there are some very useful features that could have helped here, it is somewhat overkill since the site doesn’t store any user or admin data in the back-end, acting simply as a brochure or sorts.

Why not go and take a look at the finished Supercharges project at

Tagged , , , , , , , , , | Leave a comment

How to collaborate on projects remotely – what should be in your toolbox?

Over the last few years in my opinion, we have really moved to a point where collaborating on projects with people in different offices, counties or even countries can be as good as sitting right next to them in the same office, and it’s something that we at R N D M R Limited do every day. Of course there are a few tools we use on a daily basis in order to ensure that everything is running smoothly and make contact with everyone to discuss the projects at hand, so below is a handy list of the things we use on a daily basis to collaborate on projects with people in different offices around the world.

  • Skype ( This is the main tool we use for discussing the progress of projects and holding full project meetings. As well as doing voice calls very well (even in situations where your internet connection might not be the best), you can set up video conferences, instant messaging and even share your screen with people you are calling. There are also apps for the most popular smart phones which means you can still use Skype while out of the office through your mobile.
  • Projectpier ( I’ve already posted about ProjectPier on this blog, but suffice to say it is a great system for holding all aspects of your project for everyone to refer back to time and time again, particularly to track action points and deadlines set from your Skype meetings.
  • Dropbox ( Dropbox is just an incredibly easy way to share files between people, providing you with a chunk of webspace that you can then allow access to for the other people working on your project. It has a web interface, apps you can install on your computer so that the dropbox works seamlessly as just another folder on your desktop and apps for your smart phone so you can view your files on the move. This is a great place to store any diagrams or exchange code or designs when you are in the planning stages of your project.
  • Google Docs ( Google Docs real strength is when you are working collaboratively on a file such as a word document or spreadsheet. The web interface allows those who you grant access the ability to modify the file at the same time as you are, all the while storing a complete revision history. If anything should go wrong it can be undone with a few clicks without any loss of vital information that may have been entered along the way.

Probably one of the best parts about the list of software above is that, although there are plans for extremely heavy users or advanced features, you can use these tools to collaborate on a project absolutely free in 99% of cases! So there you go – a state of the art virtual office without any cost at all – compare that to the running costs of a traditional office setup!

Tagged , , , , , , , , , , | Leave a comment

New via Twitter this week: Domain tasting, social experiments and the return of a marketing genius

As I mentioned earlier, Twitter is becoming one of the best ways to consume news in many markets, and certainly in any industry that is web based. Below are a few highlights that I’ve picked out of my Twitter timeline over the past few days in no particular order.

Expired Domain tasting in the UK via @DaveNaylor

Expired domain tasting was essentially a loophole a few years ago whereby you could take ownership of a domain, evaluate the traffic it received and any money you could make from it (usually by filling the page full of contextual text ads) and then cancel it before you needed to pay for it if it didn’t make the grade.

I remember searching several potential domains for a project on but not purchasing them, only to find them full of a holding page a few days later around this time, which was a frustrating thing to see to say the least. It’s one of the reasons I would now recommend 123 Reg if you ever want to search potential domains and make a purchase.

For better or worse, domain tasting may be on it’s way back, and it looks like it will only be better if you’re one of those doing the tasting.

Isn’t it tweet? via @OrangeTheFeed

OrangeTheFeed is Orange’s foray into interesting experiments in promotion of the Orange brand through social media, and is always good for a follow to see what a major brand that’s a good fit for the social media generation will think of next. The latest idea? Tweet your love story in 140 characters and they will get it made into an animation by cartoonists Tom Judd and Ed Barrett.

The animation’s great and it’s got some serious take up, go take a look. A great example of a seasonal idea done well.

Do nothing for 2 minutes via @delineo

Delineo brought my attention to Alex Tew’s new venture. You may remember Alex as the marketing genius who set up the million dollar homepage. 1 million pixels being sold on (basically) a single page website for $1 each – never going to work right? Well it got up a momentum of it’s own and Alex ended up making even more that $1 million by auctioning the last few pixels, and it still remains to this day a piece of (admittedly ugly!) internet history.

His new idea do nothing for 2 minutes is clearly less commercial, but I can think of worse ways to spend a couple of minutes of my day. Keep your eyes peeled for any innovative ways that may sneak in to keep Alex’s bank balance healthy!

And finally… Software calculates the appearance of the average woman in 41 countries via @Markcpearson

I love seeing clever things done with software, and anything image manipulation based in general so this is an interesting experiment for me. Put thousands of faces of women of different nationalities through a piece of software and create a composite picture of what the average woman looks like from each nation. Interesting stuff – take a look and see what you think!

Tagged , , , , , , | 1 Comment

ProjectPier – An open source way to manage projects online

Several years ago now, I found myself out of the office frequently and a few large development jobs that needed to be completed by everyone in the office so I needed a place that I could publish all of the tasks required on a project to that could be worked through by developers and designers systematically that kept me up to date with their progress.

After much searching at the time I settled for an open source system called ProjectPier. It was written in PHP and easy to install on our web servers, and provided me with a way to outline the rudimentary aspects of a project and the associated jobs quickly and easily. It certainly wasn’t heavy on features, but what it did, it did well. When I sold that business I moved into a more dedicated commercial role and so the software went by the wayside.

Recently I’ve found myself wanting a similar application again, though this time with a few extra bells and whistles (in no particular order):

  • Integration with source code control.
  • Support ticket system.
  • A place to add documentation on the software.
  • Ability to add a timesheet on a per employee basis.
  • The usual project management features (ability to add projects, set milestones, generate task lists, assign task to employees etc).
  • Easy to understand for both employees and clients.
  • Web based interface so that projects could be worked on independent of hardware and software platform and updates could be performed remotely.

So once again after a round of scouring the internet for anything that allowed project management I was pleased to discover that ProjectPier once again came up as the best choice! It seemed that the last time I’d used ProjectPier that it was being abandoned as a project, however it now has a thriving developer community, putting in hard work and covering most of the feature requests you could want, with additional timesheet, wiki and support ticket systems now provided with the latest stable build. The only thing missing from the wish list I had put together is an integration with some popular source control systems, though it may just be a matter of time before that becomes a reality.

And best of all, since the system is open source, it continues to be available completely free of charge. What’s not to like?

Tagged , , , , , , , , | 1 Comment

Twitter: Your personal news feed

Twitter is a great medium for staying up to date with happenings in the industry of your choice and making some great connections in the process. Even if you aren’t looking to be active on Twitter it’s a great idea to set up a an account and follow some influential people in your sector to keep your finger on the pulse of what is happening in your industry.

The first thing you will need after you set up your account and find the people you are looking to follow is an app that you can have open at all times on your machine that alerts you to any new tweets from the people you are following. I’ve used TweetDeck and I am currently using the official Twitter App available on the Mac App Store. Both work well though I find the official app less intrusive when a new Tweet comes in.

One of the common uses of Twitter from influencers in each sector is to publicise blog posts (something that is set up for posts from this blog through Feedburner which is now owned by Google), and the best part about Twitter is you can gauge the quality of the blog posts by retweets and discussion around each blog post that is tweeted about, to see which posts deserve your attention if you are pressed for time.

Increasingly I find Twitter being the medium in which I consume industry news over all others, and the community nature of it always points me to information that I find interesting and useful so moving forward I’ll be posting links to a selection of the most interesting blog posts I find through Twitter each week, that I hope you will find useful too.

Tagged , , , , , , | 1 Comment

Google Apps vs Microsoft Exchange

I’ve just been effusing about Google Apps yet again with a friend and it’s spurred me on to point out a few things about the system that I think are important.

At the start of most fledgling companies, almost the first thing you hear from one of the shareholders is that you need an exchange server set up so you can start to organise the business and get your company email set up, however people often overlook Google Apps as an appropriate solution to their needs, so without further ado I’ll move on to a few points that are often bones of contention in the discussions I’ve had over this in the past.

Q: Price: Isn’t it cheaper to do this ourselves with an Exchange Server?

A: Probably not – if you take into consideration the cost of buying and running your server, as well as having someone on hand at all times to maintain it should something go wrong, as well as the cost of setting up a separate solution that you can operate should you experience significant downtime, then you would probably be better off with Google Apps. Google Apps starts from £33 per user per year (a pricing system that has the ability to scare people off as they envisage their staff level growing), but if you sit down to calculate the overall costs you’ll most likely find that it’s the most cost effective solution. Google even provide a calculator to work this out. In case you are interested – using the calculator set at an IT manager’s time of £46 per hour you end up bottoming out on the cost per user for an internally hosted system at £42 per user per year with 900 employees and still with much higher up front fee’s.

Q: I’m not comfortable with the way Gmail groups emails into conversations

A: If you don’t like the conversation threading feature, just turn it off!

How to turn off Gmail conversation threading

  1. Click “Settings” in the top right corner of your email
  2. Under “Conversation View” select “Conversation view off”
  3. Go back to your inbox and and you’ll see a more traditional view

Q: Will it work with my smartphone (iPhone, Android, Blackberry)?

A: Yes, Google have realised that services on the go are one of the most important things to todays businesses and they have a raft of support items and applications for the most popular smartphones, information for which is accessible here.

These are just some of the most common objections I come up against when I recommend Google Apps thought there are others which come up from time to time. If you are using something else, what’s your reason for choosing an alternative solution?

Tagged , , , , , , | Leave a comment

How to fix the iPhone Daylight Saving Time Bug

Recently Apple iPhone’s have been hit by a bug caused by Daylight Savings Time (DST), that has caused alarms to go off at the previous time, even though the software automatically updates the time for all other applications across the iPhone. Despite seeing this bug on the 26th September when DST changed in New Zealand, Apple have failed to patch the bug and it has hit Europe, and now the US too.

I was affected by the bug when the clocks changed in the UK, and managed to solve the problem completely by accident last week. As there was an update coming for the iPhone firmware to version 4.2, I thought I’d sit on the solution as the update was imminent and should fix the problem, however since the update has now been pushed back to the 24th November, and there seems to be some demand for this so I thought I’d post my solution.

As noted, I did this by accident, however I think these are the important steps that caused the problem to fix itself. I’d be grateful of anyone getting in touch who tries this and is successful in also fixing their alarms.

  • As the alarm bug only hits recurring weekday alarms, find your recurring weekday alarm that is the problem, or create a new one.
  • Turn off the alarm in question
  • Let time pass until it is past the time that the alarm should have gone off (obviously this needs to be on a weekday)
  • Turn the alarm back on
  • The next time that the alarm goes off, it will go off at the right time!

Don’t ask me why this worked for me, but it did! Let me know if you have the same success.

Tagged , , , , , , | 1 Comment

Twitter tricks – getting stats for other peoples links

Anybody looking to spread their message on Twitter knows how important it is to get re-tweets from influential people with a high follower count. Using business influencers as an example, there are few more influential than Theo Paphitis of Dragons Den fame who, as I type this has over 53,000 followers.

Theo has started to help businesses spread their message through a weekly set of re-tweets that he does with the tag #SBS which stands for Small Business Sunday, on which he takes tweets from small businesses promoting their products and services, and re-tweets a lucky few to his followers.

But exactly how valuable is a #SBS re-tweet from Theo? Luckily due to the URL shortening service that is currently incumbent in Twitter,, we can find out – at least for the time being.

When you post a link in Twitter, will be automatically shortened using if you don’t have enough characters left to give you more space for your message, since you only have 140 characters in total. This link then sends you through to the target page and collects some stats for the creator of the link, however these stats are publicly available if you know how to access them.

Let’s take for example one of Theo’s latest #SBS re-tweets. You can see it on the screen shot below for @ClearWaterBandB.

Theo Paphitis Twitter Page

Theo Paphitis Twitter Page, showing one of his #SBS re-tweets

The link to their site is, however try visiting that URL with a plus on the end ( and voila!

ClearWater B&B stats

The stats for ClearWater's B&B link, posted on Theo Paphitis' #SBS Twitter

Not a bad amount of visits for a post on a Sunday about a niche business such as this, and the visits have been growing while I’ve been writing this post as people get back to their working week.

All in all it’s another useful measure for improving your strategy when it comes to spreading your message on Twitter and identifying who to target for re-tweets, but how long it will last given the potential for people using to be unhappy with this kind of information being publicly available, who knows?

Tagged , , , , , , , , , , | Leave a comment

Customer service system? Get Satisfaction!

When writing my post about Clearbooks and the excellent way that they do things, I touched on a point about their use of Get Satisfaction, as a community based support and suggestions system.

Before I move on from Clearbooks by the way I have to point out another new innovation – they are now posting all of their development logs online for you to see what’s being worked on. Definitely a bold move, and a welcome one. I’ve always found however that the developers that have worked for me have never really put together comments that are suitable for polite public consumption, so let’s hope they don’t have that problem!

Back to Get Satisfaction, and more specifically community systems for your support and suggestions and why you should be using them if you provide an application that people use online.

Way back in the day, support was mainly done by phone or email, then this was improved slightly by ticketing systems that are still commonplace on many customer facing websites today. While ticketing systems do have their uses, such as to discuss support issues that are specific to the user account in question and may contain sensitive information, they fall down in the way that the earlier email and phone support systems did. You inevitably end up answering the same questions over and over again.

The solution to this was to build up a comprehensive Frequently Asked Question section (FAQ), but customers tended not to readily use the system and just sent in their query direct anyway, unless of course you hid the direct contact details at the end of the FAQ journey, which tended to infuriate customers to the point that they just stopped using your system!

Community style systems break this trend by putting the answers to questions in the open for everyone to see. If someone asks a question, the instant your customer service team respond, the answer is there for all to see, and is available for anyone to refer back to who has the same issue in future. Similarly, it provides a platform for taking suggestions for additions to your system that is vastly superior, allowing customers to see suggestions that have already been made, vote for how important they feel it would be and add any thoughts of their own with extra features that may make the solution even more useful.

And it’s worth mentioning that all that content that such a system creates will be indexed by search engines, giving you a better chance of being found by potential customers.

Once again, Get Satisfaction, like Clearbooks, get it right in terms of how they address their business, embracing social media with an active presence on Twitter @getsatisfaction, syndication on Facebook, and expert information and opinion on their blog (the latest post is extremely interesting and has echoes of our only providing valuable services mantra, though with a definite focus more on the ability to work well with a client..

So if you provide customer service online, give some serious thought to an open, community style customer service system, and you are unlikely to find any better than Get Satisfaction. It starts from as little as $19 USD per month, and you can be up and running in minutes.

Tagged , , , , , , , , , , , | Leave a comment