BelongsTo problem in cakephp and html select, i can't understand how to do that
Asked Answered
S

2

4

Simple question by a cakephp noob:

i have two models, Player and Team.

Team has an id (int) and a cool_name (varchar).

Player has an id (int), a cool_name (varchar) and a reference for the team table, team_id (int).

Cool_name instead of name because i don't have tables in english, so i can't use the field 'name'.

So, a team hasMany players and a player belongsTo team.

My Player model:

class Player extends AppModel {
    var $name = 'Player';
    var $belongsTo = array('Team');
}

(Team model has nothing other than name inside)

PlayersController:

class PlayersController extends AppController {
    var $name = 'Players';

    function add() {
          $this->set('teams', $this->Player->Team->find('list'));
   //then save... 
    }

In the add view of the player:

//...
echo $form->input('squadra_id');
//...

Ok so i have a select with the team ids inside; i don't want the id, but the name of the team and then save the id: something like (in html)

<select name="data[Player][team_id]" id="PlayerTeamId">
<option value="1">Cool Name 1</option>

<option value="2">Cool Name 2</option>
<!-- -->
<option value="{team id}">{team cool name}</option>
</select>

How can i do?

  • Solution -

instead of

$this->set('teams', $this->Player->Team->find('list'));

put this

$this->set('teams', $this->Player->Team->find('list', array('fields' => array('cool name') ) ) );
Spurge answered 30/8, 2009 at 11:32 Comment(0)
E
1

Since you're doing a find( 'list' ) against your Team model and that model has a name property (which CakePHP recognizes as a display field by default), what you should be getting back is an associative array where the key is the team ID and the value is the team name. Couple that with the fact that you're setting that array in a variable named teams and Cake will do the work for you.

In your form, I'm not sure where 'squadra_id' came from, but change that to 'teams' and you should see the select list populate nicely:

echo $form->input( 'teams' );

If I understand you correctly, you have everything correct to enable this "magic" except for the input definition in your view. You can read more about how to use find( 'list' ) to automagically populate select boxes at http://book.cakephp.org/view/189/Automagic-Form-Elements.

Hope this helps.

Educate answered 30/8, 2009 at 13:16 Comment(1)
ah i'm sorry i've translated the example from italian to english so my text "nome" became "name".. magic doesn't work for me for that reason (this explains also the origin of 'squadra_id', that is the translation of 'team_id') i'll correct that in the post. thanks for help in the meanwhileSpurge
B
0

The data is not getting validated with the belongsTo model ! I can use and team_id and it works !!

Bonner answered 13/12, 2013 at 12:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.