CListView sorting on data from another table - yii

I have a table that stores information about a role. In that table I have two fields that store the ids from other tables.
Table one: id, rname, pname, idtwo, idthree
Table two: id, twoname
Table three: id, threename
My ClistView displays rname, pname, twoname, threename
With this forums help I was able to use a CListView and display the names from tables two and three.
What I would now like to do is be able to do is create a view where the information is sorted on twoname and aonther view where the data is sorted on threename.
My actionIndex is:
public function actionIndex() {
$dataProvider = new CActiveDataProvider('Staffroleprofile');
$this->render('index', array(
'dataProvider' => $dataProvider,
));
}
and my _view.php is:
<h1>List of SRP's</h1>
<?php
$dataProvider->sort->defaultOrder='rname ASC';
?>
<?php $this->widget('zii.widgets.CListView', array(
'dataProvider'=>$dataProvider,
'itemView'=>'_view',
)); ?>
so the above gives me the data sorted by rname from table one. How would I specify that I want the data to be sorted by the data in table two or three?
Kind regards,
e25taki

If model2 and model3 are the relations for table 2 and 3 respectively in Staffroleprofile, add this to your code
$dataProvider = new CActiveDataProvider('Staffroleprofile');
$criteria=new CDbCriteria;
$criteria->together=true;
$criteria->with=array('model2','model3');
$dataProvider->criteria=$criteria;
$dataProvider->sort->defaultOrder='model2.twoname ASC';
CDbCriteria::together specifies whether the query should be run using a join. If set to false additional queries are run for each record if a relation is required. For more detail go to the API pages for CDbCriteria and CActiveDataProvider

all good now, the code I required was:
$dataProvider = new CActiveDataProvider('Staffroleprofile');
$criteria=new CDbCriteria;
$criteria->together=true;
$criteria->with=array('sitename','businessname');
$dataProvider->criteria=$criteria;
$dataProvider->sort->defaultOrder='sitename.site ASC';
$this->render('index_bysite', array(
'dataProvider' => $dataProvider,
));
so, you get ba handle to the records from the Staffrleprofile model and then add the criteria for the sorting, in this case it was based on a relation.
Thank you all for your assistance. Another little step in my Yii learning adventure.
Cheers!
e25taki

Related

how to show database column value during dropdown selecetion on yii2

