zen of coding

Help me, help you

You might have noticed that my posts are not as frequent as they used to be.

Granted, I try to be more elaborate (and boy do I have a few things baking in the oven at the moment).

So with this idea, I will open up this post as Q&A “type-of-thing”…

If you are having difficulty with something in CakePHP post away in the comments with your questions and I will do my best to solve it (or at least guide you in the right direction).

I do have a couple of requests/rules though:

  1. Please don’t copy paste code in the comments. Use http://bin.cakephp.org/ or your favorite paste-bin to post the code.
  2. Review the manual before you post your question. Seriously. If the question can be answered by skimming through the cookbook… I’ll be sure to come up with some sort of “punishment” :)
  3. Please don’t ask me to write an entire app for you
  4. Keep the questions short, relevant and to the point
  5. Please understand that I cannot respond immediately, but I promise to make a timely answer, or contact you otherwise

Well that’s about it from my side. Hopefully this little endeavor will benefit both sides (I learn something new every day when I try to solve the problems for others… so yes, I am getting something out of it).

On top of that, I would like to reconnect with my readers, whom I felt neglected in the last few months (sorry, but work has to pay the bills and the habits).

Alright… let’s give it a shot… the forum is open :)!

  • Jason M

    What is the best way to change the page title in the view in cake 1.3? I have been using pageTitle since 1.2 but that has been deprecated in cake 1.3. I have a solution that works, but when I looked on book.cakephp.org it wasn’t clearly documented.


  • in the view of the relevant action use:

    $this->set(‘title_for_layout’, ‘Some page title’);

    p.s. $this->set works quite well in the views (just as in the controller) to set any variable for layout. That is due to progressive rendering where layout is actually the last object to be rendered.

  • Ceeram
  • @Ceeram

    well, it was too easy :)

    you can punish the poster… and thanks for pointing out the good info.

  • fly2279

    First I’d like to thank you for sharing your cake knowledge with the rest of us. I think I have more bookmarks for your blog than anything else cake related.

    I’ve been wondering how I can paginate the same model twice on the same page. There are a lot of articles/discussions out there on how to paginate multiple models but I can’t seem to find anything helpful on using the same model twice. Maybe using a custom query instead? It would also nice to be able to paginate an associated model twice, which is really what I need instead. I’m using 1.2 but would change my project if 1.3 is required. Thanks for being willing to help the community out.

  • derrick

    what is the best way to paginate tree data in CakePHP? (like threaded comments)

  • krusty999

    Hello, how to create admin and superadmin separate views with prefixes?

    In controller

    /* For Admins */
    function admin_index() {


    /* For Superadmins */
    function superadmin_index() {


    /* For Users */
    function index() {


    • It is very easy do so in 1.3. With prefix routing:

      The example shows how do so with just /admin prefix… but you can populate the array as follows:
      Configure::write(‘Routing.prefixes’, array(‘admin’, ‘superadmin’, ‘user’));

      Create the views, as shown, admin_index.ctp, superadmin_index.ctp, user_index.ctp
      Note, that you should renamed you user method with a prefix as well, if you plan to use built-in routing for that.

  • This one looks rather simple but is annoying me for a few hours…

    Machine belongsTo Category

    At machines/index I want to display only records where category is a given value (filter pagination by associated model data).

    On MachinesController I tried many variations with [un]bindModel and conditions, containable behavior and conditions, pagination and conditions. example:

    function index() {
    $this->paginate[‘Machine’] = array(
    ‘contain’ => array(
    ‘Category’ => array(‘conditions’ => array(‘Category.name =’ => ‘infra’)),
    $this->set(‘machine’, $this->paginate());

    The approach above shows every records of Machine but only those categories named ‘infra’. That is, for machines with a different category the resulting array doesn’t have an associated category, which is undesired.

    Of course I could achieve what I want with chained find()s but I am looking for a more elegant way.

    Any help would be appreciated (cake 1.2 only please).

    • Of course I just found the solution after a good night of sleep and 1 minute after posted away the question:

      function index() {
      $this->paginate[‘Machine’] = array(
      ‘contain’ => array(
      $cond = array(
      ‘Category.name’ => ‘infra’
      $this->set(‘machines’, $this->paginate($cond));

      • ouch just figured out paginator doesn’t do proper joins when tables comes from different data sources (different DBs). the code above did work this morning because i was on a single DB infra-structure at that time.

        now that i got back to my original infra-structure (app spread between multiple DBs) I realized why anything worked yesterday but worked at the first shot this morning.

        after moving all the tables to the same place and setting all models to the same database configuration I could make paginator build the SQL with all the JOINs necessary.

        the curious thing is that having the tables spread around just affected my ability to filter associated model’s data. paginator did retrieved all the associated data for display, though.

  • Oscar

    Okay, I have a question regarding JavaScript, which is not completely Cake related though..

    I’m using AutoJavascriptHelper (to automatically load JavaScript files according to the view name) and also the JsLang plugin to keep translations for JavaScript separated.

    This has helped me a long way to keep all my JS in it’s own files, instead of in the views as codeblocks. I’m still having problems with for example a jQuery UI Dialog which needs to contain a form generated with the HtmlHelper (for non-js the link will give you a separate page with the form).. Any ideas on how to solve that smoothly?

    • I am not quite clear on the question… isn’t jQuery UI dialog a simple setting, which contains the contents of dialog in a hidden div?

      p.s. While keeping separate JS files per view is very good for development (I do the same thing), once going to production you should consider blending/minifying them into a single script.
      Reason being, you are cutting down on the amount of HTTP requests and utilizing browser cache in a much better manner, which ultimately cuts down on page load for your app (depending on the traffic it might be quite dramatic).

      • Oscar

        Yup, I’m using an automatic asset packer thingie as well, works great.

        True, you can use it that way also, and hide it with JS. I did it the other way, placed the form for non-js clients on a separate page and put the dialog text right in the JavaScript call. But indeed, having the form on the same page, hiding it and using the Dialog on that instead might actually work. Wonder why I didn’t do that from the beginning.. Hmm. Will have to take another look at the code :)

  • Sage

    I’ve been trying to figure out how to easily reorder/move objects within and between parent objects. It seems replicating the functionality of the Tree behavior across multiple models (i.e. Category hasMany Pages) is what’s needed, but I think the Tree behavior can only be used on self-referencing tables.

    Additionally, using drag-and-drop to change the order within a category, or move objects between categories, seems like the best user interface to implement this functionality. But I’m not sure how one would combine the Ajax calls with the CakePHP back-end to make this all work. It’s a bit trickier than a to-do list.

    I’ve been thinking about this problem off and on for 6 months now (I keep avoiding the issue as it’s for the admin area and not the front-end of a site), so I welcome any thoughts you might have.

    • @Sage

      Please take a look at some of jQuery-related posts, which I have on this blog.
      Unfortunately the general problem is a bit too much to try to answer in simple post. It would take more than few pages to show the techniques.

      Tree behavior has to be can only be used with a properly structured table and I don’t believe it can used for related models.

  • spnkychnk


    I have succesfully developed my first cakephp app on my local machine. But the problem is i am not able to install it on my client’s plesk server. I understand it is something to do about mod rewrite not working, there is no httpd.conf folder to allow overrides.

    So, I am stuck. I appreciate any help.


    • What exactly is the error?

      You don’t need to have mod_rewrite enabled, please take a look here… (at the bottom):

      You’ll get uglier URL’s, but the app should work just fine.

      p.s. The obviously, cliche, answer is “get a better server” ;)

      • p.p.s You also don’t need to have access to httpd.conf. Any “instructions” to apache can be done via .htaccess files. (Although it does affect performance a little, but that’s a story for another day).

      • spnkychnk

        There are no errors, the cakephp default installation page looks strange. No colors(just plain white) on it with instructions to change set the security salt etc… went ahead and tried to open a controller and action.. the page cannot be found.

        Yeah I did try that but it does not work..as expected..

        I would gladly settle for this.

        But it does not work either.

        It only works when i change the url to this..

        and in this format form submit and link’s on the page dont work.

  • @spnkychnk

    No mystery here. mod_rewrite isn’t working properly.
    Bet solution is to get it fixed.

  • Pingback: City People Master (The Eagle-Tribune) | friends the movies()

  • Hello
    Quick question about ACL. In aros_acos table i see posible values for crud options: -1, 0, 1. As i figured :
    -1 == deny
    0 == inherit
    1 == allow

    Question 1. Is this true?
    Question 2. Can more values be added? For Example 2 == allow if the sun is shining :)
    Question 3. Inherit. What is this about? Who is inherited? The Aco parent of the Aro parent?

    • If there is one thing I can honestly bitch about in CakePHP, than it is the ACL implementation.
      I’d rather they had none at all, so that many upon many developers would stop breaking walls with their heads…

      Now onto your questions.

      1. yes
      2. no
      3. The inheritance is based on ARO (i.e. Group -> User)

      Take this all with the grain of salt, because I’ve never implemented an app with built-in ACL, although I’ve studied it enough to realize it is not for me ;)

  • Sarixell

    Hi Teknoid,

    Thanks for the excellent posts, I’ve learned so much trough your website and always wanted to thank you anyway ;)

    I’m very curious what software you use, I’ve read Aptana Studio, but does it need any special additional settings/modifications and do you use any additional software?

    Thanks in advance

    • Thank you.

      I am currently using Aptana Studio, however I am using an older version, because they’ve decided to drop PHP support in the new versions (i.e 2.x)… and while the older version is just fine, I feel like I’m getting left behind. (Plus I never liked the eclipse platform and all the bloat that comes with it).
      Generally Aptana is very nice, and I don’t have any complaints about it. Especially if you work in PHP/JS/CSS environment mostly.

      Otherwise I am taking a much closer look at NetBeans, especially since they promised CakePHP support in 6.9. It is looking promising because Zend and Symphony are already in (6.9 milestone 1). But switching IDE’s is like getting a new wife, have to learn all the tricks all over again.

      p.s. I do find NetBeans to be faster and “feel” less bloated.

  • Ian

    Hi teknoid,

    Any chance of a post on how to sort by “contained” models or is this currently impossible with cakephp 1.3?

    I’m currently implementing an EAV model in an app we are developing and the aforementioned behaviour would be very useful!



    • The only way you can sort by “contained” models, is if your relationship between the models is a hasOne or belongsTo … then the JOIN is created and ORDER BY clause will make sense.
      (Hint: look at the SQL debug).

      There are a few ways to force a join in cake, even listed on this very blog.

      Hope this helps a little.

      p.s. There will no significant changes made to ORM in 1.3, so the above will be true for a while.

  • Hello again

    Is there any way to customize the way the “cake bake controller” command will write a file named : nameofcontroller_adminprefix_controller.php ?

    And view files : nameofcontroller_adminprefix/adminprefix_action.ctp ?

    I want this so that i can separate the actions for different prefixes, so they will be more easy to update later.

    • Don’t understand why you’d want your controllers named like that. For one, it would not work with cake’s routing.

      Secondly bake allows you to bake admin views, and relevant admin actions (although, if I remember right, it only does basic CRUD).

  • Daniel

    Is it possible to call saveAll semi-recursively?

    for example:

    ModelA hasMany ModelB
    ModelC hasMany ModelD

    See here for code example: http://bin.cakephp.org/view/265321027

    What seems to be happening is that ModelA, ModelC and ModelD is saved, but not ModelB!?

    It appears to me that one possibility is that ModelA saveAll hasn’t yet finished, and the ModelC saveAll is “interrupting” it somehow?

  • @Daniel

    Have you tried doing this in ModelB’s afterSave()?
    I’m just kind of guessing here…

  • Charles Patterson

    When you develop an app, how do you approach it? Create all the tables first then the models, controllers, etc. or do one table at a time, then one model, one controller? Do you implement Auth and Acl while you develop or add them in after you get the core functionality working?

  • @Charles Patterson

    DB structure comes first, which I consider the “modeling” phase. Usually (and hopefully) at this stage some requirements of the app should be in place, which should govern how you structure your initial schema.

    Once a decent schema is in place, I start by building out the models. This allows to place any relevant logic in the models, before even starting to work on the controllers. Since, models are much easier to test (than controllers) it is usually a good place to begin writing test cases.

    Controllers and views kinda go hand-in-hand once the foundation is laid down.

    Auth usually comes in at a later stage, but this probably due to the fact that over the few years working with cake I got familiar enough with it, otherwise I’d recommend adding it sooner than much later. But it is not necessary, in general, to have it hooked-in off the bat.

    Acl … well I’ve never used cake’s Acl in a real-world app, because I feel it has a few fundamental problems, which I personally cannot live with :)

  • adi

    First of all, thanks for being the source of 90% of my Cake knowledge. I just picked it up a little less than a month ago and I’m loving it.

    General question: Do you plan to explore writing a Facebook app (hosted on Facebook but calls a Cake web app)? No need to cover FB api in depth but only bare minimum needed to hook it to Cake. I’ve been playing with it for the last few days and I’m sure plenty of your readers would appreciate your insight.

    Specific question: Could you please point me to the right direction on how to differentiate request made by an FB app vs that made by a regular webpage? I have digged around the RequestHandler but, one of the methods -getReferer() – is actually returning the domain name of my host instead of Facebook’s (apps.facebook.com). Naturally, I would like to handle these requests differently depending whether it comes from the website, FB, or mobile devices (a battle for another day). Anything short of having to run (hence maintain!) separate applications will be much appreciated!

  • teknoid,

    In cake 1.2, I used to check if data to be saved should be inserted or updated (by setting $model->id) in beforeValidate(). In cake 1.3, it doesn’t work anymore, if I don’t set a valid $model->id before calling $model->save(), it is always an insert.

    I could imagine it is a very common problem, but I couldn’t find the “correct” way to do it in cake. Any ideas? Thanks for your great blog and I hope I am posting it in the right thread…

    • teknoid

      Make sure that Model’s “id” is passed as part of the data array. This is the easiest way to ensure that the record gets updated.

      Or you could set it directly before the save() call.

  • Luminus

    I’m having a bit of a challenge. I have a form with 2 date fields. Start Date and End Date. I need to validate the form and make sure that End Date is greater than Start Date by a minimum of 11 weeks and a maximum of 13 weeks.

    I can’t even figure out how to make sure End Date is greater than Start Date. I’d appreciate help with this.


%d bloggers like this: