Yii Condition in CGridView Column - yii

I want to add a condition in a column of CGridView
I want to add a function in which the column is visible depending on a condition.
If status is equal to 10 column display. If not equal to 10, not shown
Hi, thanks for your answer. Im try your solution but doesn't work.
The column is part of a table from a query in which two tables are used: files and user. The query displays a user uploaded files, what I want is that the column that says looks "View" when the file status is 10
I try this
array(
'imageUrl'=>Yii::app()->baseUrl . '/img/view.png',
'header'=>'View',
'class'=>'CLinkColumn',
'linkHtmlOptions'=>array('title'=>'View'),
'visible'=> '$data->status == 10'
)
And This
array(
'imageUrl'=>Yii::app()->baseUrl . '/img/view.png',
'header'=>'View',
'class'=>'CLinkColumn',
'linkHtmlOptions'=>array('title'=>'View'),
'visible'=> '$data->status == 10?True:False'
)
Doesnt work!. PLease Help

Test functions. For example:
<?php
function isVisible($status){
if($status == 10) return true;
else return false;
}
?>
// CGridView
array(
'imageUrl'=>Yii::app()->baseUrl . '/img/view.png',
'header'=>'View',
'class'=>'CLinkColumn', 'linkHtmlOptions'=>array('title'=>'View'),
'visible'=> 'isVisible($data->status)'
)

Related

Display name instead of Id in Yii

