schmunk42 / gii-template-collection

Gii Template Collection with code templates for models and CRUDs
https://github.com/schmunk42/gii-template-collection
51 stars 20 forks source link

reimplement getRelatedSearchModel() #36

Closed schmunk42 closed 11 years ago

schmunk42 commented 11 years ago

Branch "back-to-the-roots"

/**
 * Returns a model used to populate a filterable, searchable
 * and sortable CGridView with the records found by a model relation.
 *
 * Usage:
 * $relatedSearchModel = $model->getRelatedSearchModel('relationName');
 *
 * Then, when invoking CGridView:
 *    ...
 *        'dataProvider' => $relatedSearchModel->search(),
 *        'filter' => $relatedSearchModel,
 *    ...
 * @returns CActiveRecord
 */
public function getRelatedSearchModel($name)
{

    $md = $this->getMetaData();
    if (!isset($md->relations[$name])) {
        throw new CDbException(Yii::t('yii', '{class} does not have relation "{name}".', array('{class}' => get_class($this), '{name}' => $name)));
    }

    $relation = $md->relations[$name];
    if (!($relation instanceof CHasManyRelation)) {
        throw new CException("Currently works with HAS_MANY relations only");
    }

    $className = $relation->className;
    $related = new $className('search');
    $related->unsetAttributes();
    $related->{$relation->foreignKey} = $this->primaryKey;
    if (isset($_GET[$className])) {
        $related->attributes = $_GET[$className];
    }
    return $related;
}
motin commented 11 years ago

This was fixed with 5c3b109f1b1c62599c0f178ca9e2af7e6f76efc4