YII2 SqlDataProvider doesn't work relation table value - php

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'

Related

Yii2 | GridView table, communication between models does not work

The connection between the modules does not work, and because of this, the data in the table is not displayed. I can not understand why
Code in the controller
public function actionIndex()
{
$searchModel = new SuggestedNewsSearch();
$dataProvider = $searchModel->getAllNews(Yii::$app->request->queryParams);
return $this->render('index', [
'dataProvider' => $dataProvider,
'searchModel' => $searchModel
]);
}
code in suggestedNewsSearch.php
class SuggestedNewsSearch extends SuggestedNews
{
public function getAllNews($params)
{
$query = $this::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
if ($this->validate() AND !($this->load($params))) {
return $dataProvider;
}
if (!empty($this->getAttribute('title'))) {
$query->andFilterWhere(['LIKE', 'title', $this->getAttribute('title')]);
}
if (!empty($this->getAttribute('category'))) {
$query->andFilterWhere(['LIKE', 'category', $this->getAttribute('category')]);
}
if (!empty($this->getAttribute('status'))) {
switch (mb_strtolower($this->getAttribute('status'))) {
case $this::APPROVED:
$status = $this::ACTIVE_STATUS;
break;
case $this::NOT_APPROVED:
$status = $this::DEACTIVATED_STATUS;
break;
}
$query->andFilterWhere(['=', 'status', $status]);
}
return $dataProvider;
}
}
code on SuggestedNews.php
class SuggestedNews extends \yii\db\ActiveRecord
{
CONST ACTIVE_NEWS = 1;
CONST ACTIVE_STATUS = 1;
CONST DEACTIVATED_STATUS = 0;
CONST APPROVED = 'одобренно';
CONST NOT_APPROVED = 'не одобренно';
/**
* {#inheritdoc}
*/
public static function tableName()
{
return 'suggested_news';
}
/**
* {#inheritdoc}
*/
public function rules()
{
return [
[['news'], 'string'],
[['category', 'status'], 'integer'],
[['date'], 'safe'],
[['title', 'news_source'], 'string', 'max' => 255],
[['category'], 'exist', 'skipOnError' => true, 'targetClass' => Category::className(), 'targetAttribute' => ['category' => 'id']],
];
}
/**
* {#inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'title' => 'Title',
'news' => 'News',
'category' => 'Category',
'status' => 'Status',
'date' => 'Date',
'news_source' => 'News Source',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getCategory()
{
return $this->hasOne(Category::className(), ['id' => 'category']);
}
public function deleteNewsById($id)
{
$customer = $this::findOne($id);
if ($customer->delete()) return true;
else return false;
}
public function getNewsByIdWithCategory($id){
return $this::find()->where(['id' => $id])->with('category')->one();
}
}
code on Category.php
class Category extends \yii\db\ActiveRecord
{
CONST STATUS_CATEGORY_OFF = 0;
CONST STATUS_CATEGORY_ON = 1;
CONST NEW_CATEGORY_INTEGER = 01;
CONST NEW_CATEGORY_NAME = 'New Category';
/**
* {#inheritdoc}
*/
public static function tableName()
{
return 'category';
}
/**
* {#inheritdoc}
*/
public function rules()
{
return [
[['name', 'status_category'], 'required'],
[['status_category'], 'integer'],
[['name'], 'string', 'max' => 255],
];
}
/**
* {#inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'name' => 'Name',
'status_category' => 'Status Category',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getSuggestedNews()
{
return $this->hasMany(SuggestedNews::className(), ['category' => 'id']);
}
public function getAllCategories(){
return $this::find()->where(['status_category' => $this::STATUS_CATEGORY_ON])->all();
}
}
my index.php file(view)
<?php echo GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
[
'attribute' => 'title',
'format' => 'text',
'label' => 'title',
'filter' => true,
],
[
'attribute' => 'category.Category',
'format' => 'text',
'label' => 'Category',
],
[
'attribute' => 'status',
'filter' => true,
'value' => function($model) {
if($model->status == 1){
return $model::APPROVED;
}else{
return $model::NOT_APPROVED;
}
}
],
'date',
[
'class' => 'yii\grid\ActionColumn',
],
],
]);
?>
and on result i have this:result table
enter image description here
table category
table suggested_news
You field name and relation are the same, so You have to change Category relation name like this:
/**
* #return \yii\db\ActiveQuery
*/
public function getCategory1()
{
return $this->hasOne(Category::className(), ['id' => 'category']);
}
//Gridview
//...
[
'attribute' => 'category',
'label' => 'Category',
'value' => function($model){
return $model->category1->name;
}
],
//...
//or
//...
[
'attribute' => 'category1.name',
'format' => 'text',
'label' => 'Category',
],
Hope it will helps.

Yii2 Grid view syntax to access data from related model

for example I can retrieve the data in the view with this command:
<?=$model->instructor->manager->location['location_title']?>
I have a relation defined in Instructor model like:
/**
* #return mixed
*/
public function getUser()
{
return $this->hasOne(User::className(), ['id' => 'user_id']);
}
/**
* #return mixed
*/
public function getManager()
{
return $this->hasOne(Manager::className(), ['user_id' => 'manager_id']);
}
and in Manager Model relations are defined like this:
/**
* #return mixed
*/
public function getLocation()
{
return $this->hasOne(Location::className(), ['id' => 'location_id']);
}
/**
* #return mixed
*/
public function getUser()
{
return $this->hasOne(User::className(), ['id' => 'user_id']);
}
Now How I can retrieve the same data in grid-view as also add filter for the same.
Thanks.
update: Gridview Code
echo GridView::widget(
[
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
//'id',
'first_name',
'last_name',
// 'username',
// 'auth_key',
// 'password_hash',
// 'password_reset_token',
'email:email',
// 'phone',
//'user_role',
['attribute' => 'created_at', 'label' => 'Last Login', 'value' => function ($data) {
return $data->getLast($data);
},
'contentOptions' => ['style' => 'width:100px']
],
['attribute' => 'created_at', 'label' => 'Create Date', 'contentOptions' => ['style' => 'width:100px'], 'value' => function ($data) {return date('M d, Y', $data->created_at);}
],
// 'updated_at',
['attribute' => 'status', 'value' => function ($data) {
return $data->getStatus($data);
},
'filter' => ['10' => 'Active', '0' => 'Deactive'],
'contentOptions' => function ($data) {
$clr = $data->status == 10 ? 'green' : 'red';
return ['style' => 'width:80px;font-weight:bold;color:' . $clr];
}
]
]
]
);
Update-1
public function actionInstructor()
{
$cond = "user_role='instructor' ";
$searchModel = new UserSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams, $cond);
return $this->render(
'instructor', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider
]
);
}
update-2
public function getInstructor()
{
return $this->hasOne(Instructor::className(), ['user_id' => 'id']);
}
You can specify relations either as a string of relation names concatenated with . like below. Make sure you have the relations defined in the respective models the below is for the $dataProvider from the UserSearch model and your User Model should have the relation getInstructor() defined
[
'intructor.manager.location.location_title'
]
or
[
'label' => 'Manager Location',
'value' => function($model){
return $model->instructor->manager->location->location_title;
}
]
if I have the $dataProvider for the UserSearch model below should be the gridview code.
<?=GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
//'id',
'first_name',
'last_name',
[
'label'=>'Manager Location'
'attribute'=>'manager_id'.
'value'=>function($model){
return $model->instructor->manager->location->location_title;
}
]
// 'username',
// 'auth_key',
// 'password_hash',
// 'password_reset_token',
'email:email',
// 'phone',
//'user_role',
['attribute' => 'created_at', 'label' => 'Last Login', 'value' => function ($data) {
return $data->getLast($data);
},
'contentOptions' => ['style' => 'width:100px'],
],
['attribute' => 'created_at', 'label' => 'Create Date', 'contentOptions' => ['style' => 'width:100px'], 'value' => function ($data) {return date('M d, Y', $data->created_at);}],
// 'updated_at',
['attribute' => 'status', 'value' => function ($data) {
return $data->getStatus($data);
},
'filter' => ['10' => 'Active', '0' => 'Deactive'],
'contentOptions' => function ($data) {
$clr = $data->status == 10 ? 'green' : 'red';
return ['style' => 'width:80px;font-weight:bold;color:' . $clr];
},
],

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 PHP Excel Error getAttributeLabel() on null

I have to implementing export excel using moonland PHP excel extension. When I implemented it, it throws the error:
"Call to a member function getAttributeLabel() on null".
Code
$dataProvider = new \app\models\Details;
\moonland\phpexcel\Excel::widget([
'models' => $dataProvider,
'mode' => 'export', //default value as 'export'
'columns' => ['id','name','address'], //without header working, because the header will be get label from attribute label.
//'header' => ['id' => 'Header Column 1','name' => 'Header Column 2', 'address' => 'Header Column 3'],
]);
My model
class Details extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'details';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['id'], 'required'],
[['id'], 'integer'],
[['name', 'address'], 'string', 'max' => 50],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
/* return [
'id' => Yii::t('app', 'ID'),
'name' => Yii::t('app', 'Name'),
'address' => Yii::t('app', 'Address'),
];*/
return [
'id' => 'ID',
'name' => 'Name',
'address' =>'Address',
];
}
}
Table
May i know what is the problem in that, thanks in advance for your idea

Yii2 app\model\Db6TrxImportData not found

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;
}
}

Categories