i am using Yii2, i have two tables and two models:
table 1: tenderprice:(id, itemname, quanity)(id is primary key) with model name=Tenderprice, table 2:tenderpricelist:id pk,singleprice, totalprice,tenderpriceid: (tenderpriceid is foreign key refers to Tenderprice) with model name: Tenderpricelist
now i want quantity when itemname is selected:
<?
$itemtenders=Tenderprice::find()->all();
$itemlist=ArrayHelper::map($itemtenders,'id','itemname');
echo $form->field($model, 'tenderpriceid')->dropDownList($itemlist,['prompt'=>'Select tender'])->hint('Please choose item one by one')->label('Add Items');
?>
// inserting data into tenderpricelist based on the selection of table tenderprice
<?= $form->field($model, 'singleprice')->textInput(['maxlength' => true])->hint('Please enter your price') ?>
<?= $form->field($model, 'totalprice')->textInput(['maxlength' => true])
?>
Now i want to insert data into tenderpricelist table based on the item name selected from dropdownlist.The dropdownlist fills correctly but i cannot access the value of "quantity" column when itemname is selected.
I just want when i select item name from the dropdownlist, its corresponding quanity will be shown on textbox or label and the totalprice column in my table tenderpricelist will be : totalprice
totalprice=quantity *singleprice
Note: singleprice is in table tenderpricelist, while quantity is in parent table tenderprice.
The best option is to handle that in the controller (If your validation requires to have the quantity value) or model (If is not required on validation) after you get the information from the $form back. There, before the validate and before save, you can operate with the value given by:
$_GET ($tenderId = Yii::$app->response->get('FormName['tenderpriceid']))
or
$_POST ($tenderId = Yii::$app->response->post('FormName['tenderpriceid']))
The "FormName" you have to review it by looking on the debug. Once you get the $tenderId you can make a database query and find the quantity:
$quantity = Tenderprice::find()->one()->where(['id' => $tenderId]);
And then you can pass that value to the save or update option. Let me know if this works, or please post the model and controller.

YII: Dropdownlist with relation

DB table:
Mcourse(Master course )-> contains Course Names
Lcourse(Linked
Course- courses belongs to a college) -> contains foreign key
Mcourse_Id. & college Id.
Nw the problem is
I want to display list of courses available in a college using dropdownlist.
So sql query is:
select Lcourse_Id, Mcourse_Name* from Lcourse inner join Mcourse on Lcourse_Mcourse_Id=Mcourse Id..
*Id & value pair for dropdownlist
I could do this usin createCommand..Its working pretty fine. But i cant do this usin Relations ..Help me.
Let's imagine for a minute that your Mcourse table is called courses and model for that table is called Courses, your Lcourse table is called courses_colleges and your colleges table is colleges and model for that table is Colleges
Now, You should have Courses model with relations:
public function relations() {
return array(
'colleges' => array(self::MANY_MANY, 'Colleges', 'courses_colleges(course_id, college_id)')
);
}
Your Colleges model should have similar relations:
public function relations() {
return array(
'courses' => array(self::MANY_MANY, 'Courses', 'courses_colleges(college_id, course_id)')
);
}
Now if you want to print out a dropdown with all courses available for a certain college. In your controller action method get the model of that college including its courses:
public function actionShow() {
$id = 1; // We set just some sample id. You could get it from request ofc.
$college = Colleges::model()->with('courses')->findByPk($id);
$this->render('show', array('college'=>$college));
}
Now in your view print out this:
echo CHtml::dropDownList('courses', '', CHtml::listData($college->courses, 'id', 'name'));
Where 'id' and 'name' are columns of your Courses model.
Something like that.
The error is in the listData() function in your view, specifically that you don't have a mc_Id in your Lcourse model.
As you haven't clarified the model that each of those relationships are assigned with, it's impossible to guess what you should substitute for 'mc_Id' in your view - check your Lcourse model to determine the proper column name.

displaying Cgridview in yii

how can i display a record in Cgridview?
tbl_book:
id
title
author
tbl_in_out:
id
book_id
date_out
date_in
I have created a relationship that the book_id in tbl_in_out belongs to id in tbl_book.
what i want to do is to query a record in the tbl_in_out with the corresponding data in tbl_book and display it in the CGridview(sorry for the bad english). Please help!
Basic grid view:
// the following code goes in your view
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider'=>$dataProvider,
'columns'=>array(
'book.title', // assuming the name of the relation is "book" in model of tbl_in_out
'book.author',
'date_out',
'date_in'
)
));
You'll need to pass the data provider from the controller:
$dataProvider=new CActiveDataProvider('InOut'); // assuming the name of your model for tbl_in_out is InOut
$this->render('gridviewname',array('dataProvider'=>$dataProvider));

Yii order by another table CActiveDataProvider

I am a bit stumped on this. Basically I have two tables:
Page:
id
name
Points:
id-
pageid
points
I am looking to get the records from the Page table, and sort it by the amount of points it has in the Points table (the points field)
Currently I have:
$dataProvider=new CActiveDataProvider('Page',array(
'criteria'=>array(
'condition'=>"active = 1 AND userid IN (".$ids.")",
'order'=>"???",
),
'pagination'=>array(
'pageSize'=>30,
),
));
I just don't know how to sort it by the Points table value for the relevant record
I have set up a relation for the Page/Points tables like so:
(in the Page model)
'pagepoints' => array(self::HAS_ONE, 'Points', 'pageid'),
Thanks
You need to do two things:
Add the pagepoints relation to the with part of the query criteria
Reference the column you want to sort by in the order part of the criteria
I 've marked the lines where this happens in the code below:
$dataProvider = new CActiveDataProvider('Page', array(
'criteria'=>array(
'with' => array('pagepoints'), // #1
'condition' => 'active = 1 AND userid IN ('.$ids.')',
'order' => 'pagepoints.points', // #2
),
'pagination'=>array(
'pageSize'=>30,
),
));
What you need to know to understand how this works is that when Yii builds the SQL query (which is a LEFT OUTER JOIN to the Points table), it uses the name you gave to the relation in the Page model (you give the definition for this, it's pagepoints) to alias the joined table. In other words, the query looks like:
SELECT ... FROM Page ... LEFT OUTER JOIN `Points` `pagepoints` ...
It follows that the correct specification for the sort order is pagepoints.points: pagepoints is the table alias, and points is the column in that table.
Try the following
$dataProvider=new CActiveDataProvider('Page',array(
'criteria'=>array(
'with'=>array('pagepoints'),
'condition'=>"active = 1 AND userid IN (".$ids.")",
'order'=>"t.points DESC",
),
'pagination'=>array(
'pageSize'=>30,
),
));
this is the sql you want to generate:
select * from page inner join points
on page.id = points.page_id order by
points.points desc

Getting data with CActiveDataProvider in yii

I have 3 tables, standart relation MANY-TO-MANY
Users(id,...) -> Users_Has_Courses(Users_id, Courses_id) -> Courses(id,...)
Courses Model has next relation
'users' => array(self::MANY_MANY, 'Users', 'users_has_courses(Courses_id, Users_id)')
Users Model has next relation
'courses' => array(self::MANY_MANY, 'Courses', 'users_has_courses(Users_id, Courses_id)')
Please, say how I can get list of courses, on which user with specified "id" hasn't been subscribed with CActiveDataProvider ?
Otherwords, I need an analogue of this plain SQL query
select * from Courses where id not in (select Courses_id from users_has_courses where Users_id = 2)
thanks for the help
Instead of a regular "relation", try a parametrized Named Scope to encapsulate the query. In your Courses model, add this scope function to get a list of all the courses the user is not in:
public function userNotIn($user_id)
{
$criteria=new CDbCriteria();
$criteria->condition .= 't.id NOT IN (SELECT users_has_courses.Courses_id FROM users_has_courses WHERE users_has_courses.Users_id = :userid)';
$criteria->params[':userid'] = $user_id;
$this->getDbCriteria()->mergeWith($criteria);
return $this;
}
Then you should be able to do this:
$coursesNotIn=new CActiveDataProvider(Courses::model()->userNotIn($user->id));
This code is completely untested, but it should work in principle. I do this sort of thing often when I have a complex query but I still want to use the AR features, like CActiveDataProvider. Read more about "named scopes" here:
http://www.yiiframework.com/doc/guide/1.1/en/database.ar#parameterized-named-scopes
Good luck!