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 :)!

39 thoughts on “Help me, help you

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

    http://gist.github.com/337366

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

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

    1. My best suggestion would be to use ajax pagination. Granted it better implemented out-of-the box in 1.3
      But in my 1.2 projects I found this little gem of code very useful:
      http://bakery.cakephp.org/articles/view/easy-ajax-pagination-using-jquery

      For 1.3, check out this on Mark Story’s blog:
      http://www.mark-story.com/posts/view/creating-simple-ajax-pagination-with-cakephp-1-3-and-mootools

      Actually, I’d recommend switching to 1.3 regardless as it is a much improved code-base.

      1. @Neil Crookes
        Yes, and probably have a little loader/spinner displayed in the place-holder div while waiting for the server to respond.

      1. hmmm, so first i should get all comments with parent_id = NULL:

        $comments = $this->paginate(‘Comment’, array(‘Comment.paren_id’ => NULL));

        then:

        foreach ($comments as $comment) {
        $children = $this->Comment->find(‘threaded’, array(
        ‘conditions’ => array(
        ‘Comment.lft >’ => $comment[‘Comment’][‘lft’],
        ‘Comment.rght $comment[‘Comment’][‘rght’]
        ));
        }

        am i right?

  4. 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() {

    }

    1. It is very easy do so in 1.3. With prefix routing:
      http://book.cakephp.org/view/950/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.

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

    1. 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(
      ‘Category’,
      ),
      );
      $cond = array(
      ‘Category.name’ => ‘infra’
      );
      $this->set(‘machines’, $this->paginate($cond));
      }

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

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

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

      1. 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 :)

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

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

  8. Hi,

    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.

    Thanks.

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

      2. 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.
        http://www.mydomainname.com/index.php/controllername/actionname/param.

        But it does not work either.

        It only works when i change the url to this..
        http://www.mydomainname.com/index.php?controllername/actionname/param.

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

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

    1. 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 ;)

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

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

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

    Cheers,

    Ian

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

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

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

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

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

  15. @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 :)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s