2
votes

Lets say I have a Company model and Companies controller. Foreign keys in the company table include time_zone_id, station_id, state_id, city_id.

I had actions in the CompaniesController to add, edit, view Companies. For adding and editing, I need dropdown lists of all the foreign key associations (time zones, states, cities, stations). So in those actions, I find myself writing lots of the following for each action:

$this->set('cities', $this->Station->City->find('list'));
$this->set('states', $this->Station->State->find('list'));

etc...

Seems like a lot of code repetition. Is there a better way to go about this?

2

2 Answers

0
votes

Add a pre-view callback such as afterFilter to your Companies controller:

function afterFilter() {
    // conditional ensures only actions that need the vars will receive them
    if (in_array($this->action, array('index', 'view', 'edit'))) {
        $this->set('cities', $this->Station->City->find('list'));
        $this->set('states', $this->Station->State->find('list'));
    }
}

afterFilter will be called after every Companies controller action.

0
votes

Filters are good, as in webbiedave's answer, but it might get complicated if you end up with a lot of conditional logic.

Another option is that you can define methods in a controller than aren't intended as actions/views: it's a normal PHP object afterall. Better yet, if using PHP5, you can declare these methods private to ensure they cannot be mistaken for actions...

For example, you could define the following in your controller:

private function _populate_dropdowns() {
    $this->set('cities', $this->Station->City->find('list'));
    $this->set('states', $this->Station->State->find('list'));
}

Then call it at the start of any action that needs it:

public function add() {
    $this->_populate_dropdowns();
    // ... 
    // add code
}

public function edit() {
    $this->_populate_dropdowns();
    // ... 
    // edit code
}