Yii: Dynamically Add Attributes To Model

If there are virtual attributes in your model, and you want to serialize the output as JSON, those attributes are not going to show up.

You can add the following code to your model:

public function getAttributes($names=TRUE)
{
    $attrs = parent::getAttributes($names);
    if(! self::$SERIALIZE_EXTRA_ATTS) return $attrs;
    $attrs['zipCounter'] = $this->zipCounter;
    $attrs['avg_x'] = $this->avg_x;
    $attrs['avg_y'] = $this->avg_y;

    return $attrs;
}

Then, in your controller:

public function actionQuestion($id='3')
{

    $question = Answer::questions($id, 'short');
    //Total # Citizens
    $total_citizens = Citizen::model()->count();
    //# of Citizens by zip
    //# of answers by citizen.
    $zip_criteria = new CDbCriteria;
    $zip_criteria->with = ('answers');
    $zip_criteria->group  = 'zip_code';
    $zip_criteria->select = 'id, zip_code, count(*) AS zipCounter, AVG(x_location) as avg_x, AVG(y_location) as avg_y';
    $zip_criteria->condition  = 'answers.question_id='.$id.' AND zip_code!=""';
    $zip_criteria->order  = "zipCounter DESC";

    $data = array(
          'answer'=>Answer::model(),
          'citizen'=>Citizen::model(),
          'question'=>$question,
          'total_citizens'=>$total_citizens,
          "total_zip" => Citizen::model()->findAll($zip_criteria),
    );

    if(!Yii::app()->request->isAjaxRequest)
    {
        Citizen::$SERIALIZE_EXTRA_ATTS = TRUE;
        // Citizen::
        unset($data['answer']);
        unset($data['citizen']);
        $this->renderJSON($data);
    } else $this->render('reporting/question', $data);
}