Yii2 app\model\Db6TrxImportData not found - php

I am new with Yii2 and i am having this error.
PHP Fatal Error – yii\base\ErrorException
Class 'app\models\Db6TrxImportData' not found
I have searched somewhere that you need to add
use app\models\Db6TrxImportData;
i have already added this to my controller but still get the same error. I am noob in yii2.. please help. This is my code.
<?php
namespace app\modules\dtv\controllers;
use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use app\components\helpers\User;
use app\components\helpers\Data;
use app\models\Db6TrxImportData;
class ManageController extends \yii\web\Controller
{
// Properties
public $layout = '/registerLayout';
public $breadcrumbItems;
public $breadcrumbHomeItems;
public $route_nav = 'dtv/manage/list';
public $viewPath = 'app/modules/dtv/views';
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['list', 'delete'],
'rules' => [
[
'allow' => true,
'actions' => ['list', 'delete'],
'roles' => ['#'],
'matchCallback' => function ($rule, $action) {
$identity = User::initUser();
$feature = Yii::$app->params['Modules']['News Video Management'];
return User::hasAccess($identity, $feature);
},
],
],
'denyCallback' => function ($rule, $action) {
if (Yii::$app->user->isGuest) {
$this->goHome();
} else {
$this->redirect(['/dashboard']);
}
}
],
];
}
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
];
}
public function init()
{
if (Yii::$app->user->isGuest) {
$label = Yii::t('app', 'Login');
$url = '/login';
} else {
$label = Yii::t('app', 'Dashboard');
$url = '/dashboard';
}
$this->breadcrumbHomeItems = [
'label' => $label,
'url' => $url,
'template' => '<li>{link}</li> ',
];
}
public function actionList()
{
// Initialize Layout
$this->breadcrumbItems = [
Yii::t('app', 'Xml acquisition article list')
];
$identity = User::initUser();
$ownerId = User::getOwnerId($identity);
$dtvMovieModel = new Db6TrxImportData();
$params = [ 'owner' => $ownerId,
'status' => 'active',
'application' => 'menumaker'
];
$dtvMovie = $dtvMovieModel->getRecords($params);
return $this->render('list', [
'dtvMovie' => $dtvMovie
]);
}
}
?>
This is my Model
<?php
namespace app\models;
use Yii;
use yii\db\Query;
use app\components\helpers\User;
use app\components\helpers\Data;
class Db6TrxImportData extends \yii\db\ActiveRecord
{
public static function tableName()
{
return '_dtvdb.trx_import_data';
}
public static function getDb()
{
return Yii::$app->get('dtvdb');
}
public function rules()
{
return [
[['article_id', 'ctrl_flg', 'image_flg', 'video_flg', 'del_flg', 'news_cat', 'news_cat_cd', 'copyright', 'copyright_cd', 'title', 'article_text', 'zapping_text'], 'required'],
[['cx_create_date', 'cx_update_date', 'publish_date_from', 'publish_date_to', 'import_date', 'create_time', 'up_time'], 'safe'],
[['status'], 'string'],
[['article_id'], 'string', 'max' => 12],
[['ctrl_flg', 'image_flg', 'video_flg', 'del_flg'], 'string', 'max' => 1],
[['news_cat', 'news_sub_cat', 'disptach_type', 'copyright', 'lang'], 'string', 'max' => 100],
[['news_cat_cd', 'dispatch_cd', 'copyright_cd', 'lang_cd', 'article_status', 'zapping_status'], 'string', 'max' => 2],
[['news_sub_cat_cd'], 'string', 'max' => 4],
[['title', 'zapping_text'], 'string', 'max' => 300],
[['article_text'], 'string', 'max' => 1000],
[['comment'], 'string', 'max' => 500]
];
}
public function attributeLabels()
{
return [
'id' => 'ID',
'article_id' => 'Article ID',
'cx_create_date' => 'Cx Create Date',
'cx_update_date' => 'Cx Update Date',
'ctrl_flg' => 'Ctrl Flg',
'image_flg' => 'Image Flg',
'video_flg' => 'Video Flg',
'del_flg' => 'Del Flg',
'news_cat' => 'News Cat',
'news_cat_cd' => 'News Cat Cd',
'news_sub_cat' => 'News Sub Cat',
'news_sub_cat_cd' => 'News Sub Cat Cd',
'dispatch_cd' => 'Dispatch Cd',
'disptach_type' => 'Disptach Type',
'copyright' => 'Copyright',
'copyright_cd' => 'Copyright Cd',
'lang_cd' => 'Lang Cd',
'lang' => 'Lang',
'publish_date_from' => 'Publish Date From',
'publish_date_to' => 'Publish Date To',
'title' => 'Title',
'article_text' => 'Article Text',
'comment' => 'Comment',
'zapping_text' => 'Zapping Text',
'import_date' => 'Import Date',
'article_status' => 'Article Status',
'zapping_status' => 'Zapping Status',
'status' => 'Status',
'create_time' => 'Create Time',
'up_time' => 'Up Time',
];
}
public static function findByAttribute($arr)
{
foreach ($arr as $arrKey => $arrValue) {
$record = self::find()->where($arrKey.'=:'.$arrKey,[':'.$arrKey => $arrValue])->one();
}
return $record;
}
}

