Passing A Relationship To Cgridview

Greetings.

Still learning Yii and PHP and loving both, and i’m looking for some help please.

Seeing that in my customer model i have the relationship:


'purchases' => array(self::HAS_MANY, 'Purchase', 'customer_id'),

would it be possible, in reference to the line of code in my users view:


'model'=>$purchaseModel,

to instead use this line of code:


'model'=>$model->purchases,

Im guessing no, as trying that has produced the error:

"Fatal error: Call to a member function search() on a non-object"

Showing my lack of knowledge, my guess is $model->purchases doesnt return a model? but an array of data or something.

Users Controller


	

	public function actionView($id)

	{	

		$purchaseModel=new purchase('search');

		$purchaseModel->unsetAttributes();  // clear any default values

		$purchaseModel->customer_id = $id;

		

		$this->render('view',array(

			'model'=>$this->loadModel($id),

			'purchaseModel'=>$purchaseModel,

		));

	}



Users View


	

	$this->widget('zii.widgets.CDetailView', array(

		'data'=>$model,

		'attributes'=>array(

			'name',

			'address',

			'phone',

			'email',

		),

	));

$this->renderPartial('/purchase/admin',array(

		'model'=>$purchaseModel,

	));



Purchase admin view




$this->widget('zii.widgets.grid.CGridView', array(

		'id'=>'purchase-grid',

		'dataProvider'=>$model->search(),

		'columns'=>array(

			'category',

			'model',

			'serialnumber',

		),

	)); 

Hi,

can you please post the your model code?




class Purchase extends CActiveRecord

{

	/**

	 * Returns the static model of the specified AR class.

	 * @param string $className active record class name.

	 * @return Purchase the static model class

	 */

	public static function model($className=__CLASS__)

	{

		return parent::model($className);

	}


	/**

	 * @return CDbConnection database connection

	 */

	public function getDbConnection()

	{

		return Yii::app()->dbhcr;

	}


	/**

	 * @return string the associated database table name

	 */

	public function tableName()

	{

		return 'purchase';

	}


	/**

	 * @return array validation rules for model attributes.

	 */

	public function rules()

	{

		// NOTE: you should only define rules for those attributes that

		// will receive user inputs.

		return array(

			array('customer_id, product_id, usertype', 'required'),

			array('year', 'numerical', 'integerOnly'=>true),

			array('customer_id, product_id', 'length', 'max'=>10),

			array('serialnumber, usertype, orcnumber', 'length', 'max'=>25),

			array('datepurchased, warrantyexpiry', 'type', 'type' => 'date', 'message' => '{attribute}: is not in date format yyyy-mm-dd', 'dateFormat' => 'yyyy-mm-dd'),

			array('datepurchased, warrantyexpiry', 'default', 'setOnEmpty' => true, 'value' => null),

			// The following rule is used by search().

			// Please remove those attributes that should not be searched.

			array('id, customer_id, product_id, serialnumber, year, datepurchased, warrantyexpiry, orcnumber', 'safe', 'on'=>'search'),

			array('orcnumber, year, serialnumber', 'safe'),

		);

	}


	/**

	 * @return array relational rules.

	 */

	public function relations()

	{

		// NOTE: you may need to adjust the relation name and the related

		// class name for the relations automatically generated below.

		return array(

			'product' => array(self::BELONGS_TO, 'Product', 'product_id'),

			'customer' => array(self::BELONGS_TO, 'Customer', 'customer_id'),

			'services' => array(self::HAS_MANY, 'Service', 'purchase_id'),

		);

	}

	

	/**

	 * @return array of Products.

	 */

	public function getProductList()

	{

		// this gives all possible Editions

		$criteria = new CDbCriteria();

		$criteria->select = array('id', 'pnc');

		$products = product::model()->findAll($criteria);

		if (count($products))

		{

			return CHtml::listData($products, 'id', 'pnc');

		}

		else

		{

			return $array();

		}

		

	}

	

	/**

	 * @return array customized attribute labels (name=>label)

	 */

	public function attributeLabels()

