okwme
okwme

Reputation: 795

cakephp how do you call a controller's action inside a model

I'm working within afterSave in my messages model. I'd like to send an email every time a message is created to notify the recepient of their new message. I have an action inside of the messages controller that sends the email and i'd like to call it from afterSave.

I've tried calling it like this:

function afterSave($created){
    if($created){
        $this->msgToEmail($this->data);
    }
}

i get a sql error because it looks for the function inside of the model instead of the controller.

How do i declare the model function? is it possible?

Upvotes: 0

Views: 1090

Answers (2)

mark
mark

Reputation: 21743

You use model methods inside other models, never ever a controller!

So make your code a model method. then you can easily use it.

In 1.3 You can hack the component in your model method for now. Until you can finally upgrade to 2.x.

App::import('Component', 'Email');
$this->Controller = new Controller();
$this->Email = new EmailComponent(null);
$this->Email->initialize($this->Controller);
// from/to/subject/...
$this->Controller->set('text', $this->data['Model']['content']);
return $this->Email->send();

Upvotes: 4

chronon
chronon

Reputation: 568

To declare a model method, just put it in your model (instead of your controller).

In your Model file:

public function msgToEmail($data) {
    // code to send your email...
}

Also, don't forget to import CakeEmail at the top of your model file:

App::uses('CakeEmail', 'Network/Email');

Upvotes: 1

Related Questions