开发者

CakePHP assocation question

I'm creating a small timesheet application. Timesheets have athletes, and each athlete has personal split times (like in running, or race car driving)

An Athlete hasMany Run, a Run belongsTo Athlete, An Athlete hasAndBelong开发者_C百科sToMany Timesheets (and vice versa). A Timesheet hasMany Run, and finally a Run belongsTo Timesheet.

When I'm adding new runs in my view, I'm unable to get anything but the athlete_id in the select box. I'd really like to have their names instead. Instead of

<?php echo $run['athlete_id'];?>, I've tried <?php echo $athlete['Athlete']['last_name'] ?> but I can't seem to get it to work. Any help would be greatly appreciated. Thanks!


Without knowing exactly how you are building your forms/data it is hard to tell, but how I would do it is.

In the RunController add

$athletes = $this->Run->Athlete->find('list');
$this->set('athletes', $athletes);

and then in the View use this form helper line.

<?php echo $form->input('Run.athlete_id', array('type' => 'select', 'options' => $athletes)); ?>

This should work, there is also a way to use 'compact' to make it a little easier but the above should work fine.

---- BEGIN EDIT ----

I did a little research and found the compact method.

In your RunController use

$athletes = $this->Run->Athlete->find('list');
$this->set(compact('athletes'));

and then in your View use

<?php echo $form->input('Run.athlete_id'); ?>

and the form helper will automatically find the compacted Athlete array and build the select.

---- END EDIT ----

Hope this helps.

Cheers, Dean


Try printing out the content of the $run: print_r($run) and see if the ['Athlete'] is there.

If not, you might have to manually contain the Athlete model when you do your run query: $this->Run->contain('Athlete');


Don't forget to use the displayField property of the Model class i.e.

<?php
    class Athlete extends AppModel {
        public $name = "Athlete";
        public $displayField = "name"; // the field name that has the athletes name in it
    }
?>

http://book.cakephp.org/view/438/displayField

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