Search code examples
phpcakephproutescakephp-2.0subroutine

CakePHP: how to do sub-actions with sub-views


Apologies if I'm using the wrong terminology to describe what I'm trying to do...

I have a model/controller called Report which users can view like so:

example.com/reports/view/123

Each report hasAndBelongsToMany File objects. I need to make those files accessible like so:

example.com/reports/view/123/file/456

Or

example.com/reports/view/123/456
                          ^   ^
                          |   |
                      report  file

I'm intentionally NOT creating a separate action for files (example.com/files/view...) because access to the file is relative to the report.

What is the correct way to do this in CakePHP?

My first guess is to add logic inside of ReportsController::view that checks for the existence of the second parameter (file) and manually render() a different view (for the file) conditionally. But I'm not sure if this is "the CakePHP way".


Solution

  • You are in the right path, modify your action to accept an optional parameter.

    public function view($file = null) {
        $somethingElse = null;
        if (isset($file)) {
            //your logic
            $somethingElse = $this->Foo->bar();
        }
        $this->set(compact('somethingElse'));
    }
    

    Regarding to the view, I don't know your requirements, but I think you don't need to create a different view, you can either put a conditional in your view to show something, or (my favourite approach) create an element that will be displayed only if $somethingElse contains something. That is:

    //View code
    if (!empty($somethingElse)) {
        echo $this->element('yourAwesomeElement', compact('somethingElse'))
    }
    

    Then in yourAwesomeElement

    foreach ($somethingElse as $something) {
        echo $something;
    }
    

    The good thing is that your element will be reusable for future views that could need this.