Yii2 Querybuilder with searchmodel - php

My searchmodel
$query = (new \yii\db\Query())
->select(['monthsubmit',"DATE_FORMAT(monthsubmit, '%m-%Y') as c_date", 'modeler', 'count(sku) as count'])
->from('sku3d')
->groupBy(['monthsubmit', 'modeler'])
->orderBy(['monthsubmit'=>SORT_DESC, 'modeler'=>SORT_DESC]);
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
My controller
$searchModel = new Sku3dSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
My gridview
<?php echo GridView::widget([
'dataProvider' => $dataProvider,
'filterModel'=>$searchModel,
'pjax'=>true,
'panel' => [
'type' => GridView::TYPE_PRIMARY,
'heading' => '<h3 class="panel-title"><i class="glyphicon glyphicon-user"></i>Submitted SKU by Month</h3>',
],
'columns' => [
[
'attribute'=>'monthsubmit',
'width'=>'310px',
'filter'=>ArrayHelper::map(Sku3d::find()->orderBy('monthsubmit')->asArray()->all(), 'monthsubmit', 'monthsubmit'),
'group'=>true,
],
[
'attribute'=>'modeler',
'width'=>'180px',
'group'=>true,
],
'count:text:Total Sku',
]
]);
?>
At first I didn't use querybuilder in searchmodel but in controller and everything worked fine. But I need to filter it also so i moved my querybuilder into searchmodel.
When I did this, it had error "Getting unknown property:app\models\Sku3d::count".
How can I call the 'count(sku) as count' to my gridview. And also it look like my groupBy(['monthsubmit', 'modeler']) not working also.
Please tell me where I'm wrong.
Thank you.

In your searchmodel add a publica var
class Sku3dSearch extends Sku3d
{
public $count;
/**
* #inheritdoc
*/
public function rules()
......
$query = (new \yii\db\Query())
->select(['monthsubmit',"DATE_FORMAT(monthsubmit, '%m-%Y') as c_date", 'modeler', 'count(sku) as count'])
->from('sku3d')
->groupBy(['monthsubmit', 'modeler'])
->orderBy(['monthsubmit'=>SORT_DESC, 'modeler'=>SORT_DESC]);
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
}

Related

How to integrate SQL-Generated columns in Yii2 GridView

To show my GridView I use this ActiveDataProvider:
public function search($params)
{
$query = PublicationsPublication::find()
->select(['eid', 'title', 'pubdate', 'citedby', "STRING_AGG(DISTINCT(CONCAT(author.authid, ' - ', authname)), ', ') AS authors"])
->joinWith('publicationsAuthor')
->groupBy(['eid','title','pubdate','citedby']);
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
return $dataProvider;
}
...
}
I can't figure out how to use the column generated by the STRING_AGG() function in the Gridview.
Just in case is needed, the publicationsAuthor relation is coded this way:
public function getPublicationsAuthor() {
return $this->hasMany(PublicationsAuthor::className(), ['authid' => 'authid'])
->viaTable('publications.pub_author', ['pubid' => 'id']);
}
I need to use the STRING_AGG() function because I want to show many authors in one cell of the Gridview.
I tried to use the "authors" column in this way:
$gridColumns = [
[
'class' => 'kartik\grid\SerialColumn',
'width' => '20px',
],
'eid',
'title',
'pubdate',
'citedby',
'authors',
];
echo GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => $gridColumns,
'pager' => [
'firstPageLabel' => 'First',
'lastPageLabel' => 'Last'
],
...
]);
But unfortunately it didn't work. In the Grid all the values are set to "not set". The query works great because I tested it in PgAdmin.
yii\data\ActiveDataProvider works with models so only fields defined by model are available by default. The easiest way to add field generated by some expression is to add public property with same name to your model like this:
class PublicationsPublication extends ActiveRecord
{
public $authors;
// ... other code in PublicationsPublication model ...
public function attributeLabels()
{
// You can also add label for new field
return [
'authors' => 'Authors',
// ... other labels ...
];
}
}
The public property $authors will be loaded with data from field authors in the result of your SQL query. Then you can use it in grid as any other field.
The other option is to use yii\data\SqlDataProvider instead of yii\data\ActiveDataProvider.

