Using Yii Model and Criteria on CGridView - php

I'm trying to use my model with a replacement for the search (custom search function):
public function combineCampInputByDate($startDate,$endDate) {
$criteria=new CDbCriteria;
$criteria->select = 'food.*,SUM(customer) AS customer, SUM(money) AS money';
$criteria->join = 'JOIN foodType food ON foodtype = food.foodtype ';
$criteria->condition = "date BETWEEN '$startDate' AND '$endDate'";
$criteria->group = 'foodtype ';
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
the result will be the attributes for the model + the other table.
i'm trying to display them in the view but it states no such attribute as .... (this is clear since the model doesnt have an attribiute that came from the other table)
So how do i use the widget below on the model result??
frustrates, but counting on the experts :)
Danny
Edit:
1. Controller -
public function actionIndex()
{
if (isset($_POST['Filter']) && !empty($_POST['Filter']['date']) ) {
$GetDates = new GetDates();
$this->dates = $GetDates->getDatesFromPostWidget($_POST);
$model = new Campaigns;
}
else
$model=NULL;
$this->render('index',array(
'model' => $model, 'dates' => $this->dates,
));
}
Model -
public function combineCampInputByDate($startDate,$endDate) {
$criteria=new CDbCriteria;
$criteria->select = 'food.*,SUM(customer) AS customer, SUM(money) AS money';
$criteria->join = 'JOIN foodType food ON foodtype = food.foodtype ';
$criteria->condition = "date BETWEEN '$startDate' AND '$endDate'";
$criteria->group = 'foodtype ';
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
View
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'bo-campaigns-grid',
'dataProvider'=>$model->combineCampInputByDate($dates['startDate'],$dates['endDate']),
'filter'=>$model,
),
));
}

In your model class create two attributes: public $customer and public $money.
You can have as many custom attributes as you want, just be consistent with the naming. (You can't use the SQL fieldname AS something if you don't have a something model attribute first)
EDIT: You should also tell the CGridView which columns to display, like this
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'bo-campaigns-grid',
'dataProvider'=>$model->combineCampInputByDate($dates['startDate'],$dates['endDate']),
'filter'=>$model,
'columns'=>array(
'customer',
'money',
//etc. for more detailed customization, check the links above
),
),
));
}

Related

How to define model parameter value in Yii?

I have a user table in which i have multiple roles and i am showing different user on different action by using same model search function. By this
public actionAdmin(){
$model = new User('search')
$model->unsetAttributes();
$model->userRole = UmsConfing::ADMIN;
if(isset($_GET('User')))
$model->attributes = $_GET['User'];
$this->render('userlist',arary('model'=>$model));
}
I am using this function for different roles .This works well. but now i want to show admin and operation user in same list i tried
$model->userRole = UmsConfig::ADMIN || UmsConfig:: OPERATION
but i didn't work Please help.
Please you can try this below code:
public actionAdmin(){
$model = new User('search')
$model->unsetAttributes();
if(isset($_GET('User')))
$model->attributes = $_GET['User'];
$this->render('userlist',arary('model'=>$model));
}
Below codeadd in User Model Search Function:
model/User.php
public function search() {
// #todo Please modify the following code to remove attributes that should not be searched.
$criteria = new CDbCriteria;
$criteria->compare('id',$this->id);
$criteria->addInCondition('userRole', array (UmsConfig::ADMIN,UmsConfig:: OPERATION));
$criteria->compare('status',$this->status);
$criteria->compare('is_deleted',$this->is_deleted);
return new CActiveDataProvider($this, array(
'criteria' => $criteria,
'pagination' => array(
'pageSize' => yii::app()->params->pagesize,
),
'sort'=>array(
'defaultOrder'=>array(
'id'=>CSort::SORT_DESC
),
),
));
}

Modify Data that is put into CGridView - Yii

