Yii Framework Forum: EJsonBehavior Enhancement - Yii Framework Forum

Jump to content

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

EJsonBehavior Enhancement Adding more features to ejsonbehavior extension

#1 User is offline   Abdulrahman Ibrahim 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 1
  • Joined: 31-August 15

Posted 31 August 2015 - 04:40 AM

After looking at the comments in the EJsonBehavior extension page and according to my needs, I added the following features to the extension:

  • It includes only relations specified by (with) in the model, which are loaded by Eager Method.
  • It gives you the choice to return an array instead of JSON encoded string that is useful in case of (findAll) query.

This is EJsonBehavior Class:
class EJsonBehavior extends CBehavior{
	private $owner;
	private $relations;
	public function toJSON($encode = true){
	    $this->owner = $this->getOwner();
	    if (is_subclass_of($this->owner,'CActiveRecord')){
	        $attributes     = $this->owner->getAttributes();
	        $this->relations= $this->getRelated();
	        foreach($this->relations as $key => $value)
	            $attributes[$key] = $value; 
	        	return CJSON::encode($attributes);
	        	return $attributes;
	    return false;
	private function getRelated()
		$related = array();
		$obj = null;
		foreach($md->relations as $name=>$relation){			
				$obj = $this->owner->getRelated($name);
				$related[$name] = $obj instanceof CActiveRecord ? $obj->getAttributes() : $obj;
	    return $related;

And this example shows you how to use it in (findAll) context:

$devices = Device::model()->with('position')->findAll();
$json = array();

foreach($devices as $device){
	$json[] = $device->toJSON(false, false);			
header('Content-type: application/json');
echo CJSON::encode($json);


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