1
votes

I'm using cakephp 2.3.0. What I'm trying to do is have the user click a link (in the form of an image) and that user action would delete some data from the database for that user.

In my view, I have this code snippet, which is actually a column in a table. For the word 'delete', I want that to be an image (using $this->Html->image()), but cakephp complains about that. According to the API, that parameter can only be a string.

$this->Form->postLink(
                'delete', 
                array('action' => 'deleteActivity', $myActivity['Activity']['id']),
                array('confirm' => 'Are you sure?')),

Here is my function in my controller that I'm attempting:

public function deleteActivity($id) {

        if ($this->Post->delete($id)) {             
            $this->Session->setFlash('The activity with id: ' . $id . ' has been deleted.');
            $this->redirect(array('action' => 'landingPage'));
        }
    }

I get the error below. Appears that wrapping a form tag with post isn't going to work. Is what I'm trying to do the best practice way of doing this, in CakePHP?

Fatal Error

Error: Call to a member function delete() on a non-object

Here is the generated HTML:

<td><form action="/activities/index.php/activities/deleteActivity/4"      name="post_515496f40ca77" id="post_515496f40ca77" style="display:none;" method="post">    <input type="hidden" name="_method" value="POST"/></form><a href="#" onclick="if (confirm(&#039;Are you sure?&#039;)) { document.post_515496f40ca77.submit(); } event.returnValue = false; return false;">delete</a></td>   
1

1 Answers

3
votes

The error:

The error basically says "Hey, there's no such thing as the Post object, so we're not sure what to do with this 'delete' method you're trying to access" (in other words, the Post model isn't yet loaded)

Further explanation / solution:

You don't inherently have access to models other than the one who's controller you're currently in.

So in your case, you cannot directly access the Post model without either loading it:

$this->loadModel('Post');
$this->Post->delete($id);

or, if it's associated with the current model (eg. Activity), you can access it through that like this:

$this->Activity->Post->delete($id);