Related

GridView filter model in Yii2

I have a gridview with a dataprovider which has joined two tables as query:
$applicationDataProvider = new ActiveDataProvider([
'query' => Application::find()->with('applicantInfo')
->where(['job_posting_id' => $jobPosting->id,
'deleted_flag' => 0])->orderBy('created_at desc'),
'pagination' => [
'pageSize' => 5
]
]);
and here is my GridView:
<?= GridView::widget([
'dataProvider' => $applicationDataProvider,
'filterModel'=>$searchModel,
'columns' => [
'id',
[
'class' => yii\grid\DataColumn::className(),
'headerOptions' => ['style' => 'color:#337ab7'],
'header' => 'სახელი',
'label'=>'name',
'value' => function ($data) {
return $data->applicantInfo->first_name . ' ' . $data->applicantInfo->last_name;
}
],
'applicantInfo.email',
'applicantInfo.phone',
'created_at:date',
[
'class' => 'yii\grid\ActionColumn',
'headerOptions' => ['style' => 'color:#337ab7'],
'template' => '{view}',
'buttons' => [
'view' => function ($url, $model) {
return Html::a('<span class="glyphicon glyphicon-eye-open"></span>', $url, [
'title' => Yii::t('app', 'გახსნა'),
]);
}
],
'urlCreator' => function ($action, $model, $key, $index) {
if ($action === 'view') {
$url = '/app-info/?id=' . $model->id;
return $url;
}
}
...
in a search model I have email field only because I want to gridview has just only email search field.
class ApplicationSearch extends Application
{
public function rules()
{
return [
[['email'], 'safe'],
];
}
but here is not drawn search field for email, how can I fix it?
You need to add email attribute to ApplicationSearch to store value from filter:
class ApplicationSearch extends Application {
public $email;
public function rules() {
return [
[['email'], 'safe'],
];
}
}
Use this attribute for filtering:
$applicationDataProvider = new ActiveDataProvider([
'query' => Application::find()->with('applicantInfo')
->where(['job_posting_id' => $jobPosting->id, 'deleted_flag' => 0])
->andFilterWhere(['like', 'applicantInfo.email', $this->email])
->orderBy('created_at desc'),
'pagination' => [
'pageSize' => 5
]
]);
And use value from relation in grid:
// ...
[
'attribute' => 'email',
'value' => function ($data) {
return $data->applicantInfo->email;
},
],
'applicantInfo.phone',
// ...

Yii2: Attribute (CLIENT_ID) is invalid

I'm trying to save a field from another table in update action. Here is my update action.
public function actionUpdateResumo($id)
{
$model = $this->findModel($id);
$model->situacao = $model->nginAgentDetail->situacao;
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$nginAgentDet = NginAgentDetail::find()
->where(['CLIENT_ID'=>$id])->one();
$nginAgentDet->situacao = Yii::$app->request->post()['EtuLoja']['situacao'];
if ($model->save() && $nginAgentDet->save()) {
return $this->redirect(['view', 'id' => $model->ID]);
} else {
var_dump($nginAgentDet->getErrors());die;
}
} else {
return $this->render('update-resumo', [
'model' => $model,
]);
}
}
When i click update it displays the message:
Client ID is invalid.
Client ID is a field from the other table (NginAgentDetail)
In my model i have this relation:
public function getNginAgentDetail()
{
return $this->hasOne(NginAgentDetail::className(),['CLIENT_ID' => 'ID']);
}
and in the other table i have this relation:
public function getEtuLojas()
{
return $this->hasMany(EtuLoja::className(), ['ID' => 'CLIENT_ID']);
}
NginAgentDetail model:
class NginAgentDetail extends \yii\db\ActiveRecord
{
public static function tableName()
{
return 'ngin_agent_detail';
}
public function rules()
{
return [
[['situacao'], 'string'],
// [['valMoeda'], 'number'],
[['CLIENT_ID'], 'integer'],
[['OPERATION_DATE', 'CATEGORY', 'MOV_TYPE', 'VALUE', 'COMMISSION', 'AFTER_BALANCE', 'ORIGIN_DESTINY', 'VALUES', 'USER'], 'string', 'max' => 100],
[['CLIENT_ID'], 'exist', 'skipOnError' => true, 'targetClass' => MasterLoja::className(), 'targetAttribute' => ['CLIENT_ID' => 'id']],
];
}
public function attributeLabels()
{
return [
'id_pk' => 'Id Pk',
'OPERATION_DATE' => 'Operation Date',
'CLIENT_ID' => 'Client ID',
'CATEGORY' => 'Category',
'MOV_TYPE' => 'Mov Type',
'VALUE' => 'Value',
'COMMISSION' => 'Commission',
'AFTER_BALANCE' => 'After Balance',
'ORIGIN_DESTINY' => 'Origin Destiny',
'VALUES' => 'Values',
'USER' => 'User',
'situacao' => 'Status',
];
}
public function getEtuLojas()
{
return $this->hasMany(EtuLoja::className(), ['ID' => 'CLIENT_ID']);
}
public function getMasterLoja()
{
return $this->hasMany(MasterLoja::className(), ['id' => 'ORIGIN_DESTINY']);
}
}
FindModel function:
protected function findModel($id)
{
if (($model = EtuLoja::findOne($id)) !== null) {
return $model;
}
throw new NotFoundHttpException('The requested page does not exist.');
}
EDIT
I found what was causing te invalid Client ID message. It was this validation rule in NginAgentDetail model:
[['CLIENT_ID'], 'exist', 'skipOnError' => true, 'targetClass' => MasterLoja::className(), 'targetAttribute' => ['CLIENT_ID' => 'id']],
The problem now is that it appears to be saving to the database but when i return to the gridview the attribute situacao stays the same, i mean it doesn't update.

why search return same rows in gridview yii2 kartik

I am facing a problem with filtering. I have created a grid view that contain a list of data from related tables.
what I'm facing is :
How can I sort data ( I can only sort the data received from the parent table)?
why the search always return same value whatever I'm writing in filters even with Pjax reload but no data change ?
this my view :
<div class="row">
<div class="col-lg-12">
<?php
$ItemSupMod = $ItemSupMod;
$gridColumns = [
['class' => 'yii\grid\SerialColumn'],
// 'ItemName',
[
'attribute' => 'CategoryName',
'label' => 'Item Name',
'filter' => true,
'enableSorting' => true,
// 'filterType' => GridView::FILTER_TYPEAHEAD,
'value' => function ($model, $key, $index, $widget) {
return "<span>" . ($model->iTEM != null && sizeof($model->iTEM) > 0 && $model->iTEM->pRODUCT != null && sizeof($model->iTEM->pRODUCT) > 0 && $model->iTEM->pRODUCT->sUBCATEGORY != null && sizeof($model->iTEM->pRODUCT->sUBCATEGORY) > 0 && $model->iTEM->pRODUCT->sUBCATEGORY->cATEGORYOFITEM != null && sizeof($model->iTEM->pRODUCT->sUBCATEGORY->cATEGORYOFITEM) > 0 && $model->iTEM->pRODUCT->sUBCATEGORY->cATEGORYOFITEM->categoryOfItemsTrans != null && sizeof($model->iTEM->pRODUCT->sUBCATEGORY->cATEGORYOFITEM->categoryOfItemsTrans) > 0 ? $model->iTEM->pRODUCT->sUBCATEGORY->cATEGORYOFITEM->categoryOfItemsTrans[0]->CATEGORY_OF_ITEM_TRANS : "" ) . "</span> ";
},
// 'vAlign' => 'middle',
'format' => 'raw',
'width' => '150px',
// 'noWrap' => true,
'enableSorting' => true,
],
[
'attribute' => 'SubCategoryName',
'label' => 'Item Name',
'filter' => true,
'enableSorting' => true,
// 'filterType' => GridView::FILTER_TYPEAHEAD,
'value' => function ($model, $key, $index, $widget) {
return "<span>" . ($model->iTEM != null && sizeof($model->iTEM) > 0 && $model->iTEM->pRODUCT != null && sizeof($model->iTEM->pRODUCT) > 0 && $model->iTEM->pRODUCT->sUBCATEGORY != null && sizeof($model->iTEM->pRODUCT->sUBCATEGORY) && $model->iTEM->pRODUCT->sUBCATEGORY->subCategoriesTrans != null && sizeof($model->iTEM->pRODUCT->sUBCATEGORY->subCategoriesTrans) > 0 ? $model->iTEM->pRODUCT->sUBCATEGORY->subCategoriesTrans[0]->SUB_CATEGORY_NAME : "" ) . "</span> ";
},
// 'vAlign' => 'middle',
'format' => 'raw',
'width' => '150px',
// 'noWrap' => true,
'enableSorting' => true,
],
[
'attribute' => 'ProductName',
'label' => 'Item Name',
'filter' => true,
'enableSorting' => true,
// 'filterType' => GridView::FILTER_TYPEAHEAD,
'value' => function ($model) {
return "<span>" . ($model->iTEM != null && sizeof($model->iTEM) > 0 && $model->iTEM->pRODUCT != null && sizeof($model->iTEM->pRODUCT) > 0 && $model->iTEM->pRODUCT->productsTrans != null && sizeof($model->iTEM->pRODUCT->productsTrans) > 0 ? $model->iTEM->pRODUCT->productsTrans[0]->PRODUCT_NAME : "" ) . "</span> ";
},
// 'vAlign' => 'middle',
'format' => 'raw',
'width' => '150px',
// 'noWrap' => true,
'enableSorting' => true,
],
[
'attribute' => 'ItemName',
// 'sortParam' => 'post-sort',
// 'defaultOrder' => ['ItemName' => SORT_ASC],
'label' => 'Item Name',
'filter' => true,
'enableSorting' => true,
// 'filterType' => GridView::FILTER_TYPEAHEAD,
'value' => function ($model) {
return "<span>" . ($model->iTEM != null && sizeof($model->iTEM) > 0 && $model->iTEM->itemsTrans != null && sizeof($model->iTEM->itemsTrans) > 0 ? $model->iTEM->itemsTrans[0]->ITEM_NAME : "" ) . "</span> ";
},
// 'vAlign' => 'middle',
'format' => 'raw',
'width' => '150px',
// 'noWrap' => true,
'enableSorting' => true,
],
'PRICE',
[
'class' => 'kartik\grid\ExpandRowColumn',
'width' => '50px',
'value' => function ($model, $key, $index, $column) {
return GridView::ROW_COLLAPSED;
},
'detail' => function ($model, $key, $index, $column) {
$actionSub = SupplierController::actionSub($model->ITEM_SUPPLIER_ID,$index);
return Yii::$app->controller->renderPartial('supitems', $actionSub);
},
'headerOptions' => ['class' => 'kartik-sheet-style'],
'expandOneOnly' => true
],
];
echo GridView::widget([
'id' => 'kv-grid-demo',
'dataProvider' => $dataItemSupplier,
'filterModel' => $searchModel,
'resizableColumns' =>true,
'formatter' => ['class' => 'yii\i18n\Formatter', 'nullDisplay' => ''],
'columns' => $gridColumns,
'containerOptions' => ['style' => 'overflow: auto'], // only set when $responsive = false
'headerRowOptions' => ['class' => 'kartik-sheet-style'],
'filterRowOptions' => ['class' => 'kartik-sheet-style'],
'pjax' => true, // pjax is set to always true for this demo
'bordered' => true,
'striped' => true,
'condensed' => true,
'responsive' => true,
'hover' => true,
'persistResize' => false,
]);
?>
</div>
</div>
this is my model that contain search :
class ItemsSupplieirs extends \yii\db\ActiveRecord
{
public $PRODUCT_ID;
public $CATEGORY_ID;
public $SUB_CATEGORY;
public $ItemName;
/**
* #inheritdoc
*/
public static function tableName()
{
return 'items_supplieirs';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['ItemName','PRICE'], 'safe'],
[['CURRENCY_ID','PRICE'], 'required'],
[['ITEM_ID', 'SUPPLIER_ID', 'CURRENCY_ID','PRICE','ITEM_SUPPLIER_ID'], 'integer'],
[['PRICE', 'COMMISSION'], 'string', 'max' => 45],
[['COMMISSION_FLAG'], 'string', 'max' => 1],
[['DISCOUNT'], 'string', 'max' => 2],
[['ITEM_ID'], 'exist', 'skipOnError' => true, 'targetClass' => Items::className(), 'targetAttribute' => ['ITEM_ID' => 'ITEM_ID']],
[['SUPPLIER_ID'], 'exist', 'skipOnError' => true, 'targetClass' => Suppliers::className(), 'targetAttribute' => ['SUPPLIER_ID' => 'SUPPLIER_ID']],
[['CURRENCY_ID'], 'exist', 'skipOnError' => true, 'targetClass' => Currencies::className(), 'targetAttribute' => ['CURRENCY_ID' => 'CURRENCY_ID']],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'ITEM_ID' => Yii::t('app', 'Item ID'),
'SUPPLIER_ID' => Yii::t('app', 'Supplier ID'),
'ITEM_SUPPLIER_ID' => Yii::t('app', 'Item Supplier ID'),
'PRICE' => Yii::t('app', 'Price'),
'CURRENCY_ID' => Yii::t('app', 'Currency ID'),
'COMMISSION' => Yii::t('app', 'Commission'),
'COMMISSION_FLAG' => Yii::t('app', 'Commission Flag'),
'DISCOUNT' => Yii::t('app', 'Discount'),
'PRODUCT_ID' => Yii::t('app', 'Products'),
'ItemName' =>Yii::t('app', 'Item Name'),
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getCriteriaValues()
{
return $this->hasMany(CriteriaValues::className(), ['ITEM_SUPPLIER_ID' => 'ITEM_SUPPLIER_ID']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getItemOptions()
{
return $this->hasMany(ItemOptions::className(), ['ITEM_SUPPLIER_ID' => 'ITEM_SUPPLIER_ID']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getItemRatingComments()
{
return $this->hasMany(ItemRatingComment::className(), ['ITEM_SUPPLIER_ID' => 'ITEM_SUPPLIER_ID']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getItemSupplierTranslations()
{
return $this->hasMany(ItemSupplierTranslation::className(), ['ITEM_SUPPLIER_ID' => 'ITEM_SUPPLIER_ID']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getItemsImgs()
{
return $this->hasMany(ItemsImgs::className(), ['ITEM_SUPPLIER_ID' => 'ITEM_SUPPLIER_ID']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getITEM()
{
return $this->hasOne(Items::className(), ['ITEM_ID' => 'ITEM_ID']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getSUPPLIER()
{
return $this->hasOne(Suppliers::className(), ['SUPPLIER_ID' => 'SUPPLIER_ID']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getCURRENCY()
{
return $this->hasOne(Currencies::className(), ['CURRENCY_ID' => 'CURRENCY_ID']);
}
/**
* #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)
{
$query = ItemsSupplieirs::find()
->joinWith('items','items_trans');
// add conditions that should always apply here
$query->where('PRICE LIKE '. $this->PRICE);
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort' => ['attributes' => ['ItemName']]
]);
$dataProvider->sort->attributes['ItemName'] = [
'asc' => ['ItemName' => SORT_ASC],
'desc' => ['ItemName' => SORT_DESC],
'label' => $this->getAttributeLabel('ItemName'),
];
$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;
// }
// grid filtering conditions
// $query->andFilterWhere([
// 'ITEM_ID' => $this->ITEM_ID,
// 'SUPPLIER_ID' => $this->SUPPLIER_ID,
// 'ITEM_SUPPLIER_ID' => $this->ITEM_SUPPLIER_ID,
// 'CURRENCY_ID' => $this->CURRENCY_ID,
// 'items_trans.LANGUAGE_ID' => '1',
// ]);
// ->andFilterWhere(['like', 'COMMISSION', $this->COMMISSION])
// ->andFilterWhere(['like', 'COMMISSION_FLAG', $this->COMMISSION_FLAG])
// ->andFilterWhere(['like', 'DISCOUNT', $this->DISCOUNT])
// ->andFilterWhere(['like', 'items_trans.ITEM_NAME', $this->PRICE]);
Yii::error("this->ItemName" .$this->ItemName);
// $query
// ->andFilterWhere(['like', 'DISCOUNT', $this->DISCOUNT]);
// 'items_trans.ITEM_NAME'=>$this->ItemName,
// $models = $dataProvider->getModels();
// if($models!=null && sizeof($models)>0){
// Yii::error("sizeof(models) : " .sizeof($models));
// }
return $dataProvider;
}
}
this what I send from controller :
$SearchItemsSupplieirs = new \app\models\ItemsSupplieirs;
$dataProvider = $SearchItemsSupplieirs->search(Yii::$app->request->getQueryParams('ItemsSupplieirs'));
return $this->render('listitems', [
'dataProvider' => $dataProvider,
'searchModel' => $SearchItemsSupplieirs,
]);
Ahmad:
The first thing I noticed is that in your search method you're not actually querying of any of the incoming search parameters. That's why you are getting the same results no matter what you do in the grid.
You are loading the search arguments via the $this->load($params) but you're not adding to your query statement before creating the ActiveDataProvider.
Here is an example of how the search method should be constructed:
public function search($params)
{
$query = Client::find()
->joinWith(['venues','events'])
->orderBy('name');
$this->load($params);
if(strlen($this->status) > 0){
if($this->status <> -1)
$query->andWhere(['status' => $this->status]);
}
if(!empty($this->name)){
$query->andFilterWhere(['like','client.name',$this->name])
->orFilterWhere(['like','venue.name',$this->name]);
}
if(!empty($this->status)){
if($this->status != -1){
$query->andWhere(['status' => $this->status]);
}
}
if(!empty($this->address1)){
$query->andFilterWhere(['like','address1',$this->address1])
->orFilterWhere(['like','address2',$this->address1])
->orFilterWhere(['like','city',$this->address1])
->orFilterWhere(['like','state',$this->address1])
->orFilterWhere(['like','zip',$this->address1]);
}
if(!empty($this->venues)){
$query->andWhere(['like','venue.name',$this->venues]);
}
if(!empty($this->staffing_manager)){
$query->andWhere(['venue.staffing_manager_id' => $this->staffing_manager]);
}
if(!empty($this->sales_rep)){
$query->andWhere(['venue.sales_rep_id' => $this->sales_rep]);
}
$dataProvider = new ActiveDataProvider([
'query' => $query,
'pagination' => false,
]);
$dataProvider->sort->attributes['name'] = [
'asc' => ['name' => SORT_ASC],
'desc' => ['name' => SORT_DESC]
];
$dataProvider->sort->attributes['last_event'] = [
'asc' => ['date' => SORT_ASC],
'desc' => ['date' => SORT_DESC]
];
return $dataProvider;
}

Yii2 ActiveDataProvider sort using count in relational

Yii2 ActiveDataProvider sort using count in relational ?
I've 3 tables, bellow :
And I displaying data from table inventory_device_type, here is the code :
Controller :
<?php
namespace app\controllers\inventory;
use Yii;
use yii\base\Action;
use app\models\tables\InventoryDeviceType;
class DeviceInventory extends Action
{
public function run()
{
$model = new InventoryDeviceType();
$dataProvider = $model->search(Yii::$app->request->post());
return $this->controller->render('device-inventory',[
'dataProvider' => $dataProvider,
]);
}
}
Model :
<?php
namespace app\models\tables;
use yii\db\ActiveRecord;
use yii\data\ActiveDataProvider;
use yii\web\NotFoundHttpException;
class InventoryDeviceType extends ActiveRecord
{
public static function tableName()
{
return 'inventory_device_type';
}
public function rules()
{
return [
[['name','id_device_vendor'],'required'],
['name','unique']
];
}
public function attributeLabels()
{
return [
'id_device_vendor' => 'Device Vendor',
];
}
/** queries **/
public function findData($id)
{
if(($data = self::findOne($id)) == null){
throw new NotFoundHttpException;
}else{
return $data;
}
}
public function getNormal()
{
return $this->getList()->where(['inventory_device_list.device_condition' => 'normal'])->count();
}
public function getBroken()
{
return $this->getList()->where(['inventory_device_list.device_condition' => 'broken'])->count();
}
public function getSold()
{
return $this->getList()->where(['inventory_device_list.device_condition' => 'sold'])->count();
}
public function getTotal()
{
return $this->getList()->where(['!=','inventory_device_list.device_condition',''])->count();
}
public static function getVendorList($sort=[])
{
return InventoryDeviceVendor::find()->orderBy($sort)->all();
}
public function search($params, $spesific=[],$sort=[])
{
$query = self::find();
$query->where($spesific);
$query->joinWith(['list']);
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort' => ['defaultOrder' => $sort]
]);
$dataProvider->sort->attributes['vendor_name'] = [
'asc' => ['inventory_device_vendor.name' => SORT_ASC],
'desc' => ['inventory_device_vendor.name' => SORT_DESC],
];
/** sort on page device-inventory **/
$dataProvider->sort->attributes['device_vendor'] = [
'asc' => ['inventory_device_vendor.name' => SORT_ASC],
'desc' => ['inventory_device_vendor.name' => SORT_DESC],
];
/** sort on page device-inventory end **/
return $dataProvider;
}
/** queries end **/
/** relation **/
public function getListLeft()
{
return InventoryDeviceList::find();
}
public function getList()
{
return $this->hasMany(InventoryDeviceList::className(),['id_device_type' => 'id']);
}
public function getVendorLeft()
{
return InventoryDeviceVendor::find();
}
public function getVendor()
{
return $this->hasOne(InventoryDeviceVendor::className(),['id' => 'id_device_vendor']);
}
/** relation end **/
}
and here is the view :
<?=
GridView::widget([
'dataProvider' => $dataProvider,
'layout' => '<div class="table-responsive">{items}</div> {summary} {pager}',
'columns' => [
[
'class' => 'yii\grid\SerialColumn',
'headerOptions' => ['width' => 50]
],
'name',
[
'attribute' => 'device_vendor',
'class' => 'yii\grid\DataColumn',
'value' => function($data){
return $data->vendor->name;
}
],
[
'attribute' => 'normal',
'class' => 'yii\grid\DataColumn',
'format' => 'html',
'value' => function($data){
return Html::a($data->getNormal(),'#',['class' => 'label label-success']);
},
],
[
'attribute' => 'sold',
'class' => 'yii\grid\DataColumn',
'format' => 'html',
'value' => function($data){
return Html::a($data->getSold(),'#',['class' => 'label label-warning']);
},
],
[
'attribute' => 'broken',
'class' => 'yii\grid\DataColumn',
'format' => 'html',
'value' => function($data){
return Html::a($data->getBroken(),'#',['class' => 'label label-danger']);
},
],
[
'attribute' => 'Total',
'class' => 'yii\grid\DataColumn',
'format' => 'html',
'value' => function($data){
return Html::a($data->getTotal(),'#',['class' => 'label label-primary']);
},
],
],
]);
?>
and how to sort it, like normal, broken, and, sold ?
here is : the result view :
the header normal, sold, broke and all not sortable, i can sort by relation if not using count like this code (like Device Vendor):
$dataProvider->sort->attributes['device_vendor'] = [
'asc' => ['inventory_device_vendor.name' => SORT_ASC],
'desc' => ['inventory_device_vendor.name' => SORT_DESC],
];

YII2 SqlDataProvider doesn't work relation table value

This is my model Riders:
<?php
namespace backend\models;
use Yii;
class Riders extends \yii\db\ActiveRecord
{
public static function tableName()
{
return 'riders';
}
public function rules()
{
return [
[['cagories_category_id', 'rider_firstname', 'rider_no_tlpn', 'rider_ucinumber', 'countries_id', 'rider_province', 'rider_city', 'rider_dateofbirth', 'rider_gender'], 'required'],
[['user_id', 'countries_id'], 'integer'],
[['rider_dateofbirth', 'cagories_category_id'], 'safe'],
[['rider_gender', 'rider_status'], 'string'],
[['rider_firstname', 'rider_lastname', 'rider_nickname', 'rider_province', 'rider_city'], 'string', 'max' => 45],
[['rider_email', 'rider_sponsor', 'rider_birthcertificate_url', 'rider_parental_consent_url'], 'string', 'max' => 100],
[['rider_no_tlpn'], 'string', 'max' => 15],
[['rider_ucinumber'], 'string', 'max' => 11]
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'rider_id' => 'rider_id',
'cagories_category_id' => 'Category Name',
'user_id' => 'User Team',
'rider_firstname' => 'Rider Firstname',
'rider_lastname' => 'Rider Lastname',
'rider_nickname' => 'Rider Nickname',
'rider_email' => 'Rider Email',
'rider_no_tlpn' => 'Rider No Tlpn',
'rider_ucinumber' => 'Rider Ucinumber',
'countries_id' => 'Country Name',
'rider_province' => 'Rider Province',
'rider_city' => 'Rider City',
'rider_sponsor' => 'Rider Sponsor',
'rider_dateofbirth' => 'Rider Dateofbirth',
'rider_gender' => 'Rider Gender',
'rider_birthcertificate_url' => 'Rider Birthcertificate Url',
'rider_parental_consent_url' => 'Rider Parental Consent Url',
'rider_status' => 'Rider Status',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getRegistrations()
{
return $this->hasMany(Registrations::className(), ['riders_rider_id' => 'rider_id']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getCagoriesCategory()
{
return $this->hasOne(Categories::className(), ['category_id' => 'cagories_category_id']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getUser()
{
return $this->hasOne(User::className(), ['id' => 'user_id']) -> from(user::tableName() . 'ud');
}
/**
* #return \yii\db\ActiveQuery
*/
public function getUserDesc()
{
return $this->hasOne(UserDesc::className(), ['desc_id' => 'user_id']) -> from(['ud' => userDesc::tableName()]);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getCountries()
{
return $this->hasOne(Countries::className(), ['id' => 'countries_id']);
}
}
This my Controller actionIndex:
$searchModel = new RidersSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$totalCount = Yii::$app->db->createCommand('SELECT COUNT(*) FROM riders WHERE user_id = :user_id',
[':user_id' => Yii::$app->user->identity->id])->queryScalar();
$dataProvider = new SqlDataProvider([
'sql' => 'SELECT * FROM riders WHERE user_id = :user_id',
'params' => [':user_id' => Yii::$app->user->identity->id],
'totalCount' => $totalCount,
'key' => 'rider_id',
'pagination' => [
'pageSize' => 10,
],
'sort' => [
'attributes' => [
'cagories_category_id',
'rider_id',
'rider_firstname',
'rider_email:email',
'rider_no_tlpn',
]
]
]);
$models = $dataProvider->getModels();
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
This is my view index:
<?= GridView::widget([
'dataProvider' => $dataProvider,
// 'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
[
'label' => 'Category Name',
'attribute'=>'cagories_category_id',
'value' => 'cagoriesCategory.category_name', <---Can't work again
],
[
'label' => 'BIB',
'attribute'=>'rider_id',
],
'rider_firstname',
'rider_email:email',
'rider_no_tlpn',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
Before I use sqldataprovider, it can call from model function have relation, after use sqldataprovider can't work. How to get relation table value???
then before use it, i can to merge rider_firstname and rider_lastname with return $model->rider_firstname . " " . rider_lastname; after use sqldataprovider can't work too??
SqlDataProvider returns data as an array so You can't able to access related object with $dataProvider->models()
either you have to use ActiveDataProvider or change your Sql of SqlDataProvider with join condition
sql='sql' => 'SELECT * FROM riders inner join '. Categories::tableName() .' as c on c.category_id=riders.cagories_category_id WHERE user_id = :user_id'

Categories