How to merge filters from one search model to one findModel from a controller in Yii 2?

The question is confusing, but I'll explain.
I have this search query from AsistenciaSearch.php
public function search($params)
{
$query = Asistencia::find();
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
$query->joinWith('rutAlumno0');
$query->joinWith('idPlanificacion0');
// grid filtering conditions
$query->andFilterWhere([
'idAsistencia' => $this->idAsistencia,
//'idPlanificacion' => $this->idPlanificacion,
]);
$query->andFilterWhere(['like', 'asistencia', $this->asistencia])
->andFilterWhere(['like', 'rutAlumno', $this->rutAlumno])
//->andFilterWhere(['like', 'idPlanificacion', $this->idPlanificacion])
->andFilterWhere(['like', 'alumno.nombreAlumno', $this->nombreAlumno])
->andFilterWhere(['like', 'alumno.apellidoAlumno', $this->apellidoAlumno])
->andFilterWhere(['like', 'alumno.cursoAlumno', $this->cursoAlumno])
->andFilterWhere(['like', 'alumno.establecimientoAlumno', Yii::$app->user->identity->escuelaProfesor]);
return $dataProvider;
}
And this a controller function using the search query in PlanificacionController.php:
public function actionVerasistencia($id)
{
$searchModel = new AsistenciaSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('verasistencia', [
'model' => $this->findModel($id), //findModel from Planificacion
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
Both Asistencia and Planificacion are related by using a primary key in Planificacion named idPlanificacion and a foreign key from that model in Asistencia using the same name.
The question is, I need to make merge with another filter, where the $id from findModel($id) is like the $idPlanificacion from the search query, like this:
public function actionVerasistencia($id)
{
$searchModel = new AsistenciaSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('verasistencia', [
'model' => $this->findModel($id),
'searchModel' => $searchModel,
'dataProvider' => $dataProvider->andFilterWhere('like',$id,$this->idPlanificacion),
]);
}
But I got this error:
Getting unknown property: frontend\controllers\PlanificacionController::idPlanificacion
Any solution, please?
$this inside the controller is related to the controller itself
but your are referring to idPlanificacion alias you are referring to a model attribute
could be you want retrive the value by the model eg:
$model = $this->findModel($id)
so could be
public function actionVerasistencia($id)
{
$searchModel = new AsistenciaSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$model = $this->findModel($id);
return $this->render('verasistencia', [
'model' =>$model,
'searchModel' => $searchModel,
'dataProvider' => $dataProvider->andFilterWhere('like',$id,$model->idPlanificacion),
]);
}

Yii2 filter Sum data in GridView

I'm trying display and filter data which I got via SQL SUM operator.
I have 2 table employee and department. Table employee contains department_id filed and salary filed. I need display all department and total SUM salary for every department.
I followed this guide, but GridView does not display any data.
Here is action:
public function actionIndex()
{
$searchModel = new DepartmentFrontendSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index',
[
'dataProvider' => $dataProvider,
'searchModel' => $searchModel,
]
);
}
Model:
class DepartmentFrontendSearch extends DepartmentFrontend
public $employee_count;
public $salary;
public function rules() {
return [
[['employee_count','salary','name'], 'safe']
];
}
public function search($params) {
$query = DepartmentFrontend::find();
$subQuery = Employee::find()
->select('department_id, SUM(salary) as salary_amount')
->groupBy('department_id');
$query->leftJoin(['salarySum' => $subQuery], 'salarySum.department_id = id');
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$dataProvider->setSort([
'attributes' => [
'name',
'salary'
]
]);
$this->load($params);
if (!$this->validate()) {
return $dataProvider;
}
$query->andFilterWhere(['like', 'name', $this->name]);
$query->andWhere(['salarySum.salary_amount' => $this->salary]);
return $dataProvider;
}
GRID:
echo GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'salary_amount',
'employee_count',
'name',
],
]);
So, can anybody tell me what I did wrong?
If You need a filter for the alias salary_amount you should add a specific var for this (do the fact salary_amount is an alias for sum(salary) the var $salary is not useful)
public $employee_count;
public $salary;
public $salary_amount;
otherwise use salary as alias too
the in your filter you are using
$query->andWhere(['salarySum.salary_amount' => $this->salary]);
But salary_amount is the result of an aggregation so you should use having(SUM(salary) = $this->salary_amount)
$query->having('SUM(salary) = ' . $this->salary_amount);

