cgridveiw to display fetched data via customized query - yii-extensions

I am a newbei in yii, when a person clicks on a category display him all products under that particular category in a gridview
view
productcategory
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'admin-grid',
'dataProvider'=>$model->SelectedCategoryProducts,
'filter'=>$model,
'columns'=>array(
'Name',
'Model',
'Brand',
'Price',
array(
'class'=>'CButtonColumn',
),
),
)); ?>
controller
product
public function actionProductcategory($id)
{
$model= Product::model()->SelectedCategoryProducts($id);
var_dump($model);
$this->render('productcategory',array(
'model'=>$model,'id'=>$id,
));
}
model
product
public function SelectedCategoryProducts($id)
{
$dataProvider=new CActiveDataProvider('Product', array(
'criteria'=>array(
'select'=>'name,model,price,brand',
'condition'=>'category=:category',
'params'=>array(':category'=>$id),
)));
var_dump($dataProvider);
return $dataProvider;
}
CException
Property "CActiveDataProvider.sellerSelectedCategoryProducts" is not defined.
PLEASE HELP! I am losing my mind on this ... not able to display in gridview.

Pass $id to your view file.
$this->render('productcategory',array('model'=>$model,'id'=>$id));
Then pass id to model function in ccgridview function.
'dataProvider'=>$model->SelectedCategoryProducts($id),

Hope this might help
Controller file
public function actionProductcategory($id)
{
$model=new Product;
$this->render('productcategory',array('model'=>$model,
'id'=>$id));
}
In View file
'dataProvider'=>$model->SelectedCategoryProducts($id),
UPDATE 1
'columns'=>array(
'name',
'model',
'brand',
'price',
change them to lowercase which are your original column names

$dataProvider=new CActiveDataProvider('Product', array(
'criteria'=>array(
'select'=>'name,model,price,brand',
'condition'=>'category=:category',
'params'=>array(':category'=>$id),
)));
this can retrieve needed data.... first check that data is perfect ... is it right after that take second step....

Related

How to get names in alphabetic order in Yii

In my Yii web application, having student table for saving student details. I want to student name in alphabetical order when retrieve data from student table.
public function defaultScope() {
return array("order" => "student_firstname");
}
I tried this function, but not working properly.
Please help me.
Thanks in advance.
you can use the defaultOrder property of CSort. For example...
$dataProvider=new CActiveDataProvider('Example', array(
'sort'=>array(
'defaultOrder'=>array(
'student_firstname'=>false
)
)
));
In model's search method for data provider try to set default order, like this:
$dataProvider=new CActiveDataProvider($this, array(
'sort'=>array(
'defaultOrder'=> 'student_firstname ASC'
)
));
In model's search method for data provider try to set default order, like this:
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
'pagination'=>array(
'pageSize'=>Yii::app()->params['defaultPageSize'],
),
'sort'=>array(
'defaultOrder'=>array(
'student_firstname'=>CSort::SORT_ASC
),
),
));

Accessing field in related table through Foreign Key in Yii

I have three tables
1. tbl_employee: id(PK), name, position_id(FK), type_id(FK)
2. tbl_position: id, position
3. tbl_type : id, type
I want to display records in field position like what sql does below.
SELECT tbl_employee.name, tbl_position.position
FROM tbl_employee, tbl_position
WHERE tbl_employee.position_id = tbl_position.id AND tbl_position.position LIKE '%Designer';
In my EmployeeController
public function actionIndex(){
$dataProvider=new CActiveDataProvider('Employee', array(
'criteria'=>array(
'select'=>'t.name, tbl_position',
'with'=>array(
'position'=>array('select'=>'position'),
'type'=>array('select'=>'type'),
),
'condition'=>"tbl_position.position LIKE '%Designer'",
),
));
$this->render('index',array('dataProvider'=>$dataProvider,));
}
and in my models
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(
'position' => array(self::BELONGS_TO, 'Position', 'position_id'),
'type' => array(self::BELONGS_TO, 'Type', 'type_id'),
);
}
and this is my view
<?php $this->widget('zii.widgets.CDetailView', array(
'data'=>$model,
'attributes'=>array(
'id',
'name',
array(
'name'=>'position_id',
'value'=>CHtml::encode($model->position->position),
),
array(
'name'=>'type_id',
'value'=>CHtml::encode($model->type->type),
)
),
)); ?>
The error I've got is:
Active record "Employee" is trying to select an invalid column "tbl_position".
Note, the column must exist in the table or be an expression with alias.
How can I access position field in tbl_position by using join?What is the correct syntax for achieving that purpose.
Many thanks
'select'=>'t.name, position.position',
'condition'=>"position.position LIKE '%Designer'",
or
$model = TblEmployee::model()->with('position','type')->findall(array("condition"=>"position.position LIKE '%Designer'"));
Here I find the solution, but actually your answer was very close
public function actionIndex(){
$dataProvider=new CActiveDataProvider('Employee', array(
'criteria'=>array(
'select'=>'t.name',
'with'=>array(
'position'=>array('select'=>'position'),
'type'=>array('select'=>'type'),
),
'condition'=>"position.position LIKE '%Designer'",
),
));
$this->render('index',array('dataProvider'=>$dataProvider,));
}