I want to display the name of Shift instead of shift_id
I have a dropboxlist from other table that is like this
<div>
<?php echo $form->labelEx($model,'mon'); ?>
<?php echo $form->dropDownList($model, 'mon', CHtml::listData(
Shift::model()->findAll(), 'shft_id', 'name'),
array('prompt' => 'Select a Department')
); ?>
<?php echo $form->error($model,'mon'); ?>
I have two tables that is
Day: id_day,mon,tues,wed,etc
Shift: shft_id,start,end,name,status
Here is the relation in the day
'shift'=>array(self::HAS_MANY,'Shift','shft_id'),
For Shift:
'day'=>array(self::BELONGS_TO,'Day','id_day'),
It is already working. The choices in the dropbox was the name of the Shift, and puts the shft_id in the mon,tues,wed,etc. In the view of the form it looks like
id_user: 3
mon:5
tues:5
wed:6
what I wanted to be is that in the view.
id_user: 3
mon: 6am-5pm
tues: 7am-6pm
etc.etc.
I dont know what command it is. I have no idea. Help me please
Instead of User::getusername() method.
I think you can simply use this in one line.
// format models resulting using listData
<?php echo $form->dropdownlist($model,'user_id', CHtml::listData(User::model()->findAll(),'id', 'name')); ?>
below is an example which I think may solved your problem
in _form.php
<?php echo $form->dropdownlist($model,'user_id', User::getusername()); ?>
<?php echo $form->error($model,'user_id'); ?></th>
in User model
public function getusername()
{
$criteria2=new CDbCriteria;
$criteria2->select='*';
$quser=User::model()->findAll($criteria2);
foreach($quser as $r)
{
$user_id= $r->user_id;
$user_name=$r->user_name;
$user_array[$user_id]=$user_name;
}
return $user_array;
}
I'm trying to understand what you are really asking. I believe you were saying that you are already able to populate your records correctly from the dropdowns. But when you are displaying, the view is only showing the shift_id value? The relation for the day should be able to get your shift name. How are you displaying the list:
mon: 5
tue: 5
wed: 6
I'm trying to understand if you need help displaying the dropdown items properly, or how to display the shift name later after the values have been set in the database. Also, your 'Day' table has me confused. What are the field names? Are they 'day_id' and 'day'? Or do you actually name the fields after each day of the week?
If you are displaying the data through a foreach and are getting each day (let's assume it is $day) object, then the relationship to 'shift' can give you the name like this: echo $day->shift->name; if the name displays as '#am-#pm'. Otherwise you can display it like this:
echo sprintf('%d a.m. - %d p.m.',$day->shift->start,$day->shift->end);
Thanks for the people who helped me. It did lead me to the answer anyone who has the same problem here is what i did.
In my model/Day
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(
'monday'=>array(self::BELONGS_TO,'Shift','mon'),
'tuesday'=>array(self::BELONGS_TO,'Shift','tue'),
'wednesday'=>array(self::BELONGS_TO,'Shift','wed'),
'thursday'=>array(self::BELONGS_TO,'Shift','thurs'),
'friday'=>array(self::BELONGS_TO,'Shift','fri'),
'saturday'=>array(self::BELONGS_TO,'Shift','sat'),
'sunday'=>array(self::BELONGS_TO,'Shift','sun'),
);
}
and In my models/Shift
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(
'day_mon' =>array(self::HAS_MANY,'Day','mon'),
'day_tue' =>array(self::HAS_MANY,'Day','tue'),
'day_wed' =>array(self::HAS_MANY,'Day','wed'),
'day_thurs'=> array(self::HAS_MANY,'Day','thurs'),
'day_fri'=>array(self::HAS_MANY,'Day','fri'),
'day_sat'=>array(self::HAS_MANY,'Day','sat'),
'day_sun'=>array(self::HAS_MANY,'Day','sun'),
);
}
The problem is with my relations. its not set properly, so you need to set it properly then go to Day/view
<?php $this->widget('bootstrap.widgets.TbDetailView',array(
'data'=>$model,
'attributes'=>array(
'id_day',
array(
'name'=>'mon',
'value'=>CHtml::encode($model->monday->name)
),
Here is the output
If you have a detail veiw then use the following code:
widget('zii.widgets.CDetailView', array(
'data'=>$model,
'attributes'=>array(
'id',
'name',
array(
'label' => $model->shift->getAttributeLabel('shift_name'),
'value' => $model->shift->shift_name
),)); ?>
In case anybody else will be in my boat, what you will need to do is edit view.php in view/modelname/view.php
widget('zii.widgets.CDetailView', array(
'data'=>$model,
'attributes'=>array(
'id',
'name',
'country_id')); ?>
into
widget('zii.widgets.CDetailView', array(
'data'=>$model,
'attributes'=>array(
'id',
'name',
array(
'label' => $model->country->getAttributeLabel('country'),
'value' => $model->country->name
),)); ?>

How do I apply a CDataColumn filter to my CGridView so it displays only rows with a null-value?

I have a model with a boolean value, generated from a table like this:
CREATE TABLE receivable (
...
is_paid INTEGER DEFAULT NULL,
...
)
You should only take notice of the possible NULL value.
I have a gii-generated Receivable.php-model and a simple CGridView, like this:
$dataProvider = $model->search();
$dataProvider->pagination = ['pageSize'=>20];
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider'=>$dataProvider,
'filter'=>$model,
'columns'=>array(
'id',
[
'name'=>'is_paid',
'type'=>'raw',
'value'=>'($data->is_paid==1)?"PAID":"";',
'filter'=>['1'=>'PAID', '0'=>'0']
],
'someothercolumn',
['class'=>'CButtonColumn']
),
);
It should make sense so far? It does work fine I must say, with just one tiny problem - I want to allow filtering on null values as well!
'filter'=>['1'=>'PAID', '0'=>'0', null=>'null'] // This shows all records.
'filter'=>['1'=>'PAID', '0'=>'0', ''=>'null'] // This also shows all records.
'filter'=>['1'=>'PAID', '<>1'=>'null or zero'] // This shows 0-records only.
Well, now I'm at a loss. Is there any way I can use the CDataColumn.filter to allow the user to filter on null values? (Only display rows where 'is_paid'==null)
Edit: Values can be 1,0 or NULL, but the filter can only be applied for 1 or 0 (or show everything). How can I let the user display rows with null-values only?
Any help is much appreciated!
this is one way you can do it
1.'filter' => array('0' => Yii::t('app', 'No'), '1' => Yii::t('app', 'Yes')),
or something like this
2.is_paid:boolean
or something like this
3.'filter' => CHtml::listData(UserRegistry::model()->findAll(), 'id_user_registry', 'firstname' ),
In the above example i have the values in a db table
or something like this
4.'filter' => Lookup::items('option'),
and for the above example in the model you would have something like this
4. public static function items($type, $code)
{
if(!isset(self::$_items[$type]))
self::loadItems($type);
return isset(self::$_items[$type][$code]) ? self::$_items[$type][$code] : false;
}
private static function loadItems($type)
{
self::$_items[$type]=array();
$models=self::model()->findAll(array(
'condition'=>'type=:type',
'params'=>array(':type'=>$type),
//'order'=>'position',
));
foreach($models as $model)
self::$_items[$type][$model->code]=$model->name;
}

My cgridview is showing only one record in yii

i am newbii in yii development and have an issue while displaying data using cgridview as it is showing only first record
Motel,Hotel,Roomcategory and halls are models in which PK and FK are passing ...
Code is here
$sponsorm = Motel::model()->find('MotelId=:MotelId', array(':MotelId'=>Yii::app()->user->id));
$sponsorhotel = Hotel::model()->find('hotelId=:hotelId', array(':hotelId'=>$sponsorm->MotelId));
$room = Roomcategory::model()->find('hotelId=:hotelId', array(':hotelId'=>$sponsorhotel->hotelId));
$halls = Halls::model()->find('hotelId=:hotelId', array(':hotelId'=>$sponsorhotel->hotelId));
echo CHtml::image(Yii::app()->request->baseUrl.'/img/4.png');
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'businessowner-grid',
'dataProvider'=>$room->search(),
//'filter'=>$sponsore,
'columns'=>array(
'roomCategoryNames',
'noOfRooms',
'price',
),
));
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'businessowner-grid',
'dataProvider'=>$halls->search(),
//'filter'=>$sponsore,
'columns'=>array(
'Type',
//'noOfHalls',
'seats',
'price',
),
));
Right now you are finding only one record because you use find to get one specific record. So you assign this record data to model variables and then you do
$model->search();
This searches from specific table multiple values but you have set the attributes so, that it matches only one record.
To get Motel gridview data use following code:
$sponsorm = $dataProvider=new CActiveDataProvider('Motel', array(
'criteria'=>array(
'condition'=>'MotelId = :MotelId',
'params' => array(':MotelId'=>Yii::app()->user->id)
),
));
It is doing the same as search() but the difference is that searching criteria is different. You can use also code below.
$motelModel = new Model();
$motelModel->MotelId = Yii::app()->user->id;
Now there is only one attribute assigned an is setting a criteria to match all rows what has this user id in MotelId field.
$modelModel->search();
Also, I see that you echo something between logic. Please do not do that. Output data only in views and keep the logic out of views. :)

