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

与世无争的帅哥 提交于 2020-01-01 12:25:08

问题


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') ) ) );

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




回答2:


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



来源:https://stackoverflow.com/questions/1353680/belongsto-problem-in-cakephp-and-html-select-i-cant-understand-how-to-do-that

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!