Ajay K
Ajay K

Reputation: 354

CakePHP : view is out of sync with controller

I have encountered a weird problem, where in the Controller is passing a single record from a table, but the View ends up displaying the entire table.

I have extensive logging and am pretty sure, that the Controller is passing a single record via the $this->set().

Controller (ContactsController : show_list)

$arr_contacts = $this->Contact->find(
    'all', 
    array(
        'conditions' => array(
            'Contact.state_id' => $i_state_id, 
            'Contact.city'=> $str_city
        ),
        'fields' => array(
            'Contact.id', 
            'Contact.name',  
            'Contact.city'
        ),
        'recursive' => -1
    )
);

$contacts = $arr_contacts;
$this->log ($contacts, 'debug');
$this->set('contacts', $this->paginate());
$this->log(__FUNCTION__." : ".__LINE__, 'debug' );

Output in log:

 Debug: Array
(
    [0] => Array
        (
            [Contact] => Array
                (
                    [id] => 504
                    [name] => Michael
                    [city] => New York
                )

        )

)


Debug: show_list : 303

In the view file (show_list.ctp), I have

 <div class="contacts index">

   <?php echo print_r($contacts);?> 

The view file, prints a list of all records from the table. The SQL dump that cakephp displays, shows that additional SQL calls are being made. However, it isn't clear, where those calls are coming from.

The rest of the controllers and actions seem to be working fine, ruling out any corruption issues.

Has anyone encountered a similar situation before? Any pointers?

Upvotes: 0

Views: 122

Answers (2)

AKKAweb
AKKAweb

Reputation: 3817

If you do not need Paginate as it seems you don't since you are only getting a single line of entries from Db, then you should rewrite your $this->set() as such:

$this->set('contacts',$contacts);

If you need Paginate (???), then you need to set you entire function as such:

$this->paginate = array(
    'conditions' => array(
        'Contact.state_id' => $i_state_id, 
        'Contact.city'=> $str_city
    ),
    'fields' => array(
        'Contact.id', 
        'Contact.name',  
        'Contact.city'
    ),
    'recursive' => -1
);

$this->log ($this->paginate, 'debug');
$this->set('contacts', $this->paginate());
$this->log(__FUNCTION__." : ".__LINE__, 'debug' );

Upvotes: 1

JvO
JvO

Reputation: 3106

You pass the output of the paginate() function to your view, which is different from your own find() call.

If you want the same conditions as with your find(). pass them to paginate() (Tip: put your conditions in an array first)

Upvotes: 2

Related Questions