Yii CGridView sorting and searching with relation table

I have 3 tables in my database,
Image is below, I have followed http://www.yiiframework.com/wiki/281/searching-and-sorting-by-related-model-in-cgridview/
to get final grid with with search and sort purpose. so i have connected 2 tables in search() function like
public function search()
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria=new CDbCriteria;
$criteria->with = array( 'bposite' );
$criteria->together = false;
$criteria->with = array( 'client' );
$criteria->compare('id',$this->id);
// $criteria->compare('client_id',$this->client_id);
// $criteria->compare('bposite_id',$this->bposite_id);
$criteria->compare('userid',$this->userid,true);
$criteria->compare('password',$this->password,true);
$criteria->compare( 'bposite.name', $this->bposite_search, true );
$criteria->compare( 'client.name', $this->client_search, true );
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
'sort'=>array(
'attributes'=>array(
'client_search'=>array(
'asc'=>'client.name',
'desc'=>'client.name DESC',
),
'bposite_search'=>array(
'asc'=>'bposite.name',
'desc'=>'bposite.name DESC',
),
'*',
),
),
));
}
}
But I am getting result for client, bposite seach and sort is showing problem like
> Error 500: <h1>CDbException</h1>
> <p>CDbCommand failed to execute the SQL statement: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'bposite.name'
> in 'where clause'. The SQL statement executed was: SELECT
> COUNT(DISTINCT `t`.`id`) FROM `clientbposites` `t` LEFT OUTER JOIN
> `client` `client` ON (`t`.`client_id`=`client`.`id`) WHERE
> (bposite.name LIKE :ycp0)
> (D:\wamp\www\yi\framework\db\CDbCommand.php:516)</p><pre>#0
> D:\wamp\www\yi\framework\db\CDbCommand.php(411):
> CDbCommand->queryInternal('fetchColumn', 0, Array)
how can implement non-related table with cgridview search and sort options.
I've made a step by step blog post about this. Feel free to read it and ask questions if you're stuck. Instead of repeating myself by writing everything here too, here's the link: http://www.mrsoundless.com/post/2011/05/09/Searching-and-sorting-a-column-from-a-related-table-in-a-CGridView.aspx
It seems to have helped a bunch of people. Hope it helps you too :)

