快速最佳做法问题。
我的关联如下:
用户拥有一个UserBasicInfo
UserBasicInfo有一个国家的选择元素(用户在其中居住)
select元素由一个简单的'countries'表(id,country name,abbreviation)填充
最好使用Model :: query()从countries表中获取数据吗?或者我应该为这些数据创建一个模型?
如果要创建模型,我应该使用与UserBasicInfo模型的关联,还是应该只使用$ uses变量?
如果它摇摆不定,实际上有很多选择字段以类似的方式填充。
答案 0 :(得分:1)
如果它摇摆不定,实际上有很多选择字段以类似的方式填充。
可能。您是否有多个国家/地区选择框,或者这些选择字段是否都来自不同的表格?如果是前者,您可以使用FormHelper::select()
中的options
键从一个数组中填充多个选项:
$this->loadModel('Country');
$this->set('countries', $this->Country->find('list'));
$this->Form->select('UserBillingInfo.country_id', $countries);
$this->Form->select('UserShippingInfo.country_id', $countries);
etc...
否则,我通常通过在模型之间创建正确的关联,然后使用Model::find('list')
或自定义模型方法来检索选项来处理这种情况。如果正确命名变量,options变量将自动用作select的选项:
$this->set('countries', $this->User->UserBasicInfo->Country->find('list'));
$this->Form->input('UserBasicInfo.country_id');
答案 1 :(得分:0)
Model :: query()绝不是最好在cakephp中做任何事情。
您正在使用的UsersController操作中的
$this->set('countries', $this->User->Country->find('list'));
编辑/添加表单中的
$this->Form->input('country_id');
答案 2 :(得分:-1)
我对这种select元素使用了view helper。如果我以你的情况为例,我会这样做:
控制器:
class UsersController extends AppController {
....
public $helpers = array('Common');
....
}
助手:
class CommonHelper extends AppHelper {
....
public function get_country_list() {
App::import( 'Model', 'Country' );
$objCountry = new Country();
$countries = $objCountry->find( 'list' );
return $countries;
}
....
}
视图:
....
echo $this->Form->input('country_id', array(
'options' => $this->Common->get_country_list(),
'value' => !empty($data['UserBasicInfo']['country_id']) ? $data['UserBasicInfo']['country_id'] : ''
));
....
条件是您必须拥有国家/地区模型。通过这种方式,您可以填充任何下拉菜单。干杯!!!