Yii: Trying to get property of non-object in view - php

I am trying to access attributes of the model in the view and it is throwing me the error mentioned in the title. This is my CompanyMask model:
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(
'company' => array(self::BELONGS_TO, 'company', 'company_id'),
);
}
public function search()
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria = new CDbCriteria;
// $criteria->select = "t.id, t.company_id, t.mask_id, t.mask_text, c.name as company_name";
// $criteria->join = 'LEFT JOIN company c on c.id=t.company_id';
$criteria->with = array('company');
$criteria->compare('id', $this->id);
$criteria->compare('company_id', $this->company_id);
$criteria->compare('mask_id', $this->mask_id);
$criteria->compare('mask_text', $this->mask_text, true);
return new CActiveDataProvider($this, array(
'criteria' => $criteria,
));
}
Now In the view I am trying to access the name of the company like this:
$gridView = $this->widget('zii.widgets.grid.CGridView', array(
'id' => 'deals-grid',
'dataProvider' => $model->search(),
'filter' => $model,
'ajaxUpdate' => 'deals-grid',
'itemsCssClass' => 'table table-striped table-responsive table-bordered no-margin',
'pagerCssClass' => 'pagination pagination-sm no-margin pull-right',
'pager' => array(
'maxButtonCount' => '7',
),
'columns' => array(
array(
'header' => 'Company Name',
'type' => 'raw',
'htmlOptions' => array('style' => 'width:15%',),
'value' => '$data->company->name',
),
),
));
What am I doing wrong here? Any help?

It's about two things:
You are using $data as object, but it's an array: $data['company']->name
You are using single quotes, so the value is the literal value $data->company->name instead of the real value. Remove the single quotes around $data['company']->name

Related

Yii Cgridview with duplicated column name from relational models

I am using Cgridview to display results for "User" model with relation from "UserFlag" model.
"User" model -> tbl_user (id, name, password, flag)
"Flag" model -> tbl_userFlag (id, flag)
The id means the same from both models. However, the flags means differently (I can't modify the database so have to stick with it) and I need to display them on the same gridview.
The problem I encounter is that
the gridview can show both flags correctly but it fails and shows error when I try to sort and filter the flag from "User" model. (However sorting and filtering work fine for the flag from "UserFlag" model.)
How can I solve it?
The error log:
CDbCommand failed to prepare the SQL statement: SQLSTATE[HY000]: General error: 1 ambiguous column name: flag.
"User" model:
class User extends CActiveRecord
{
public function relations()
{
return array(
'FLAG' => array(self::HAS_ONE, 'UserFlag','id'),
);
}
public function search()
{
$criteria=new CDbCriteria;
$criteria->compare('id',$this->id);
$criteria->compare('name',$this->username,true);
$criteria->compare('password',$this->password,true);
$criteria->compare('flag',$this->flag,true);
$criteria->with = array(
'FLAG' => array(
'select' => 'FLAG.flag',
'together' => true,
)
);
$criteria->compare('FLAG.flag',$this->flagFromB,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
'sort'=> array(
'attributes'=>array(
'flagFromB' => array(
'asc' => 'FLAG.flag',
'desc' => 'FLAG.flag DESC',
),
'*',
),
),
));
}
"UserFlag" model:
Link to table tbl_userFlag (id, flag)
"User" view:
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'user-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
'id',
'username',
'password',
'email',
'flag',
array(
'name' => 'flagFromB',
'type' => 'raw',
'value' => '$data->FLAG->flag',
),
array(
'class'=>'CButtonColumn',
),
),
));
You can change your modal relationship.
User.php modal file.
<?php
class User extends CActiveRecord {
public function relations() {
return array(
'FLAG' => array(self::BELONGS_TO, 'UserFlag', 'id'),
);
}
public function search() {
$criteria = new CDbCriteria;
$criteria->compare('id', $this->id);
$criteria->compare('name', $this->username, true);
$criteria->compare('password', $this->password, true);
$criteria->compare('flag', $this->flag, true);
$criteria->with = array(
'FLAG' => array(
'select' => 'FLAG.flag',
'together' => true,
)
);
$criteria->compare('FLAG.flag', $this->flagFromB, true);
return new CActiveDataProvider($this, array(
'criteria' => $criteria,
'sort' => array(
'attributes' => array(
'flagFromB' => array(
'asc' => 'FLAG.flag',
'desc' => 'FLAG.flag DESC',
),
'*',
),
),
));
}
}
?>
I hope it will help.