Date Field Search not filtering for 'dd/mm/yyyy' format - YII Framework

CJUIDatePicker not filtering value for dd/mm/yyyy format but filtering if i gave DB date format manually like shown in image, I have attached all codes including View and Model for Search panel and Date Widget, Please look into this,
My Model Search(),
public function search()
{
// #todo Please modify the following code to remove attributes that should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('crm_base_contact_id',$this->crm_base_contact_id);
$criteria->compare('name',$this->name,true);
$Date = date('Y-m-d',strtotime($this->created)); // get proper Y-m-d
$startOfDay = $Date . ' 00:00:00'; // from start of the day
$endOfDay = $Date . ' 23:59:59'; // until end of the day
// the rows between these
$criteria->addBetweenCondition('created', strtotime($startOfDay) , strtotime($endOfDay) );
$criteria->compare('createdby',$this->createdby,true);
$criteria->compare('description',$this->description);
$criteria->compare('is_active',$this->is_active);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
My View for CGridView,
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'basecontact-grid',
'dataProvider'=>$model->search(),
//'filter'=>$model,
'columns'=>array(
array('class'=>'CButtonColumn',),
'name',
'crm_base_contact_id',
array(
'name'=>'is_active',
'filter'=>CHtml::dropDownList('Event[is_active]', '',
array(
''=>'',
'1'=>'Y',
'0'=>'N',
)
),
'value' =>'($data->is_active==1)?"Y":"N"',
),
'created',
'createdby',
'description',
),
)); ?>
My View Code for Search column,
<?php $this->widget('zii.widgets.jui.CJuiDatePicker',array(
'model'=>$model,
'id'=>'Search-Created',
'attribute'=>'created',
'options'=>array(
'dateFormat'=>'dd/mm/yy',
'showAnim'=>'fold',
'buttonImage'=>Yii::app()->baseUrl.'/images/icons.date.png',
'buttonImageOnly'=>true,
'buttonText'=>'',
'showAnim'=>'fold',
'showOn'=>'button',
'showButtonPanel'=>false,
),
));?>
you should probably change the date format. set it like this, 'dateFormat'=>'dd-mm-yy',
$this->widget('zii.widgets.jui.CJuiDatePicker', array(
'model'=>$model,
'attribute'=>'dob',
// additional javascript options for the date picker plugin
'options' => array(
'showAnim' => 'fold',
'dateFormat'=>'dd/mm/yyyy',
),
'htmlOptions' => array(
'style' => 'height:20px;'
),
));
Update:
In your model, define it as following, in my case dob is the attribute name. you can have your own instead.
This will change your dateformat from "dd/mm/yyyy" to "yyyy-mm-dd internally before you run any find.
Ref : http://www.yiiframework.com/doc/api/1.1/CActiveRecord#beforeFind-detail
protected function beforeFind()
{
$this->dob=date('Y-m-d', strtotime($this->dob));
parent::beforeFind();
}
update 2
Replace your search method with this,
public function search() {
// #todo Please modify the following code to remove attributes that should not be searched.
$criteria = new CDbCriteria;
$criteria->compare('crm_base_contact_id', $this->crm_base_contact_id);
$criteria->compare('name', $this->name, true);
$criteria->compare('created', '07/12/2013'); //date('Y-m-d', strtotime($this->created))
$criteria->compare('createdby', $this->createdby, true);
$criteria->compare('description', $this->description);
$criteria->compare('is_active', $this->is_active);
return new CActiveDataProvider($this, array(
'criteria' => $criteria,
));
}
Update 3
change this line $criteria->compare('created', '07/12/2013'); to
$criteria->compare('created', date('Y-m-d', strtotime($this->created));

How to set defalut value in CGridView

How can I set default value if $data->pic=="" in my dataprovider values. Set data pic as na.jpg
widget('zii.widgets.grid.CGridView', array(
'dataProvider'=>$dataProvider,
'columns'=>array(
array(
'type'=>'raw',
'name'=>'pic',
'value'=>'CHtml::image("http://localhost/studentpics/".$data->pic)',
),
));
widget('zii.widgets.grid.CGridView', array(
'dataProvider'=>$dataProvider,
'columns'=>array(
array(
'name'=>'your Image URL',
'type'=>'image',
'htmlOptions'=>array('width'=>'30px','height'=>'30px'),
),
));
value is evaluated as a php expression so it is ok to use a condition in it
'value'=>'CHtml::image(($data->pic)?"http://localhost/studentpics/".$data->pic:"default_image_url")',
P.S it's a bad idea to use absolute url's everywhere.
I think you can override afterFind method of CActiveRecord
protected function afterFind()
{
if($this->pic ===null)
{
$this->pic = na.jpg;
}
parent::afterFind();
}

Yii View, Replacing some database values in CGridView

I am new with Yii, Sorry if my question might be stupid, I am using CGridView to show some fields of my database in a table:
<?php echo CHtml::link('Advanced Search','#',array('class'=>'search-button')); ?>
<div class="search-form" style="display:none">
<?php $this->renderPartial('_search',array(
'model'=>$model,
)); ?>
</div><!-- search-form -->
<?php
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'show-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
'id',
'title',
'brief',
'tbl_season_id',
'on_season',
array(
'name'=>'status',
'value'=>'Lookup::item("NewsStatus",$data->status)',
'filter'=> Lookup::items('NewsStatus'),
),
array(
'class'=>'CButtonColumn',
),
),
)); ?>
</div>
I want to replace some of the values that are shown, for example, the on_season field is binary and in the table the values are 0 or 1, I want to change this values to Yes and NO,
And tbl_season_id is a foreign key form another table, I would like to get the name of the season and put it instead of the id which is not understandable by the users.
You can refer this wiki article for customizing your column values to your heart's content
Yii Documentataion: cgridview-render-customized-complex-datacolumns
Just remember that the value property can be an expression string, which is later evaluated for each data of rows. So you have a method call there which can dynamically calculate any value for you depending on the current values of that row.
Let you have two table
1): clients 2): projects
Relation is a client has many projects.
in model
and clients model the relation is (the Client table model name is Client)
class Client extends CActiveRecord{
}
and relations() method ;
return array(
'projects' => array(self::HAS_MANY, 'Projects', 'clients_id'),
);
project model the relation is (the project table model name is Projects)
class Projects extends CActiveRecord{
}
and relations() method ;
return array(
'clients' => array(self::BELONGS_TO, 'Client', 'clients_id')
);
Now
now you can use the following to get the client_name replace the client_id in proejct table
in CGridView
'dataProvider' => $model->search(),
'columns' => array(
'id',
'project_name',
array(
'name' => 'client Name',
'value' => '$data->clients->name', //where name is Client model attribute
),
)
and
Project view page in CDetailView you can use the following
'data' => $model,
'attributes' => array(
'id',
'project_name',
array(
'name'=>'Client Name',
'value'=>$model->clients->name ,
),
)
if you have client relation with company table (a company has many clients )
client model
'company' => array(self::BELONGS_TO, 'Company', 'company_id'),
you can also get the company name by following method in
index (CGridview)
array(
'name' => 'client Name',
'value' => '$data->clients->company->name', //where name is company model attribute
),
and in view CDetailView
array(
'name'=>'Client Name',
'value'=>$model->clients->company->name ,
),