Yii Cgridview filter not working? - yii

I am trying to implement a dropdown filter in Cgridview, The column is from another table.
//model search code
//person table
public function search(){
$criteria=new CDbCriteria;
$criteria->alias='per';
$criteria->compare('LastName',$this->LastName,true);
$criteria->compare('FirstName',$this->FirstName,true);
$criteria->join='right JOIN person_surveys ps ON ps.id = per.P_Id';
}
//relation to person survey
public function relations()
{
return array(
'user' => array(self::BELONGS_TO, 'PersonSurvey', 'P_Id'),
);
}
//person survey table model search
public function search()
{
$criteria=new CDbCriteria;
$criteria->compare('person_id',$this->person_id,true);
$criteria->compare('survey_ids',$this->survey_ids,true);
$criteria->join='left JOIN persons ps ON ps.id = per.P_Id';
}
//controller
public function actiongriddisplay(){
$model2=new Persons('search');
if(isset($_GET['ajax'])){
$model2->attributes =$_GET['Persons'];
$this->render('griddisplay',array('model2'=>$model2));
}
else{
$this->render('griddisplay',array('model2'=>$model2));
}
}
//in view file
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider' => $model2->Search(),
'filter' => $model2,
'ajaxType'=>'GET',
// 'ajaxUpdate'=>'items',
//'ajaxUrl' =>$this->createUrl('userManagement'),
'columns' => array(
array(
'name' => 'FirstName',
'header'=>'Full Name',
),
array(
'name' => 'user.survey_ids',
'header'=>'Survey ids',
'filter'=>CHtml::activeDropDownList($model2 ,'survey_ids', array('224'=>'224','223'=>'223','225'=>'225')),
'value'=>'isset($data->user->survey_ids)?$data->user->survey_ids:null'
),
I have put the search on, in models. why is the dropdown filter not working?
Why this is not working please help?

This link (http://www.yiiframework.com/wiki/281/searching-and-sorting-by-related-model-in-cgridview/) will solve your problem.

Related

Filters in CGridView not filtering

Can You check why filtering is not working in CGridView? When i type for exaple 'Adam' in filter field, nothing happens. I can't find my mistake, everything looks ok but not working. I helped with that article: Yii: CGridView Filter examples
CONTROLLER
<?php
class UzytkownikController extends CController
{
public function actionIndex()
{
$Dane = new Uzytkownik('search');
$Dane -> unsetAttributes(); // clear any default values
if(isset($_GET['Uzytkownik']))
{
$Dane->attributes=$_GET['Uzytkownik'];
}
$this -> render ('index', array(
'Dane' => $Dane,
));
}
}
?>
MODEL
<?php
class Uzytkownik extends CActiveRecord
{
public static function model($className=__CLASS__)
{
return parent::model($className);
}
public function search()
{
$criteria = new CDbCriteria;
$criteria -> compare('imie', $this -> imie, true);
return new CActiveDataProvider($this, array(
'criteria' => $criteria,
)
);
}
}
?>
WIEV
<?php
$this -> widget('zii.widgets.grid.CGridView', array(
'dataProvider' => $Dane -> search(),
'filter' => $Dane,
'columns' => array(
array(
'name' => 'imie',
'type'=>'raw',
),
array(
'name' => 'nazwisko',
'type'=>'raw',
'filter' => false,
),
array(
'name' => 'data',
'filter' => false,
),
),
)
);
?>
For future reference:
In order to make sure the $model->attributes "saves" the attributes the model needed the following addition:
public function rules() {
return array(
array('imie', 'safe', 'on'=>'search')
);
}
And $_GET should have been used instead of $_POST Because the CGridView widget uses GET when posting to the server:
class UzytkownikController extends CController
{
public function actionIndex()
{
$Dane = new Uzytkownik('search');
$Dane -> unsetAttributes(); // clear any default values
if(isset($_GET['Uzytkownik']))
{
$Dane->attributes=$_GET['Uzytkownik'];
}
$this -> render ('index', array(
'Dane' => $Dane,
));
}
}

Nested Whgridview. Grids disappear on sort or pagination click

I'm a newbie in Yii programming.
I'm using boostrap library on Yii via Yiistrap/Yiiwheels
I've created a relation table view
The related view is a Whgridview itself
The first (master grid) has a TbRelationColum clicking it i display the second grid (detail grid).
When I click on the row to display the sub grid, everything appears ok. When I change the sort order or the page of the sub grid disappear both grid.
I understand we should differentiate the css class of the pager and the sort of sub grid from the main grid. How to do this specifically in Yii-Way?
Is This the problem?
This is the view of the main grid:
$this->widget('yiiwheels.widgets.grid.WhGridView',array(
'id'=>'masterGrid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'template' => "{summary}{items}<div class=\"row-fluid\"><div class=\"pull-right\">{pager}</div></div>",
'type' => array(TbHtml::GRID_TYPE_BORDERED, TbHtml::GRID_TYPE_STRIPED),
'columns'=>array(
array(
'class' => 'yiiwheels.widgets.grid.WhRelationalColumn',
//'name' => 'multiMembers.id',
'type' => 'raw',
'header' => 'Sub Items',
'url' => $this->createUrl('multiGroup/ajaxSubItems'),
'cacheData' => false,
'value' => "CHtml::tag('button',array('class'=>'btn btn-primary'),'Sub Items')",
'htmlOptions'=>array('style'=>'width:90px;'),
'cssClass' => 'showSubItems',
),
'id',
'title',
array(
'class'=>'bootstrap.widgets.TbButtonColumn',
),
),
));
This is the sub-grid:
echo CHtml::tag('h3',array(),'Sub Items Group #"'.$id.'"');
$this->widget('yiiwheels.widgets.grid.WhGridView', array(
'id'=>'subGrid_'.$id,
'type'=>array(TbHtml::GRID_TYPE_BORDERED, TbHtml::GRID_TYPE_STRIPED),
'dataProvider' => $gridDataProvider,
'template' => "{summary}{items}<div class=\"row-fluid\"><div class=\"pull-right\">{pager}</div></div>",
'columns' => $gridColumns,
));
This is the controller:
/**
* Manages all models.
*/
public function actionAdmin()
{
$model=new MultiGroup('search');
$model->unsetAttributes(); // clear any default values
if (isset($_GET['MultiGroup'])) {
$model->attributes=$_GET['MultiGroup'];
}
$this->render('admin',array(
'model'=>$model,
));
}
public function actionAjaxSubItems()
{
$id = Yii::app()->getRequest()->getParam('id');
$model = $this->loadModel($id);
if($model->numSubItems > 0) {
$this->renderPartial('_child', array('id' => $id,
'gridDataProvider' => $this->getGridDataProvider($id),
'gridColumns' => $this->getGridColumns()
), false, true);
} else {
echo 'Non ci sono Sub Items.';
}
}
public function getGridDataProvider($id) {
$sql = 'SELECT * FROM multi_member WHERE groupid = :groupid ORDER BY lastname,firstname';
$cmd = Yii::app()->db->createCommand($sql);
$cmd->bindParam(':groupid', $id, PDO::PARAM_INT);
$result = $cmd->queryAll();
$dataProvider = new CArrayDataProvider(
$result, array(
'sort' => array(
'attributes' => array('id','groupid','firstname','lastname','membersince'),
'defaultOrder' => array('lastname' => CSort::SORT_ASC, 'firstname' => CSort::SORT_ASC),
),
'pagination' => array(
'pageSize' => 2,
),
));
return $dataProvider;
}
public function getGridColumns() {
return array('id', 'lastname', 'firstname', 'membersince');
}
How can I do?
thank you ..
If the extensions you're using all extend CGgridView, then you should be able to use option 'ajaxUpdate' (link to documentation).
Try setting 'ajaxUpdate'=>false in one of the grids (or in both of them) to see whether it helps you.
Sometimes setting ajaxUpdate to false is the only way I get get some grids to behave the way I want them to...

Yii, filtering and ordering column in grid view that has data from custom model function

This is follow up on this question:
Display related has_many data inside once cell in Yii TbExtendedGridView
I got that cell working, but now i have no idea how to make it sortable and filterable (filter field is hidden).
View:
$this->widget('bootstrap.widgets.TbExtendedGridView', array(
'id'=>'user-grid',
'dataProvider' => $model->search(),
'filter' => $model,
'columns' => array(
'user_name',
'favorite_color',
array(
'value'=>'$data->getAllDates()',
),
),
));
One user can have many Dates that can be single date or date range, so i have getAllDates function that fetches em all and put em all inside string so they can be represented inside single cell for that user.
Model:
public function relations()
{
return array(
'listofdates' => array(self::HAS_MANY, 'Dates', 'user_id'),
);
}
public function getAllDates()
{
$data = '';
foreach ($this->listofdates as $date) {
$data .= $date->start_date.'-'.$date->end_date;
}
return $data;
}
I have no idea how to enable filtering and search for dates column. There is no even title for it or filter field.
I can enable filter field for that column by adding 'name' => 'whatever', but of course there is no single column in database for that data so i get MYSQL error.
I'm guessing i need to create another custom function for filtering but i have no idea where to start.
you can create an additional field for filtering and sorting $datesFilter and filter like this:
in model:
public $datesFilter;
public function rules()
{
array(
array('datesFilter', 'safe', 'on'=>'search')
);
}
public function search()
{
$criteria=new CDbCriteria;
...
// filtering
if ($this->datesFilter!==null)
$criteria->addCondition('YOUR QUERY CONDITION');
...
// sorting
$sort = new CSort;
$sort->attributes =
array(
...
'datesFilter'=>=>array('asc'=>'YOUR SORT ASC', 'desc'=>'YOUR SORT DESC'),
);
}
in view:
$this->widget('bootstrap.widgets.TbExtendedGridView', array(
'id'=>'user-grid',
'dataProvider' => $model->search(),
'filter' => $model,
'columns' => array(
'user_name',
'favorite_color',
array(
'value'=>'$data->getAllDates()',
'name'=>'datesFilter',
),
),
));

Yii Model with combined tables using relations in Active Record

I've got the model class Contactindiv with relations and search as follows.
public function relations()
{
return array(
'contactlogs' => array(self::HAS_MANY, 'Contactlog', 'ContactIndivID'),
);
}
public function search()
{
$criteria=new CDbCriteria;
$criteria->compare('ContactIndivID',$this->ContactIndivID);
$criteria->compare('PersonalTitle',$this->PersonalTitle,true);
$criteria->compare('NameLast',$this->NameLast,true);
$criteria->compare('NameMiddle',$this->NameMiddle,true);
$criteria->compare('NameFirst',$this->NameFirst,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
The current page shows the data in a searchable CGridView format.
My goal is to combine the 'contactlogs' from relations into the Model in order to have it show up on the page in a searchable fashion in the GridView. Basically add a searchable GridView column for each contact showing their contact log.
Thanks ahead of time for your help!
For your first goal (show contactlogs in model) you can write a getter in your main model. It depends, what you want to show in your gridview column but you could use something like:
public function getContacts()
{
$names = array();
foreach($this->contactlogs as $log)
$names[] = $log->name;
return implode(', ', $names);
}
Now you can use contacts as if it where a regular attribute of your "Contactindiv" model.
For your second goal you could add a public property which will contain the filter value, and which you can use in your search() method:
public $contactFilter;
public function search()
{
// ...
if(!empty($this->contactFilter)) {
$criteria->with = array(
'contactlogs' => array(
'joinType' => 'INNER JOIN',
'on' => 'contactlogs.name = :name',
),
);
$criteria->params[':name'] = $this->contactFilter;
}
// ..
}
Now you only need to add all the above in your gridview's columns configuration:
array(
'name' => 'contacts',
'filter' => CHtml::activeTextField($model, 'contactFilter'),
)
Please note, that i'm writing most of this from the top of my head and couldn't fully test it. But it should hopefully make the basic concept clear to you. Please let me know if it works.

Searching/filtering two concatenated columns in cgridview

cgridview code in admi.php
array(
'header'=>'Client Name',
'name'=>'client_name',
'value'=>'$data->first_name." ".$data->last_name', //or u can write also value'=>'$data->first_name.\' \'.$data->last_name',
),
model search() class in client.php
public $client_name;
$criteria->compare('CONCAT(first_name,last_name)',$this->client_name,true);
Concatenation and displaying is done but seraching the data show no results found?
In model :
class User extends CActiveRecord
{
public $fullName;
}
in search
$criteria->addSearchCondition('concat(first_name, " ", last_name)', $this->fullName);
in rules()
array('..., fullName', 'safe', 'on' => 'search'),
in model created a function
public function getFullName()
{
return $this->first_name . ' ' . $this->last_name;
}
And last put it in your view:
<?php $this->widget('zii.widgets.grid.CGridView', array(
.......
'columns' => array(
array(
'name' => 'full_name',
'value' => '$data->getFullName()',
),
...