Captain Kenpachi
Captain Kenpachi

Reputation: 7215

CakePHP controller method not writing to the DB

I am calling one controller method from another controller's method. I can confirm that the method is being called because when I do a print_r on the passed data, I see everything I expect. My problem is that when I call $this->Log->save($this->data) nothing is written to the DB. I am a .NET developer, hence I know preciously little about cakePHP, but I know that this is the way one is supposed to save stuff to the DB, hence I am majorly stumped.

<?php
//The calling controller
App::import('Controller', 'Logs');
class othAuthComponent extends Object //I noticed this inherits from Object, 
                                      //but it doesn't seem to be a problem
{
    function SomeFunction()
    {
        //create instance of our Logs controller as per example
        $Logger = new LogsController;
        $Logger->constructClasses();
        $Logger->cms_addlog($user['User']['name'].' Logged in', $user['User']['id']);
    }
}
?>

And the offender:

<?php
//the called controller
class LogsController extends AppController 
{
    function cms_addlog($note,$ba_id)
    {

        $this->Log->create();
        $curDateTime = getdate();

        $this->data['LogTime'] = $curDateTime;
        $this->data['Note'] = $note;
        $this->data['brandactivatorid'] = $ba_id;
        //print_r($this->data);
            //die();
        $this->Log->save($this->data);
    }
}
?>

Upvotes: 0

Views: 144

Answers (2)

nanoman
nanoman

Reputation: 1069

You're not supposed to call Controller actions/methods from anywhere in your code. Controller actions are meant to be directly accessed from the browser.

The clean way is to implement a addLog method in your model and call that one either from the controller, or from the component.

Please read http://book.cakephp.org/2.0/en/getting-started/cakephp-structure.html and http://book.cakephp.org/2.0/en/cakephp-overview/understanding-model-view-controller.html for further reference.

Upvotes: 1

Joey
Joey

Reputation: 21

The correct way to do this is to make the cms_addlog function part of the Log model.

Then call

$this->Log->cms_addlog($user['User']['name'].' Logged in', $user['User']['id']);

Upvotes: 2

Related Questions