开发者

cakePHP: automagic form elements, populating selection list

开发者 https://www.devze.com 2023-02-08 17:53 出处:网络
I have two tables, users{name,id,age_range_id} and age_ranges{id,range_name}. There are also two models, controllers and the proper view files.

I have two tables, users{name,id,age_range_id} and age_ranges{id,range_name}.

There are also two models, controllers and the proper view files.

In the views I have the adduser.ctp file, which hold the proper form.

What I want is to have an input (select) that will hold the options from age_ranges.name field.

So, in the users model I've added var $hasMany = 'age_ranges'; What's next?

I know that I can use the $this->set to store the options as an array in the controller and then use it in the view.

but I assume(wrongly?) that by relating the mod开发者_开发知识库els there is an 'automatic' way to do it. Which lead me to the question: how?


I won't repeat what Thorpe and dogmatic have already written. They are both correct.

However, although it's difficult to be sure without seeing your model files, commonsense tells me that in the User model the relationship should be User:hasOne:AgeRange and in the AgeRange model it is AgeRange:hasMany:User, not the other way round as you have written.

Also, you do not specify the table name ('age_ranges') in the relationship, but the Model name ('AgeRange').

See these pages in the manual:

http://book.cakephp.org/view/1001/Understanding-Models & http://book.cakephp.org/view/1039/Associations-Linking-Models-Together


add $this->set('ageRanges', $this->User->AgeRange->find('list')); to the controller action

then add $this->Form->input('age_range_id') to the form


You can do this:

$this->User->AgeRange->find('list') and pass that to the view for a select statement

0

精彩评论

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