Yii CGridview not filtering - php

I'm trying to work with a YII CGridview to display some data.
This is home my model search function looks like:
/**
* 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()
{
$criteria=new CDbCriteria;
$criteria->compare('ip',$this->ip,true);
$criteria->compare('first_use',$this->first_use,true);
$criteria->compare('last_use',$this->last_use);
$criteria->compare('memberid',$this->memberid);
$criteria->compare('countryid',$this->countryid);
return new CActiveDataProvider(get_class($this), array(
'criteria'=>$criteria,
));
}
And this is how my view looks like
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'iplog-grid',
'dataProvider'=>$oIPLog->search(),
'filter'=>$oIPLog,
'summaryText' => 'showing you {start} - {end} of {count} logged Ips',
'columns'=>array(
array(
'name'=>'ip',
'type'=>'raw',
),
array(
'name'=>'first_use',
'type'=>'datetime',
),
array(
'name'=>'last_use',
'type'=>'datetime',
),
),
));
Displaying the CGridview works, but I can't seem to get the filter on top of it to work. It sends the call and I don't get any error as reponse, it just returns the whole unfiltered data again..
Any clues?

And how exactly does your controller look like?
For the CGridview filter to work you need to check in your controller if there are any filters set and then return the filtered object.
To clarify, something like this should be placed into your controller action
$oObject = new Object('search');
if (isset($_GET['Object'])) {
$oObject->attributes = $_GET['Object'];
}
Hope this helps

You Have to apply these points:
1.Specify the global variable($_REQUEST) in function of your controller
for example
$model = new User('search');
$model->unsetAttributes(); // clear any default values
if (isset($_REQUEST['User'])){
$model->attributes = $_REQUEST['User'];
}
$this->render('admin', array(
'model' => $model,
));
Set method type in search form
<?php $form=$this->beginWidget('CActiveForm', array(
'action'=>Yii::app()->createUrl('user/admin'),
'method'=>'POST',
)); ?>
3.In Cgrid view you have to define the url like
'ajaxUrl'=>Yii::app()->createUrl( 'controller/function' ),

Related

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,
));
}

Page size dropdownlist and CListView not working in yii

I am traying to make a dropdown pagination in my project, but it's not working correctly.
Whatever the number that I select in the dropdownlist, it still shows 10 items in the page.
What I am missing ?
Thank you.
Screenshot
The view code :
<?php
//$dataProvider->pagination->pageSize = 25;
$pageSize=Yii::app()->user->getState('pageSize',Yii::app()->params['defaultPageSize']);
echo CHtml::dropDownList('pageSize',$pageSize,array(5=>5,10=>10,15=>15,20=>20,25=>25,30=>30),
array('onchange'=>"$.fn.yiiGridView.update('packages-grid',{ data:{pageSize: $(this).val() }})",
'empty'=>'-- Select Page Range --','style'=>'width:198px;'));
$this->widget('zii.widgets.CListView', array(
'id'=>'propertylistview',
'dataProvider'=>$dataProvider,
'summaryText'=>'',
'itemView'=>'_propertyview',
'sortableAttributes' => array(
.........
)
));
?>
The controller code :
public function actionAdmin(){
if (isset($_GET['pageSize'])) {
Yii::app()->user->setState('pageSize',(int)$_GET['pageSize']);
unset($_GET['pageSize']);}
$model=new Packages('search');
$model->unsetAttributes();
if(isset($_GET['Packages']))
$model->attributes=$_GET['Packages'];
$dataProvider=new CActiveDataProvider('Packages');
$this->render('admin',array('model'=>$model,'dataProvider'=>$dataProvider,
));
}
I already added this to model search
return new CActiveDataProvider(get_class($this),array(
'pagination'=>array(
'pageSize'=> Yii::app()->user->getState('pageSize',Yii::app()->params['defaultPageSize']),
),
'criteria'=>$criteria,
));
and this to config/main.php
'params'=>array('defaultPageSize'=> '10'),
You're doing an ajax call but in your widget you do not state any update part to update. ajaxUpdate is the solution.
And you are using 'onchange'=>"$.fn.yiiGridView.update while using a CListView so change the js to 'onchange'=>"$.fn.yiiListView.update and:
<?php
// your code
$this->widget('zii.widgets.CListView', array(
'id'=>'propertylistview',
'ajaxUpdate' => 'propertylistview', //add this line
'dataProvider'=>$dataProvider,
'summaryText'=>'',
'itemView'=>'_propertyview',
'sortableAttributes' => array(
//etc.. )
));
?>

search function in yii gridview

I have project implemented in Yii. Grid view search function is not working in server. In localhost Grid view search function is working. What could be issue in that. please suggest me where should i change.
my Recipe controller:
public function actionAdmin()
{
$model=new Recipe('search');
$model->unsetAttributes(); // clear any default values
if(isset($_GET['Recipe']))
$model->attributes=$_GET['Recipe'];
$this->render('admin',array(
'model'=>$model,
));
}
My model part:
public function search()
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria=new CDbCriteria;
$pagination=array('pageSize'=>'10');
$criteria->compare('recipe_id',$this->recipe_id);
$criteria->compare('posted_id',$this->posted_id,true);
$criteria->compare('name',$this->name,true);
$criteria->compare('type',$this->type);
$criteria->compare('cuisinename',$this->cuisinename);
$criteria->compare('course_id',$this->course_id);
$criteria->compare('details',$this->details,true);
$criteria->compare('serving_size',$this->serving_size,true);
$criteria->compare('calorie_count',$this->calorie_count);
$criteria->compare('preparation_time',$this->preparation_time);
$criteria->compare('cooking_instructions',$this->cooking_instructions,true);
$criteria->compare('garnishing_instructions',$this->garnishing_instructions,true);
$criteria->compare('serving_instructions',$this->serving_instructions,true);
$criteria->compare('recipe_image',$this->recipe_image,true);
$criteria->compare('recipe_small_image',$this->recipe_small_image,true);
$criteria->compare('status',$this->status,true);
$criteria->compare('posting_time',$this->posting_time,true);
$criteria->compare('pLike',$this->pLike);
$criteria->compare('pDislike',$this->pDislike);
$criteria->compare('images',$this->images,true);
$criteria->compare('Ingredient_TypeId',$this->Ingredient_TypeId,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,'pagination'=>$pagination
));
}
my view part:
<?php $this->widget('zii.widgets.grid.CGridView', array( 'id'=>'mygridview',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
//'id',
'name',
array(
'class'=>'CButtonColumn','template'=>'{update}{delete}',
),
),
)); ?>
Handle your javascript following way, there will be no double jquery problem after this, add all other js in the 'js' array
$baseurl = Yii::app()->baseUrl;
$cs = Yii::app()->clientScript;
$cs->scriptMap = array('jquery.min.js'=>$baseurl.'/js/jquery-2.0.3.min.js', 'jquery.js'=>$baseurl.'/js/jquery-2.0.3.min.js');
$cs->registerCoreScript('jquery');
Yii::app()->clientScript->addPackage('other-required-scripts', array(
'baseUrl'=>$baseurl,
'js'=>array(
"js/abc.js",
"js/bcd.js",
//...
),
'depends'=>array('jquery')
));
Yii::app()->clientScript->registerPackage('other-required-scripts');

YII model ::: CGridView Search by specific attribute using criteria

I am new in yii. I want to search by attribute (field name) from my model and need to view in view page or another page by zii.widgets.grid.CGridView.
how can I create a search() function in model by findByAttribute()
so that we can show the results by attribute without any search
here is my model function but it is not working.. :: ERROR Undefined variable: pp_requisitionno
public function searchView()
{
$criteria=new CDbCriteria();
$criteria->select= 'pp_requisitionno';
$criteria->addSearchCondition('pp_requisitionno',$pp_requisitionno);
$criteria->compare('pp_requisitionno',$this->pp_requisitionno);
$criteria->condition = 'pp_requisitionno=:pp_requisitionno';
$criteria->params = array(':pp_requisitionno'=>Yii::app()->Request->Getpost('pp_requisitionno'));
$model = Requisitiondt::model()->find();
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
Any help please...
It's probably going to be more useful to define a general search function that can be reused for different searches. This can be done in the following way:
/**
* 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() {
$criteria = new CDbCriteria;
//Define all your searchable fields here
$criteria->compare('t.title', $this->title, true);
$criteria->compare('t.type', $this->type, true);
$criteria->compare('t.published', $this->published, true);
$criteria->compare('category.id', $this->category_id, true);
//Add any other criteria, like the default sort order etc.
return new CActiveDataProvider($this, array(
'criteria' => $criteria,
));
}
Then in your controller you can use the search like this;
pubic function actionSearch(){
$model = new Requisitiondt;
if (isset($_POST)){
$model->attributes = $_POST;
$dataProvider = $model->search();
$this->render('searchView', array('dataProvider' => $dataProvider));
}
}
The view 'searchView' then looks like this;
<?php
$this->widget('CGridView', array(
'dataProvider' => $dataProvider,
'columns' => array(
//Add in whatever columns you want the grid to show
)
));
?>
Obviously you'll need to replace your own model names and field names, but this is the general idea. This way will search for any attributes you include in the POST request,and is more reusable.
You need use Relations in your model, read here.
Then add 'filter' => $model, in your GridView Widget options array

How did $data extracted from dataprovider when using clistview widget?

In yii framework demos, there is an blog demo. In this blog demo a Post controller has two different actions: index and view.
/**
* Lists all models.
*/
public function actionIndex()
{
$criteria=new CDbCriteria(array(
'condition'=>'status='.Post::STATUS_PUBLISHED,
'order'=>'update_time DESC',
'with'=>'commentCount',
));
if(isset($_GET['tag']))
$criteria->addSearchCondition('tags',$_GET['tag']);
$dataProvider=new CActiveDataProvider('Post', array(
'pagination'=>array(
'pageSize'=>Yii::app()->params['postsPerPage'],
),
'criteria'=>$criteria,
));
$this->render('index',array(
'dataProvider'=>$dataProvider,
));
}
/**
* Displays a particular model.
*/
public function actionView()
{
$post=$this->loadModel();
$comment=$this->newComment($post);
$this->render('view',array(
'model'=>$post,
'comment'=>$comment,
));
}
and index view is:
<?php $this->widget('zii.widgets.CListView', array(
'dataProvider'=>$dataProvider,
'itemView'=>'_view',
'template'=>"{items}\n{pager}",
)); ?>
and view view is:
<?php $this->renderPartial('_view', array(
'data'=>$model,
)); ?>
but both index and view use _view:
<div class="author">
posted by <?php echo $data->author->username . ' on ' . date('F j, Y',$data->create_time); ?>
</div>
<div class="content">
<?php
$this->beginWidget('CMarkdown', array('purifyOutput'=>true));
echo $data->content;
$this->endWidget();
?>
</div>
here is my question: I can understand the view assign the 'data' => $model, so in _view, $data is valid. In index action, the widget clistview is applied, but i cannot understand where is $data variable being set? I know the $data presents the current post(from dataprovider). I just cannot figure out how and where did yii did this?
Thanks for any help.
The above code first creates a data provider for the Post ActiveRecord class. It then uses CListView to display every data item as returned by the data provider. The display is done via the partial view named '_post'. This partial view will be rendered once for every data item. In the view, one can access the current data item via variable $data.
By using the itemView property of CListView which is used for rendering each data item. This property value will be passed as the first parameter to CController property renderpartial to render each data item.
public string renderPartial(string $view, array $data=NULL, boolean $return=false, boolean $processOutput=false)
public function renderPartial($view,$data=null,$return=false,$processOutput=false)
{
if(($viewFile=$this->getViewFile($view))!==false)
{
$output=$this->renderFile($viewFile,$data,true);
if($processOutput)
$output=$this->processOutput($output);
if($return)
return $output;
else
echo $output;
}
else
throw new CException(Yii::t('yii','{controller} cannot find the requested view "{view}".',
array('{controller}'=>get_class($this), '{view}'=>$view)));
}
Renders a view.
If $data is an associative array, it will be extracted as PHP variables and made available to the script The named view refers to a PHP script .the Script Which is resolved via getViewFile Used in the renderPartial method the script for getViewFile as shown below
public function getViewFile($viewName)
{
if(($theme=Yii::app()->getTheme())!==null && ($viewFile=$theme->getViewFile($this,$viewName))!==false)
return $viewFile;
$moduleViewPath=$basePath=Yii::app()->getViewPath();
if(($module=$this->getModule())!==null)
$moduleViewPath=$module->getViewPath();
return $this->resolveViewFile($viewName,$this->getViewPath(),$basePath,$moduleViewPath);
}
Looks for the view file according to the given view name.
renderItems is the abstract method defined in CBaseListView ClassFile
/**
* Renders the data items for the view.
* Each item is corresponding to a single data model instance.
* Child classes should override this method to provide the actual item rendering logic.
*/
abstract public function renderItems();
And This Method is Overriden by ClistView Class
CListView widget loops thru $dataProvider, and for each item it does something like that:
$this->renderPartial($itemView, array(
'data'=>$model,
));
Where $itemView is view file set in CListView config.
And that's it.
Edit: To clarify of how CListView iterates over dataprovider items: it is defined in CListView::renderItems, in short, the most important parts are:
// Get dataprovider data as array
$data=$this->dataProvider->getData();
...
// Get viewfile
$viewFile=$owner->getViewFile($this->itemView);
...
// Loop thru $data items
foreach($data as $i=>$item)
{
...
// Here data is assigned from dataprovider item
$data['data']=$item;
...
// Render view file
$owner->renderFile($viewFile,$data);
}

Categories