CakePHP n00b Tip #1

14 06 2007

This marks the start of an ongoing series of tips for newcomers to Cake. It will be based on posts to the Cake PHP Google Group as well as things that I myself come across.

Action parameters from the Url

Passing parameters to actions via the url is simple. Urls are in the format and so on. Your actions will be called with parameters in the order they are in the url .ie action($param1, $parm2)

This is a common scenario when using hasMany, for example Company hasMany Employees. On the company details view you want to add a “New Employee” link that automatically assigns the company_id.

Your Employee::add action looks like:

function add($company_id){
            //success logic
        } else {
            //fail logic
    $this->set('company_id', $company_id);

$company_id is passed in from the url. The link should look like /emplyees/add/XX where XX is the company id. This is simple to do in your companies/view.ctp like so.
<?= $html->link('New Employee', '/employees/add/'.$this->data['Company']['id']); ?>

And finally in the employees/add.ctp we use a hidden form field to ensure that the correct company id is used.
<?= $form->hidden('Employee.company_id', array('value' => $company_id); ?>




8 responses

10 07 2007
Brendon Kozlowski

Was “Goggle” (aka Google) mistyped purposefully due to the supplied content in the post? 😀

11 07 2007

Oops, fixed the typo. Thanks.

12 07 2007
Brendon Kozlowski

Heh, I actually kind of liked the typo, I thought it meshed well. 😉

23 08 2007

Such things like child forms should autobaked 🙂

11 03 2008

Thx alot. I just started with CakePHP and spent nearly 5 hours reading manuals and searching google for doing exactly this. Glad I found your noob tips.

1 12 2008

I am a CakePHP noob and definitely found this noobishly useful. Thanks a lot. It’s posts like this one that stops me from going back to my old ugly, messy, PHP coding ways. Must fight the temptation….

24 11 2011
Flight Ticket Booking

Nice posting ..keep updating us..

24 11 2011
Promotion Code

hey..i like the typo..keep giving this type of information

Leave a Reply

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

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

Google photo

You are commenting using your Google 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

%d bloggers like this: