Search code examples
phpcakephp

CakePHP: creating a dropdown on homepge through an element problem


I try to create a search function on my homepage where the user can limit the search results by country.

It all works in my posts/index controller whereby the country list is automatically retrieved by a find('list).

However, on the homepage, the country dropdown remains empty. Below some code: I try to retrieve the dropdown by using requestAction (please omit 'requestAction is slow from the comments, thanks)

homesearch.ctp ELEMENT:

<?php $this->requestAction('countries/getCountries');?>
<?php
echo $this->Form->create('Post', array(
    'url' => array_merge(array('controller' => 'posts','action' => 'index'), $this->params['pass'])
    ));
echo $this->Form->input('title', array('div' => false, 'empty' => true, 'label' => false)); 
echo $this->Form->input('country_id');
echo $this->Form->submit(__('Search', true), array('div' => false));
echo $this->Form->end();

?>

getCountries function in countries controller:

function getCountries(){
    $countries = $this->Country->find('list');
    $this->set(compact('countries'));
}

Before diving into alternatives (loadmodule('Country') in PagesController etc), I think I am doing something wrong, there is no data flowing back from the requestAction function as debug taught me.

How do you guys wash this cow? Thanks!


Solution

  • ... (please omit 'requestAction is slow from the comments, thanks)

    For improved performance, replace:

    <?php $this->requestAction('countries/getCountries');?>
    

    with:

    <?php $this->viewVars['countries'] = ClassRegistry::init('Country')->find('list'); ?>
    

    This approach doesn't generate a second request.