1
votes

quick best-practices question(s).

I have as association as follows: User hasOne UserBasicInfo
UserBasicInfo has a select element for country (in which the user is living).
The select element is populated by a simple 'countries' table (id, country name, abbreviation)

Is it best to use Model::query() for getting the data from the countries table? Or should I create a model for this data?

If creating a model, should I use an association with the UserBasicInfo model, Or should I just use the $uses variable?

If it sways the answer, there are actually many select fields populated in a similar fashion.

3

3 Answers

1
votes

If it sways the answer, there are actually many select fields populated in a similar fashion.

It might. Do you have multiple Country select boxes, or are these select fields all pulling from different tables? If the former, you can use the options key in FormHelper::select() to populate multiple selects from one array:

Controller:

$this->loadModel('Country');
$this->set('countries', $this->Country->find('list'));

View:

$this->Form->select('UserBillingInfo.country_id', $countries);
$this->Form->select('UserShippingInfo.country_id', $countries);
etc...

Otherwise, I typically handle this situation by creating the proper associations between my models, and then using either Model::find('list') or a custom Model method to retrieve the options. If you name your variables properly, the options variable will automatically be used as the options for your select:

Controller:

$this->set('countries', $this->User->UserBasicInfo->Country->find('list'));

View:

$this->Form->input('UserBasicInfo.country_id');
1
votes

Model::query() is never best for doing anything in cakephp.

in the UsersController action you are using

$this->set('countries', $this->User->Country->find('list'));

in the edit / add form

$this->Form->input('country_id');
0
votes

I use view helper for this kind of select elements. If I take your case as an example, I'd do in this way:

controller:

class UsersController extends AppController {
      ....
      public $helpers = array('Common');
      ....
}

helper:

class CommonHelper extends AppHelper {
      ....
      public function get_country_list() {
            App::import( 'Model', 'Country' );
            $objCountry = new Country();
            $countries = $objCountry->find( 'list' );
            return $countries;
      }
      ....
}

view:

....
echo $this->Form->input('country_id', array(
     'options' => $this->Common->get_country_list(),
     'value' => !empty($data['UserBasicInfo']['country_id']) ? $data['UserBasicInfo']['country_id'] : ''
));
....

The condition is that you must have a Country model. In this way you can populate any drop-down menu. Cheers!!!