Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

Data Model Questions

Overloading getters in DataObject not working


Reply

3 Posts   578 Views

Avatar
Urug

4 August 2013 at 2:48am (Last edited: 4 August 2013 2:50am), Community Member, 4 Posts

Calling $this->Property or $this->obj('Property') in DataObject overloaded method getProperty() results in [Notice] Undefined property: DataObject::$Property.

Interesting fact: Calling $this->Nonexistent (where Nonexistent is any undefined property) doesn't result in any Notice/Error whatsoever.

Example:

class News extends DataObject {
public static $db = Array(
'Title' => 'Text',
'Content' => 'HTMLText',
);

public function getTitle() {
Debug::dump($this->Content); //works fine as we are not in getContent() method
Debug::dump($this->AnythingUndefined); //doesn't cause any trouble, returns empty string
return $this->Title; //source of the problem
}
}

using SilverStripe 3.0.5

Avatar
simon_w

4 August 2013 at 8:07am Forum Moderator, 474 Posts

That is PHP protecting you from infinite recursion, since $this->Title would end up calling $this->getTitle(), which would access $this->Title and call $this->getTitle() and so in.

To get the actual value, use $this->getField('Title'); Likewise, in setTitle($value), you'd use $this->setField('Title', $value);

Avatar
Urug

4 August 2013 at 12:02pm (Last edited: 4 August 2013 10:03pm), Community Member, 4 Posts

Thanks for the answer, it truly works, but it has a flaw. getField('Property') returns raw data, which means I can't do this for example:

public function getDate() {
return $this->getField('Date')->Day();
}


since the getField('Date') doesn't return object Date.

Nevertheless tutorial at http://doc.silverstripe.org/framework/en/topics/datamodel (section Overloading) is misleading and should be corrected imo.