1
votes

I am working on a SilverStripe project. Now I am trying to create DataObject instance from an array. This is how I created.

$dataObject = \SilverStripe\ORM\DataObject::create([
   'Title' => 'This is my title',
   'Body' => 'This is the body',
   'Intro' => 'Thi is the intro',
])

The object is created. The problem is when I try to access the Title value of the object. I printed out the Title field like this.

echo $dataObject->Title;

It is printing out # / hash instead of printing out the Title value. When I convert it into array using toMap(), I can see the Title value is there. But I want to get the Title value from the object. What is wrong and how can I fix it?

1

1 Answers

2
votes

We must create our own custom class that extends DataObject and use that. DataObject does not have a Title field, Body field, Intro field or even a database table to store data in.

For example we could call our class Course:

use SilverStripe\ORM\DataObject;

class Course extends DataObject
{
    private static $db = [
        'Title' => 'Varchar(255)',
        'Body' => 'Text',
        'Intro' => 'Text',
    ];
}

Then we can use our Course class as follows:

$course = Course::create([
   'Title' => 'This is my title',
   'Body' => 'This is the body',
   'Intro' => 'Thi is the intro',
]);

$course->write();

echo $course->Title;