How to implement single search form in yii2

Yii2 has a searchModel to search each field in the GridView. Is it possible to just create a single search field outside the GridView where the user can input keywords and by the time Search button is hit, the results will display in the GridView based on the keywords entered.
CONTROLLER
public function actionIndex()
{
$session = Yii::$app->session;
//$searchModel = new PayslipTemplateSearch();
$PayslipEmailConfig = PayslipEmailConfig::find()->where(['company_id'=> new \MongoId($session['company_id'])])->one();
$payslipTemplateA = PayslipTemplate::find()->where(['company_id' => new \MongoId($session['company_id'])])->andwhere(['template_name' => 'A'])->one();
$payslipTemplateB = PayslipTemplate::find()->where(['company_id' => new \MongoId($session['company_id'])])->andwhere(['template_name' => 'B'])->one();
$pTemplateModel = PayslipTemplate::find()->where(['company_id' => new \MongoId($session['company_id'])])->all();
$user = User::find()->where(['_id' => new \MongoId($session['user_id'])])->one();
$module_access = explode(',', $user->module_access);
//$dataProvider = User::find()->where(['user_type' => 'BizStaff'])->andwhere(['parent' => new \MongoId($session['company_owner'])])->all();
$searchModel = new UserSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'PayslipEmailConfig' => $PayslipEmailConfig,
'dataProvider' => $dataProvider,
'payslipTemplateA' => $payslipTemplateA,
'payslipTemplateB' => $payslipTemplateB,
'searchModel' => $searchModel,
]);
}
public function actionSearchresults($keyword)
{
$session = Yii::$app->session;
if ( $keyword == '') {
return $this->redirect(\Yii::$app->request->getReferrer());
} else {
$user = User::find()->where( [ '_id' => new \MongoId($id) ] )->one();
$searchModel = new PayslipTemplateSearch();
$payslipTemplateA = PayslipTemplate::find()->where(['company_id' => new \MongoId($session['company_id'])])->andwhere(['template_name' => 'A'])->one();
$payslipTemplateB = PayslipTemplate::find()->where(['company_id' => new \MongoId($session['company_id'])])->andwhere(['template_name' => 'B'])->one();
return $this->render('searchresults', [
'searchModel' => $searchModel,
'user' => $user,
'payslipTemplateA' => $payslipTemplateA,
'payslipTemplateB' => $payslipTemplateB,
]);
}
}
I asked a question connected to this problem here: Main Search Form in Yii2
It didn't due to some complications in Kartik's Select2 search dropdown widget. Now I switched temporarily to a simple Yii2 search field.
VIEW
echo $form->field($model, '_id')->textInput(array('placeholder' => 'search'))->label(false);
MODEL
<?php
namespace app\models;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\User;
/**
* UserSearch represents the model behind the search form about `app\models\User`.
*/
class UserSearch extends User
{
/**
* #inheritdoc
*/
public function rules()
{
return [
[[/*'_id',*/ 'creator_id'], 'integer'],
[['fname', 'lname', 'email', 'username', 'user_type'], 'safe'],
];
}
/**
* #inheritdoc
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* #param array $params
*
* #return ActiveDataProvider
*/
public function search($params)
{
$session = Yii::$app->session;
$query = User::find();
$query->where(['user_type' => 'BizStaff'])->andwhere(['parent' => new \MongoId($session['company_owner'])]);
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
$query->andFilterWhere([
'_id' => $this->_id,
'creator_id' => $this->creator_id,
]);
$query->andFilterWhere(['like', 'fname', $this->fname])
->andFilterWhere(['like', 'lname', $this->lname])
->andFilterWhere(['like', 'email', $this->email])
->andFilterWhere(['like', 'username', $this->username])
->andFilterWhere(['like', 'user_type', $this->user_type]);
return $dataProvider;
}
}
Do you have any idea on how to I implement a single search? It's kind of a smarter search since it can search everything in the database table based on keywords inputted.
EDIT
When I search a keyword, say for example 'hello', it then gives me this url and error after hitting enter key:
URL:
http://localhost/iaoy-dev/web/index.php?r=payslip-template%2Fsearchresults&PayslipTemplateSearch%5B_id%5D=hello
Error message:
Bad Request (#400) Missing required parameters: id
Help.
I had the same problem and my solution is:
Model
Extend your UserSearch Model with a search parameter
class UserSearch extends User
{
public $searchstring;
...
Enable passing the variable
public function rules()
{
return [
...
[['searchstring'], 'safe'],
];
}
Change your search-Method (beware: the searchfields are combined with orFilterWhere, depends on your needs).
$query->orFilterWhere(['like', 'fname', $this->searchstring])
->orFilterWhere(['like', 'lname', $this->searchstring])
->orFilterWhere(['like', 'email', $this->searchstring])
->orFilterWhere(['like', 'username', $this->searchstring])
->orFilterWhere(['like', 'user_type', $this->searchstring]);
View (could be also layout)
Extend your form with a search-input. You can style the input-field by yourself, this is just an example:
<?php
/* #var $searchModel app\models\UserSearch */
echo $form->field($searchModel, 'searchstring', [
'template' => '<div class="input-group">{input}<span class="input-group-btn">' .
Html::submitButton('GO', ['class' => 'btn btn-default']) .
'</span></div>',
])->textInput(['placeholder' => 'Search']);
?>
Controller
Also check for the value of $searchstring after posting the form.
public function actionIndex()
{
...
$searchModel = new UserSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
...
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
That's it.

Yii 2.0 Getting data from model without widget

Can anyone give me sample of how to retrieve data from model without having to use Widget ? Because need to get data per table column and put them inside my own view (not using widget)
Controller :
public function actionIndex() {
$searchModel = new B2CProductsSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
View :
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
'sku',
'name',
'short_description',
'long_description',
'thumb_img:ntext',
'large_img:ntext',
'url_content:ntext',
'contact_info',
'status',
'currency',
'price',
'dimension',
'weight',
// 'created',
// 'modified',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
The widget above iterate through the element inside the predefined gridview,
but what I want to do instead is something like :
foreach($data as $ab) {
echo $ab->id;
}
You can do it this way:
/* assuming $data is an ActiveDataProvider object */
$models = $data->getModels();
foreach($models as $model) { ... }
see more here
If you are using an ActiveDataProvider:
Controller:
public function actionMyAction()
{
$dataProvider = new ActiveDataProvider([
'query' => MyModel::find(),
]);
return $this->render('my-results-page', [
'dataProvider' => $dataProvider,
]);
}
View:
<?php
foreach ($dataProvider->models as $model){
echo $model->myProperty;
}
?>
If you are using a query, such as this:
$query = (new \yii\db\Query())
->select('this, that')
->from('over_there');
$command = $query->createCommand();
$rows = $command->queryAll();
Then you can iterate over the result like this(assuming you passed it to the view in a variable called $dataProvider):
foreach($dataProvider as $data)
{
$data['myProperty'];
}

Categories