Portlet snippet to display relations of a class in portlets

Hi again Yii users,

I would like to contribute a small piece of code and would be happy to get suggestions, ideas and hints for improvement or even improved code :-). I expanded the blog tutorials Portlet with the controller class ActivRecordRelation




/**

 * This Portlet ist used to show a certain relation for a certain ActiveRecord

 * in an portlet. Use this class as parent class for every relation of the Active 

 * Record class, you want to display.

 * @author bergtroll

 */

abstract class ActiveRecordRelation extends Portlet {

	

	public $recordName	= '';

	public $record		= '';

	public $relationName= '';

	public $relations	= array();

	public $view		= 'activeRecordRelation';

	

	protected function renderContent() {

		$this->relations = $this->getRelation();

		$this->render($this->view);

	}

	

	function getRelation() {

		if(empty($this->record)){$this->record = $this->getModel();}

		foreach ($this->record[0]->getRelated($this->relationName) as $relation) {

			$relations[] = $relation; 

		}

		if(empty($relations)){return array();}

		return $relations;

	}

	

	function getModel() {

		return CActiveRecord::model($this->recordName)->with($this->relationName)->findAllByPk($_GET['id']);

	}

}



To use a Portlet you simply have to extend this new class e.g. UserAddressesRelation




class UserAddressesRelation extends ActiveRecordRelation {

	protected function renderContent() {

		$this->recordName	= 'User';

		$this->relationName	= 'userAddresses';

		$this->view		= 'userAddressesRelation';

		parent::renderContent();

	}

}



Now all what is left to to is to create the referenced view which could be something like this




$i = 1; 

foreach ($this->relations as $relation) {

	//echo "<li>".$attribute['name']."</li>";

	//echo "<li>".$relation->ability['name']."</li>";

	//echo var_dump($relation);

	echo "<dl>";

		echo "<dt>Straße / Nr</dt>";

		echo "<dd>".$relation->street." ".$relation->number."</dd>";

		echo "<dt>Land / PLZ / Stadt</dt>";

		echo "<dd>".$relation->country."-".$relation->zip." ".$relation->city."</dd>";

	echo "</dl>";

	$i++;

}



As you can see, you are able to access the relations column entries for the given parent model via its name. Have fun so far.

open problems:

  • Wouldn’t it be nice, if you could decide, if the $id is passed by POST, GET or SESSION? Don’t know how to do it atm…

  • Something I tried to implement but was unsuccessfull with is, to directly pass a model to the portlet. That would be rather usefull, if your model has more than a few relations. You could load your model with all appended relations once, pass the references to the portlets and they would display it. No need for repeated SQL Queries. Unfortunately I ran into an "Property is read only" error, from which I do not know, why it occurs.

Good night,

Bergtroll