Question

I have some models witch are using Doctrine nestedset feature. I want to add delete functionaly of elements from tree since that is required in my application. I was trying with snippets from documentation but I am getting a very strange error with that code.

YAML is here: http://pastie.org/820978

And I am trying with this code in my Menu class witch extends generated abstract class BaseMenu and BaseMenu extends Doctrine_Record :)

Anyway my code:

 public function getMenuItem($id)
 {
     return Doctrine::getTable('Menu')->find($id);
 }

 public function delete($id)
 {
     $item = $this->getMenuItem($id);

     //echo get_class($item); will return Menu so object exists !?

     $item->getNode()->delete();
 }

And I get this an error:

Fatal error: Call to a member function getNode() on a non-object

And I just noticed that get_class($item) is trowing a warring (so that probabbly is reason for this strange behavior):

Warning: get_class() expects parameter 1 to be object, boolean given in...

However I need a solution for this and all hints are welcome...

Was it helpful?

Solution

getNode() returns a Doctrine_Node, not a Doctrine_Record.

A Doctrine_Record can be deleted, but a Doctrine_Node cannot be deleted -- because it is not persistent anyway.

The correct logic would simply be:

$item = $this->getMenuItem($id)->delete();

Also, don't name a method in your model 'delete'!! This will override Doctrine_Record's delete() method, which will drive you crazy trying to debug it.

OTHER TIPS

I personally don't like using Doctrine::getTable("table_name") because it doesn't make the code very dry. If for some reason "table_name" ever changes, you'll have to change it in alot of places.

I used Doctrine in Zend Framework apps, so my typical pattern of use involves instantiating a protected instance of every model in my module.

Using that pattern, I would just do this in my controller

$this->_Menu
     ->getTable()
     ->find($id)
     ->getNode()
     ->delete();

If you really want to keep your functions similar, I would use something like this

 public function getMenuItem($id)
 {
     if (empty($id))
     {
         throw new Exception ("A parameter of id is required to retrieve a menu item".);
     }
     return $this->getTable()->find($id);
 }

 public function delete($id)
 {
     $item = $this->getMenuItem($id);

     if ($item instanceof Doctrine_Record == false)
     {
          throw new Exception("Item is not a valid Menu Record.");
     }

     $item->getNode()->delete();
 }

Answer is in your question: $item is not object (i guess it's value is false, but you can use var_dump($item)), because there is no row with such id in DB (also I guess your $id is null)

Warning: get_class() expects parameter 1 to be object, boolean given in...

Fatal error: Call to a member function getNode() on a non-object

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top