how to apply sorting on model method in CGridView Yii

I have User model which contain a function that calculates the average revenue per user. Now i want apply sorting in CGridView on the column which is associated with getAvgRevenue() function. While license is relation in the User model.
Here is my code,
public class User{
$user_id;
$email;
public function getAvgRevenue(){
$count = 0;
$revenue = 0;
foreach ($this->license as $license){
$revenue += $license->price;
$count++;
}
if($count!= 0){
$averageRevenue = $revenue/$count;
return $averageRevenue;
}
else{
return null;
}
}
}
In Controller
$modelUser = new CActiveDataProvider('User', array(
'sort' => array(
'attributes' => array(
'user_id',
'email',
'averagerevenue'
),
'defaultOrder' => array(
'user_id' => CSort::SORT_ASC,
),
),
));
In view
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id' => 'user-grid',
'dataProvider' => $modelUser,
'columns' => array(
array(
'header' => 'User ID',
'name' => 'user_id',
),
array(
'header' => 'Email',
'name' => 'email',
),
array(
'header'=>'Average Revenue',
'value'=>'$data->averagerevenue',
),
)
));
?>
Sorting is applicable on user_id and email but Average Revenue column is not sortable. how to specify model method in sort() of CActiveDataprovider
Please help me to solve the problem.
Try this:
$modelUser = new CActiveDataProvider('User', array(
'sort' => array(
'attributes' => array(
'user_id',
'email',
'avgRevenue' //here's the change for you
),
'defaultOrder' => array(
'user_id' => CSort::SORT_ASC,
),
),
));
And your gridview column should be:
array(
'header'=>'Average Revenue',
'value'=>'avgRevenue',
),
and you can read more info on it over here:
http://www.yiiframework.com/wiki/167/understanding-virtual-attributes-and-get-set-methods/

Yii model->findAll(), how to add relational table columns?

I have two models. They are DisnotificationUpdate and DisNotification.
DisnotificationUpdate relations are as below.
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(
'user' => array(self::BELONGS_TO, 'Login', 'userid'),
'notifi' => array(self::BELONGS_TO, 'Disnotification', 'notifi_id'),
);
}
It's attributes are as following.
public function attributeLabels()
{
return array(
'id' => 'ID',
'notifi_id' => 'Notifi',
'view' => 'View',
'userid' => 'Userid',
);
}
Disnotification model has following attributes.
public function attributeLabels()
{
return array(
'id' => 'ID',
'notification' => 'Notification',
'owner' => 'Owner',
'workspace_id' => 'Workspace',
'postID' => 'Post',
'pDate' => 'P Date',
);
}
I want to select values from DisnotificationUpdate and order by values using 'pDate' in DisNotification.
I tried as following.
$dataProvider=DisnotificationUpdate::model()->findAll(array(
'condition' => 'userid=:userid',
'order' => 'notifi.pDate ASC',
'limit'=>10,
'params' => array(':userid' => $myid)
));
But it is giving an error saying, "Unknown column 'notifi.pDate' in 'order clause'". What I am doing wrong? Thanks.
You need to eager load related model
$dataProvider=DisnotificationUpdate::model()->findAll(array(
'with' => array('notifi'),
'condition' => 'userid=:userid',
'order' => 'notifi.pDate ASC',
'limit'=>10,
'params' => array(':userid' => $myid)
));

Filtering data in CGridView based on relations

