Display name instead of Id in Yii - 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
),)); ?>

Related

cgridveiw to display fetched data via customized query

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....

Displaying data from different tables in a view

I have a requirement where I would like to display a list of records and the information from each record can come from a umber of tables. To further explain I have the following tables:
Table srp with columns id (PK), srpname, idbusiness (FK), idsite (FK)
Table business with columns id (PK), businessname
Table site with columns id (PK), sitename
Table srpprimary with columns id (PK), idsrp (FK), pname
Table srpdepname with columns id (PK), idsrp (FK), dname
An srp can have multiple entries in the table srpprimary and one entry in each of the other tables business, site, srpdepname
What I would like is to display an srp record along with all the pname entries in the table srpprimary, the dname from the table srpdepname and the actual business name and site name.
I looked at the CListView but could not see how I could get this additional data.
Any suggestions on how the above could best be achieved would be greatly appreciated.
Kind regards
e25taki
To help you in this question and in your next project I recommended you to use database relations :
1- prraper your datbase
2- write your relations on paper bettwen tables
3- do it (use phpmyadmin for example ):
by GUI methode
How to create a relation between two tables using PHPMyAdmin?
https://www.youtube.com/watch?v=IdQGFZwP7Xc
Sql method
ALTER TABLE Orders
ADD CONSTRAINT fk_PerOrders
FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id)
4- now you can use yii gii to create your code and all you relations will be save in model class
5- load data in view will be so so easy now :
For Example if your model is like :
<?php
..
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(
'co' => array(self::BELONGS_TO, 'Country', 'co_id'),
'events' => array(self::HAS_MANY, 'Events', 'city'),
'news' => array(self::HAS_MANY, 'News', 'city'), /// here
'users' => array(self::HAS_MANY, 'Users', 'city'),
);
}
...
?>
So we can access to all news table that related to current city by call it as :
echo $model->news->title;
It's all about the relations in your models.
With correct relations, you can access data like:
$srp = Srp::model()->findByPk(1);
$sites = $srp->sites; // gets an active record-array with a HAS_MANY-relation
$site = $srp->site; // gets the active record directly with a HAS_ONE-relation
Considering the code generation in Gii, you'll have a much easier time if you rename your foreign keys so they end with "id" or "_id". That way, you'll get sensiblle relations automatically when you generate your models. (Though they still might need to be tweaked a bit to suit your needs.)
With your new relations, you can create a listview like this in your view:
$dataProvider=new CActiveDataProvider('Srp');
$this->widget('zii.widgets.CListView', array(
'dataProvider' => $dataProvider,
'itemView' => '_view',
));
And access your data something like this (_view.php) :
<b>Id:</b> // Or better yet: echo CHtml::encode($data->getAttributeLabel('id'));
<?php echo $data->id; ?>
<br />
<b>Business:</b>
<?php echo $data->business->name; ?>
<br />
<b>Site:</b>
<?php echo $data->site->name; ?>
<br />
<b>Depname:</b>
<?php foreach ($data->srpdepnames as $dep): ?>
<?php echo $dep->dname; ?>,
<?php endforeach ?>
<br />
<b>Depname:</b>
<b><?php echo CHtml::encode($data->getAttributeLabel('srpprimary_id')); ?>:</b>
<?php foreach ($data->srpprimaries as $prime ){
echo CHtml::link( // If you want links instead of just text.
CHtml::encode($prime->pname),
array('SrpPrimary/View', 'id'=>$prime->id)
);
}?>
(I haven't tried this, so it's not a working example. Sorry! But it should give you an idea and it's not far from the truth. )
In controller.php
public function actionQueries()
{
$dataProvider=new CActiveDataProvider('Student', array(
'criteria' => array(
'with' =>'student',
'join' => 'INNER JOIN studentinfo si ON si.stud_id=t.id',
)
));
$this->render('query',array(
'dataProvider'=> $dataProvider,
));
}
in a view,in tables model view make php file for ex query.php
<?php
/* #var $this StudentController */
/* #var $model Student */
$this->breadcrumbs=array(
'Students'=>array('query'),
//$user->name,
);
$this->widget('zii.widgets.CListView', array(
'dataProvider'=>$dataProvider,
'itemView'=>'_view', // refers to the partial view named '_post'
'enablePagination'=>true,
'sortableAttributes'=>array(
'name',
)
));
?>
// add your new feilds in _view.php file:
// in controller.php
in accsessRule() add your new file for authentication for ex.queris
public function accessRules()
{
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('index','view','queries'),
'users'=>array('*'),
),
}

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 - Widgets - Explanation

I am trying to use drop down list widget :
$this->widget('ext.multiselect.JMultiSelect',array(
'model'=>$model,
'attribute'=>'attribute',
'data'=>$data,
// additional javascript options for the MultiSelect plugin
'options'=>array()
));
What I want to know is that Details of each option available in the widget array Like what is 'attribute' , 'model' and'data' represent , as I an unable to understand it form the documentation.
The model param is the model you are creating the multi select for.
The attribute is the model attribute you are creating the multi select for.
The data is an array of key/value pairs for the list items you want to display in the multi select.
For example, if you had a model 'User' and in that model you had a field 'access_rights' and you wanted to have that field as a multi select box with a few values, you might do something like:
In your controller:
$model = new User;
$data = array(
'admin_area'=>'Admin Area Access',
'product_area'=>'Product Area Access',
'customer_area'=>'Customer Area Access',
... etc
);
In your form in your view file:
$this->widget('ext.multiselect.JMultiSelect',array(
'model'=>$model,
'attribute'=>'access_rights',
'data'=>$data,
// additional javascript options for the MultiSelect plugin
'options'=>array()
));
Edit:
To add data to the multi select options from another model you can use the CHtml::listData() method, this takes an active record result set and converts it into an array of key/value pairs so you can use in any of the other CHtml methods that require a key/value pair. To do this you simply get the records you're after from the database using active record, eg;
$myData = Data::model->findAll();
You can then put that into the listData() method and it'll create your array:
$this->widget('ext.multiselect.JMultiSelect',array(
'model'=>$model,
'attribute'=>'access_rights',
'data'=>CHtml::listData($myData, 'id', 'name'),
// additional javascript options for the MultiSelect plugin
'options'=>array()
));
(where 'id' and 'name' are the fields from the model table that you want to be the 'key' and 'value' within the array)
echo $form->dropDownList($model, 'category', CHtml::listData(TblCategory::model()->findAll(),
'id', 'category_name'), array('empty' => '---Select Category---',
'style' => 'width:350px;')), array() ?>
<?php echo $form->error($model, 'category'); ?>

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?