Sunday, June 9, 2013

YII load model dynamically by model name


$phoneModel = $this->loadMyModel(100, "PhoneNumber"); 
 
public function loadMyModel($id, $modelName){
    $model = new $modelName();
    $criteria = new CDbCriteria;
    $criteria->condition = $model->getTableAlias().".id = :id";
    $criteria->params = array(
        "id" => $id
    );
    $data = new CActiveDataProvider($model, array(
        'criteria'=>$criteria
    ));
    if(count($data->getData()) > 0) {
        $data = $data->getData();
        $data = $data[0];
        return $data;
    }
    return null;
}

1 comment:

  1. Really awesome blog. Your blog is really useful for me. Thanks for sharing this informative blog. Keep update your blog.
    Hire Yii Developers in India

    ReplyDelete