Hi everyone,
I am new to yii and I am performing crud operation using gii for model called city and I have relation with state model a city->state_id = state.state_id. Crud everything is working fine, but in that view part I want to filter based on state_name
In relations method,I have code this code
'state' => array(self::BELONGS_TO, 'MasState', 'State_Id'),
here is the code for search
public function search() {
// #todo Please modify the following code to remove attributes that should not be searched.
$criteria = new CDbCriteria;
$MasState = new MasState;
$criteria->together = true;
$criteria->compare('state.State_Name',$MasState->State_Name,true);
$criteria->with= array('state');
$criteria->compare('City_Id', $this->City_Id);
$criteria->compare('State_Id', $this->State_Id);
$criteria->compare('City_Name', $this->City_Name, true);
$criteria->compare('Del_Flag', $this->Del_Flag);
$criteria->compare('Ts_Modified', $this->Ts_Modified, true);
$criteria->compare('Ts_Created', $this->Ts_Created, true);
return new CActiveDataProvider($this, array(
'criteria' => $criteria,
));
}
and admin.php page code
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'mas-city-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
array(
'header' => 'SL NO#',
'class' => 'CounterColumn'
),
array(
'name' => 'state.State_Name',
'header' => 'State Name',
'filter' => CHtml::activeTextField($model,'State_Name'),
'value' => '$data->state->State_Name',
),
'City_Name',
array(
'class'=>'CButtonColumn',
),
),
)); ?>
I am getting error "Property "MasCity.State_Name" is not defined" I know city model does not have state_name but how to make it work. Plese help me
Thanks in advance
First in your search method you should do:
public function search() {
$criteria = new CDbCriteria;
$criteria->with= array('state');
$criteria->together = true;
//Get the relation value from the request
$criteria->compare('state.State_Name',Yii::app()->request->getParam('state_state_name'),true);
$criteria->compare('City_Id', $this->City_Id);
$criteria->compare('State_Id', $this->State_Id);
$criteria->compare('City_Name', $this->City_Name, true);
$criteria->compare('Del_Flag', $this->Del_Flag);
$criteria->compare('Ts_Modified', $this->Ts_Modified, true);
$criteria->compare('Ts_Created', $this->Ts_Created, true);
return new CActiveDataProvider($this, array(
'criteria' => $criteria,
));
}
And in your view:
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'mas-city-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
array(
'header' => 'SL NO#',
'class' => 'CounterColumn'
),
array(
'name' => 'state.State_Name',
'header' => 'State Name',
'filter' => CHtml::textField('state_state_name', Yii::app()->request->getParam('state_state_name')),
'value' => '$data->state->State_Name',
),
'City_Name',
array(
'class'=>'CButtonColumn',
),
),
)); ?>

CSqlDataProvider attributeLabels

<?php
//form
class SomeForm extends CFormModel
{
public $id;
public $user_id;
public function search()
{
$sql = 'SELECT id, name FROM some_table';
$sql_count = 'SELECT COUNT(id) FROM some_table';
return new CSqlDataProvider($sql, array(
'totalItemCount' => Yii::app()->db->createCommand($sql_count)->queryScalar(),
'sort' => array(
'attributes' => array(
'id', 'name',
),
),
'pagination' => array(
'pageSize' => 50,
),
));
}
public function attributeLabels()
{
return array(
'id' => 'ID',
'name' => 'NAME',
);
}
}
//grid
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider' => $model->search(), //$model = new SomeForm()
'columns' => array(
'id',
'name'
),
));
/*
Result:
id | name
---------
1 | John
EXPECTED Result:
ID | NAME
---------
1 | John
*/
How to set custom names for query columns ?
The simplest way:
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider' => $model->search(), //$model = new SomeForm()
'columns' => array(
'id::ID',
'name::NAME'
),
));
Another way:
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider' => $model->search(), //$model = new SomeForm()
'columns' => array(
array(
'header' => 'ID',
'name' => 'id'
),
array(
'header' => 'NAME',
'name' => 'name',
),
),
));
Link to api doc
If you don't want to use custom names; if you want to use your labels declared in your model, then you can do this:
Create an empty instance of your model and pass it to your view. The view will thus utilize the $data (CSqlDataProvider) as well as the empty model.
$labelModel = new my_model;
$this->widget('zii.widgets.CListView',array(
'dataProvider'=>$my_model->search(), //returns a CSqlDataProvider
'itemView'=> '_view',
'viewData' => array('labelModel' => $labelModel),
));
Use the empty model - together with getAttributeLabel - to echo labels.
Use $data['field_name'] to echo the data.
This link has more info on how to pass the additional model to the CListView or CGridView.

Categories