Vince
Vince

Reputation: 3288

Doctrine ORM object type column not being serialized

I am working on a REST api and I have a column of type object as a property of my User class. In my User entity I have:

/**
 * @var stdClass
 * @Serializer\Expose
 * @Serializer\Groups({"list", "details"})
 * @ORM\Column(type="object", name="notifications")
 */
protected $notifications;

When a new user is created, I initialize this field using default values for the different notifications like so:

$_notifications = new \stdClass();

$_notifications->voucherSold = true;
$_notifications->voucherRedeemed = true;
$_notifications->newConnection = true;

$user->setNotifications($_notifications);

I can see this field is being written to the database correctly. In my db, under the notifications column, I get:

O:8:"stdClass":3:{s:11:"voucherSold";b:1;s:15:"voucherRedeemed";b:1;s:13:"newConnection";b:1;}

But when I load this User via the API, I end up with an empty object in the notifications field:

{
  "resource": "vendors/39",
  "id": 39,
  "email": "[email protected]",
  "notifications": {},
  "company": "",
  "address": "",
  "city": "",
  "state": "",
  "zipcode": "",
  "phone": "",
  "website": ""
}

I can't figure out why the value isn't coming through. Any ideas? Thanks.

Upvotes: 2

Views: 970

Answers (1)

samlev
samlev

Reputation: 5942

The json encoder may only convert arrays to json, and will simply set an object as an object {} instead of looking into it for fields, etc.

Try casting the $_notifications object to an array before returning it:

$user->setNotifications((array) $_notifications);

Upvotes: 2

Related Questions