How can I display a single record in 2 rows by using Yii CGridView?

I am using CGridView in Yii, how can I display a single record in 2 lines?
Basically I want to show a record details in 1st row of table and on other row I want to display its summary, I tried it with div and css but can't get proper results, is anyone there who can help me in this case?
I am using like this:
<?php
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'bidding-grid',
'itemsCssClass' => 'data-default',
'dataProvider'=>$model,
'summaryText' => '',
'columns'=>array(
'people_detail_for_bid.Person' => array(
'type'=>'raw',
'name'=>'people_detail_for_bid.Person',
'value'=>'Yii::app()->Controller->createUserNameLink($data->people_detail_for_bid->PeopleFirstName." ".$data->people_detail_for_bid->PeopleLastName, $data->people_detail_for_bid->PeopleId).
"<br><span class=decriptionText>".$data->people_detail_for_bid->PeopleDesignation."</span>".
"<br><span class=decriptionText>".$data->people_detail_for_bid->PeopleEmail."</span>"',
'htmlOptions'=>array('width'=>200),
),
'timeAgo' => array(
'type'=>'raw',
'name'=>'timeAgo',
'value'=>'"<span class=decriptionText>".Yii::app()->Controller->_ago($data->PBPostedOn)."</sapn>"',
'htmlOptions'=>array('width'=>150),
),
),
));
?>
I think the best and cleanest way to accomplish this is to create a new extension and extend it to CGridView, override the renderTableRow function like this:
/**
* Renders a table body row.
* #param integer $row the row number (zero-based).
*/
public function renderTableRow($row)
{
if($this->rowCssClassExpression!==null)
{
$data=$this->dataProvider->data[$row];
echo '<tr class="'.$this->evaluateExpression($this->rowCssClassExpression,array('row'=>$row,'data'=>$data)).'">';
}
else if(is_array($this->rowCssClass) && ($n=count($this->rowCssClass))>0)
echo '<tr class="'.$this->rowCssClass[$row%$n].'">';
else
echo '<tr>';
$colCtr = 0;
foreach($this->columns as $column){
$column->renderDataCell($row);
$colCtr++;
}
echo "</tr>\n";
echo "<tr><td colspan=\"$colCtr\">This is the summary row. </td></tr>";
}
You can customize what you are rendering in the columns, so if you want to show two different fields of your table in the same row, you have to create a function in your model:
public function customColumn()
{
return $this->PeopleDesignation.'<br/>'.$this->PeopleEmail;
}
And then assign the method to the value of your column:
array(
'type'=>'html',
'value'=>'$data->customColumn()'
),
Cheers, Pablo.
After too much search .. and I tried with different ways now finally got a solution for this .. that solution is basically a kind of 2nd way to do anything not actual way .. but it works to me ..
.....
.....
'timeAgo' => array(
'type'=>'raw',
'name'=>'timeAgo',
'value'=>'"<span class=decriptionText>".Yii::app()->Controller->_ago($data->PBPostedOn)."</sapn></td></tr><tr><td colspan=\"6\"><span class=decriptionText>".$data->PBSummary."</span>"',
'htmlOptions'=>array('width'=>150),
),
.....
.....
added some table tags on last column to close row and added another one.
hope it works for all ..
thanks ..
Sounds like 2 interleaved CGridViews. So you might try that, but I can't imagine it will work out well:
Overlay one CGridView over the other, with enough transparent space in each row for the other to display it's row, and ...
a. one `CGridView` table offset vertically by half a row height, *OR*
b. one table's row's text vertically top-aligned & the other bottom-aligned
But somehow I doubt that's a CGridView capability ;) And keeping the two in sync so they pagenate and scroll together would be darn near impossible. Sounds like you need to enhance CGridView or derive a new widget from CGridView. I wonder if JQuery has something to do this?