Yii2: Attribute (CLIENT_ID) is invalid - php

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.

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-Time not saved while creating a record

I am creating a record in which there is a created_at (datetime) field. While saving the record only date is saved into the Database.
Create Action
public function actionCreate()
{
$model = new Meters();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
The saved date is like 2017-12-03 00:00:00. Also I have used var_dump($model) and I get on date not time.
I don't know what I am missing.
Update 1
My model is
public function rules()
{
return [
[['meter_msn','description','meter_status','historic'],'required'],
//[['meter_msn'],'unique','message'=>'This meter already exists'],
[['created_at', 'updated_at','comments'], 'safe'],
[['created_by', 'updated_by', 'status','historic'], 'integer'],
[['description', 'meter_msn'], 'string', 'max' => 200],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'description' => 'Name',
'meter_msn' => 'Meter MSN',
'created_at' => 'Created At',
'updated_at' => 'Updated At',
'created_by' => 'Created By',
'updated_by' => 'Updated By',
'status' => 'Status',
'comments' => 'Comments',
'meter_status' => 'Meter Status',
'historic'=> 'Version'
];
Any help would be highly appreciated.
Add the following to your model:
public function beforeSave($insert)
{
if($this->isNewRecord) {
$this->created_at = date('Y-m-d H:i:s');
}else {
$this->updated_at = date('Y-m-d H:i:s');
}
return parent::beforeSave($insert);
}

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

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],
];

Categories