We are moving our forum in GitHub Discussions. For questions about Phalcon v3/v4 you can visit here and for Phalcon v5 here.

Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Deleting records: model's beforeDelete event and delete return value

Hi Everyone, following the documentation

http://docs.phalcon.io/pt/latest/reference/models.html#deleting-records

I've create a model with a beforeDelete method that contain a rule not to delete a certain record, lets say for example when the 'year' value of the record is 3000.

    public function beforeDelete()
    {
        if ($this->year == 3000) {
            echo "Cannot delete Robot of year 3000";
            return false;
        }
        return true;
    }

Then I've created a controller action where I get this record and call delete on it

    public function deleteAction()
    {
        $robot = Robots::findById(10);

        if ($robot != false) {
            if ($robot->delete() == false) {
                echo "Sorry, we can’t delete the robot right now: \n";
                foreach ($robot->getMessages() as $message) {
                    echo $message, "<br />";
                }
            } else {
                echo "The robot was deleted successfully!";
            }
        }
    }

This is what I get if I run that action

Cannot delete Robot of year 3000The robot was deleted successfully!

The record is not deleted from DB, but $robot->delete() is return TRUE, is that the correct behaviour? Shouldn't return FALSE?

Thank you



33.7k
edited Nov '14

Maybe removing return true; from the event.

Or return false; inside the IF from the event , because the API shows this:

public function beforeSave()
   {
     if ($this->name == 'Peter') {
        $message = new Message("Sorry, but a robot cannot be named Peter");
        $this->appendMessage($message);
     }
   }
edited Nov '14

use

Robots::findFirstById(10);

not

Robots::findById(10);

All should be Ok.



3.5k
Accepted
answer
edited Nov '14

I debugged again, and found that the

Robots::findById(10);

return

object(Phalcon\Mvc\Model\Resultset\Simple)

but

Robots::findFirstById(10);

return

object(Robots)

I think, that is why $robot = Robots::findById(10); $robot->delete() return true, because beforeDelete was set for Robots object not for Simple object.

Maybe, that's why...

Hi vitaliykoziy, you got it, findBy will return a resultset and both object have the delete method.

Thanks