	{

		return array(

			'id' => 'ID',

			'customer_id' => 'Customer',

			'product_id' => 'Product',

			'serialnumber' => 'Serial#',

			'usertype' => 'User type',

			'year' => 'Year',

			'datepurchased' => 'Date purchased',

			'warrantyexpiry' => 'Warranty expiry',

			'orcnumber' => 'ORC#',

		);

	}


	/**

	 * Retrieves a list of models based on the current search/filter conditions.

	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.

	 */

	public function search()

	{

		// Warning: Please modify the following code to remove attributes that

		// should not be searched.


		$criteria=new CDbCriteria;


		$criteria->compare('id',$this->id,true);

		$criteria->compare('customer_id',$this->customer_id,false);

		$criteria->compare('product_id',$this->product_id,false);

		$criteria->compare('serialnumber',$this->serialnumber,true);

		$criteria->compare('year',$this->year);

		$criteria->compare('datepurchased',$this->datepurchased,false);

		$criteria->compare('warrantyexpiry',$this->warrantyexpiry,false);

		$criteria->compare('orcnumber',$this->orcnumber,true);


		return new CActiveDataProvider($this, array(

			'pagination'=>array(

				'pageSize'=> Yii::app()->user->getState('pageSize',Yii::app()->params['defaultPageSize']),

			),

			'criteria'=>$criteria,

		));

	}

}



Hi,

i don’t understand you question but please see it link it’s may be helpful

Thankyou for your reply

I’m guessing i need to reword my question:

instead of




        public function actionView($id)

        {       

                $purchaseModel=new purchase('search');

                $purchaseModel->unsetAttributes();  // clear any default values

                $purchaseModel->customer_id = $id;

                

                $this->render('view',array(

                        'model'=>$this->loadModel($id),

                        'purchaseModel'=>$purchaseModel,

                ));

        }


$this->renderPartial('/purchase/admin',array(

               'model'=>$purchaseModel,

        ));



is there a way to do this:




        public function actionView($id)

        {       

                $this->render('view',array(

                        'model'=>$this->loadModel($id),

                ));

        }


$this->renderPartial('/purchase/admin',array(

               'model'=>$model->purchase,

        ));



Note i’m passing $model->purchase instead of $purchaseModel

Out of interest i did a var dump on $model->purchase and $purchaseModel,

and they seem to be identical except one looks like an array and the other an object?

$purchaseModel dumped:

"

Purchase#1

(

[CActiveRecord:_md] => CActiveRecordMetaData#2


(

etc…

"

and $model->purchase dumped out:

array

(

0 => Purchase#1


(


    [CActiveRecord:_md] => CActiveRecordMetaData#2


    (

etc…

so im assuming when i pass $model->purchase to cgridview its because its an array that im getting the error:

Call to a member function search() on a non-object in

the key word is non-object?

is there a way to feed the array in $model->purchase to cgrid view

or make $model->purchase give an object instead of an array?

Thanks again for your time.

if you want it display any record on admin grid view you can write a query on grid view…

for e.g




array(

            'name'=>'user_id',

            'value'=>'Users::Model()->FindByPk($data->user_id)->username',

        ),

I’ll try and illustrate it another way

instead of doing this:

Controller




$purchaseModel=new purchase('search');

$purchaseModel->customer_id = $customer_id;


$customerModel=Customer::model()->findByPk($customer_id);


$this->render('view',array(

	'customerModel'=>$customerModel,

	'purchaseModel'=>$purchaseModel,

));



View




$this->widget('zii.widgets.CDetailView', array(

		'data'=>$customerModel,

.....

$this->widget('zii.widgets.grid.CGridView', array(

		'dataProvider'=>$purchaseModel->search(),

.....



Is there some way to simplify it to this:




$customerModel=Customer::model()->findByPk($customer_id);


$this->render('view',array(

	'customerModel'=>$customerModel,

));



View




$this->widget('zii.widgets.CDetailView', array(

		'data'=>$customerModel,

.....

$this->widget('zii.widgets.grid.CGridView', array(

		'dataProvider'=>$customerModel->purchases->search(),

.....