I'm working on a project in Yii where I would like the user to be able to update information on his mobile "accounts". The database I use has multiple accounts for each person (and, for that matter, has multiple individuals who will use the system). Now, when the user goes to "manage his account" he is able to manage all of the accounts of the database (not just his own).
Currently the code in the controller looks like this
public function actionAdmin()
{
$model =new Account('search');
$userId = Login::model()->getUserId();
$model->unsetAttributes(); // clear any default values
if(isset($_GET['Account']))
{
$model->attributes=$_GET['Account'];
}
$this->render('admin',array(
'model'=>$model,
));
}
UserId is the the id that I would like to restrict that data to. Something along the lines of
$account = Account::model()->findAll(array("condition"=>"user_id = $userId"));
I'm not sure how exactly to go through with this. I've looked around and I know that there are "Criteria" that I could update in the model and there is also a "Filter function in the view". Should I be using one of these two to limit the accounts shown? Or can I do something directly from the controller?
Here is the code in the view
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'account-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
'id',
'user_id',
'name',
'mobile_comp',
'msisdn',
'pin',
'balance',
/*
'company',
*/
array(
'class'=>'CButtonColumn',
),
),
)); ?>
And the model
public function search()
{
// #todo Please modify the following code to remove attributes that should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('name',$this->name,true);
$criteria->compare('mobile_comp',$this->mobile_comp,true);
$criteria->compare('msisdn',$this->msisdn);
$criteria->compare('pin',$this->pin);
$criteria->compare('company',$this->company,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
Change your actionAdmin to the following
public function actionAdmin()
{
$model =new Account('search');
$userId = Login::model()->getUserId();
$model->unsetAttributes(); // clear any default values
if(isset($_GET['Account']))
{
$model->attributes=$_GET['Account'];
}
$model->user_id = $userId;
$this->render('admin',array(
'model'=>$model,
));
}
The above code will load only the current user record.
Just Solved - Different way than Think Different:
In my model I added a condition
public function search()
{
// #todo Please modify the following code to remove attributes that should not be searched.
$criteria=new CDbCriteria;
$userId = Login::model()->getUserId();
$criteria->addCondition(array("condtion"=>"user_id = $userId"));
$criteria->compare('name',$this->name,true);
$criteria->compare('mobile_comp',$this->mobile_comp,true);
$criteria->compare('msisdn',$this->msisdn);
$criteria->compare('pin',$this->pin);
$criteria->compare('company',$this->company,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}

How To Write A Customised Query To Fetch Result Array An Display

following is my query how do i place what code in view ,model,controller in yii
select productid, count(*)
from fc_member
group by productid
order by count(*)desc
LIMIT 3
Please let me know i am a newbie
i did try but then do not the how and what of it :(
controller
public function actiondsplayproduct()
{
$model=new Member;
$dataProvider=new CActiveDataProvider('$model',
array(
'criteria'=>array(
'select'=>'productid, COUNT( * )as Cproductid',
'from'=>'fc_member',
'group'=>'productid',
'order'=>'COUNT( * ) ',
),
)
);
$this->render('dsplayproduct',array(
'dataProvider'=>$dataProvider,
));
//$this->render('dsplayproduct',array('model'=>$model));
}
view
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider'=> $dataProvider,
'filter'=>$model,
'columns'=>array(
'productid',
'Cproductid',
)
));
And also get the below error
PHP warning
include($model.php) [<a href='function.include'>function.include</a>]: failed to open stream: No such file or directory
Please let me know I am a newbie
I did try but then do not know the how and what of it :(
following r d changes
model
`public function top_selling_products() {
$criteria = new CDbCriteria;
$criteria->select = 'productid , count(*) as pid_count';
$criteria->from='fc_member';
$criteria->group = 'productid';
$criteria->order = 'pid_count desc';
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}`
controoler
`
public function actiondsplayproduct()
{
$dataProvider=new CActiveDataProvider('Member');
$this->render('dsplayproduct',array(
'dataProvider'=>$dataProvider,
));
}
view
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider'=>Member::model()->top_selling_products(),
'enablePagination' => false,
'columns'=>array(
'pid',
'pid_count',
array(
'class'=>'CButtonColumn',
),
),
)); `
but i get the folowing error
Property "CDbCriteria.from" is not defined.
Plz let me now where am i wrong
I think it's not string $model than you want to put into CActiveDataProvider class ...
So, it's not
CActiveDataProvider('$model', ...
But
CActiveDataProvider('model', ...
Or
CActiveDataProvider($model, ...
error says that you dont have "$model.php" file - so you have to put there valid and existing name for model file.
for example:
new CActiveDataProvider('model', ...

Yii CDbCriteria compare 2 attributes to a single value

Hi I am new to yii and I am currently working on a project and I am having trouble with CDbCriteria.
My target query is:
title LIKE '$_GET['search']%' OR description LIKE '$_GET['search']%'
Is it possible to attain same result like this using CDbCriteria compare?
Controller action :
public function actionClassifieds(){
$model = new Classifieds('search');
$model->unsetAttributes();
if(isset($_GET['category'])){
if( $_GET['category'] == 0 ){
$model->classified_category_id = '';
}else{
$model->classified_category_id = $_GET['category'];
}
}
if(isset($_GET['search'])){
$model->title = $_GET['search'];
$model->description = $_GET['search'];
}
$this->render('classifieds',array('model'=>$model));
}
My model:
public function search()
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('classified_category_id',$this->classified_category_id);
$criteria->compare('title',$this->title,true);
$criteria->compare('description',$this->description,true);
$criteria->compare('price',$this->price,true);
$criteria->compare('timestamp',$this->timestamp);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
'pagination'=>array(
'pageSize'=>10,
),
));
}
Try:
$criteria->condition = "title LIKE :t OR description LIKE :d";
$criteria->params = array(
':t' => trim( Yii::app()->request->getParam('search') ).'%',
':d' => trim( Yii::app()->request->getParam('search') ).'%');
Better using Yii::app()->request->getParam($var_name)
UPDATED
$criteria->compare('classified_category_id',$this->classified_category_id);
$criteria->compare('price',$this->price,true);
$criteria->compare('timestamp',$this->timestamp);
$criteria->addCondition("title LIKE :t OR description LIKE :d");
$criteria->params[':t'] = $this->title;
$criteria->params[':d'] = $this->description;

how to use both condition() and addcondition() for a same search model

I have a grid view with a condition "upload_date = today", but when I search for other dates it is not filtering the grid. Here is my model:
public function search()
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$date=date('Y-m-d');
$criteria=new CDbCriteria(array('order'=>'upload_date ASC'));
$criteria->condition = "upload_date='$date' ";
if(isset($_GET['upload_date']))
{
$criteria->addCondition('upload_date = :upload_date','AND');
$criteria->params[':upload_date'] = $this->upload_date;
}
$criteria->compare('book_id',$this->book_id);
$criteria->compare('date_received',$this->date_received,true);
$criteria->compare('batch',$this->batch,true);
$criteria->compare('isbn_no',$this->isbn_no,true);
$criteria->compare('book_title',$this->book_title,true);
$criteria->compare('auther_name',$this->auther_name,true);
$criteria->compare('upload_date',$this->upload_date,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
'pagination'=>array(
'pageSize'=>50
),
));
}
I am trying to use both condition and addcondition in same search. What did I do wrong in the model above?
Try this:
public function search()
{
$criteria=new CDbCriteria(array('order'=>'upload_date ASC'));
if(isset($_GET['ModelName']['upload_date']))
{
$criteria->compare('upload_date',$this->upload_date,true);
// $criteria->addCondition('upload_date = :upload_date');
// $criteria->params[':upload_date'] = $this->upload_date;
}
else
{
$date=date('Y-m-d');
$criteria->condition = "upload_date='$date' ";
}
$criteria->compare('book_id',$this->book_id);
$criteria->compare('date_received',$this->date_received,true);
$criteria->compare('batch',$this->batch,true);
$criteria->compare('isbn_no',$this->isbn_no,true);
$criteria->compare('book_title',$this->book_title,true);
$criteria->compare('auther_name',$this->auther_name,true);
$criteria->compare('upload_date',$this->upload_date,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
'pagination'=>array(
'pageSize'=>50
),
));
}
You don't need addCondition, specially because you are adding a condition to the same column.
Edit:
In your main initial condition you have already set upload_date = $date, now if you add condition to it, say $_GET['ModelName']['upload_date'] provided by the user in the filter, your actual db query will become something like select * from tbl_name where upload_date = 'xxx' and upload_date = 'yyy' , here xxx=$date you gave, and yyy=date provided by user. Now if xxx != yyy, how will the query return any value? It is not possible.
Hope you got this explanation.

Categories