Yii Framework Forum: CJSON encode ignoring CActiveRecord getter - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

CJSON encode ignoring CActiveRecord getter Rate Topic: -----

#1 User is offline   aschafer324 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 4
  • Joined: 16-February 13

Posted 26 November 2014 - 05:53 PM

I have an AR class that includes the following virtual attribute getter function that returns a constructed url:

public function getUrl()
{
return $baseUrl . $this->id;
}

When I use CJSON to serialize an instance of my object:

CJSON::encode($myObjectInstance)

The resulting json does not include my url attribute - is there a way to designate this virtual attribute as serializable by CJSON?
0

#2 User is offline   alirz23 

  • Master Member
  • PipPipPipPip
  • Yii
  • Group: Members
  • Posts: 1,086
  • Joined: 08-August 12
  • Location:Durban, South Africa

Posted 27 November 2014 - 03:25 AM

you can write a simple method to include that attribute something like this
<?php
// this goes in your model
public function toJson()
{
	array_push($this->attributes, $this->getUrl());
	return JSON::encode($this->attributes);
}

// then in your controller you can call
echo $myObject->toJson();

2

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users