Hi Guys!
First of all, I just wanted to say that I've started using SilverStripe a month a go, and now, for all my incoming projects, I'll use it! Really, it's wonderful! I'm really amazed about your efforts to bring this wonderful product.
I have a question that is more of a feature request. I would like to know if it would be possible to have a toJSON method for DataObjects ? I've implemented it in DataObject class, but maybe it would be smart to include it in future releases. This method allows me the usage of the powerful evalJSON method of Prototype, because many of my Ajax requests responses are JSON strings, which 90% of the time is a representation of a DataObject...
Tell me what you would think about it. Here's my code (added to DataObject.php) : I'm not sure if I follow the coding standards, but it works. Or maybe there's already a way of doing it that I missed?
/**
* Convert this object to a JSON string. It will includes all the has_one objects recursively.
* TODO: Including default values ???
* @return string The data as a JSON string.
*/
public function toJSON() {
$array = $this->toMap();
foreach($this->has_one() as $relationship => $class) {
if (ClassInfo::exists($class)) {
$component = $this->getComponent($relationship);
$array[$relationship] = $component->exists() ? $this->obj($relationship)->toJSON() : null;
}
}
return json_encode($array);
}
From this, in javascript, it's really easy, for example, accessing let's say... a Song Object, for example, related to a File Object...
new Ajax.Request ('url/to/a/song/', {onSuccess: function (response) {
var song = response.responseText.evalJSON();
alert ('Song ID'+song.ID+' is named '+song.Name+' and is located at: '+song.Attachment.Filename);
}});
Thanks and keep on the good work!