Yii2-Time not saved while creating a record - php

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

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: 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.

YII 2 relational data from third table

I have a database having relationship of three levels. cheque->account->customer. Now I am trying to retrieve data from all three table at same time using the following method.
$query = Cheque::find();
$query->joinWith(['account.customer']);
$query->orderBy('sr desc');
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
Cheque Model:
class Cheque extends \common\components\db\ActiveRecord {
/**
* #inheritdoc
*/
public static function tableName() {
return 'cheque';
}
/**
* #inheritdoc
*/
public function rules() {
return [
[['sr'], 'integer'],
[['ID', 'account_ID'], 'required'],
[['ID', 'account_ID', 'created_by', 'branch_ID', 'application_ID'], 'string'],
[['serial_start', 'serial_end', 'status'], 'number'],
[['created_on'], 'safe']
];
}
/**
* #inheritdoc
*/
public function attributeLabels() {
return [
'ID' => 'ID',
'account_ID' => 'Account ID',
'serial_start' => 'Serial Start',
'serial_end' => 'Serial End',
'created_on' => 'Created On',
'created_by' => 'Created By',
'branch_ID' => 'Branch ID',
'application_ID' => 'Application ID',
'status' => 'Status',
'sr' => 'ID'
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getAccount() {
return $this->hasOne(Account::className(), ['ID' => 'account_ID']);
}
public static function getActiveChequeBook($account_ID) {
return Cheque::findAll(['account_ID' => $account_ID, 'status' => array_search('Active', \common\models\Lookup::$cheque_status)]);
}
}
But executing this I get the following error:
pre>Exception 'yii\base\InvalidCallException' with message 'Setting read-only property: common\models\Account::customer'
Property customer in your common\models\Account model has no setter (only getCustomer method exists). Check you model and add appropriate property to class.

Can't get data to save in MySQL using Laravel

I'm trying to get the ticket data to save in the database and when I submit the form I get no error, but it does not insert the data into the database. Added my Route just adding random text because the post
Controller Code
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'title' => 'required|min:15',
'category' => 'required',
'priority' => 'required',
'message' => 'required|min:100',
]);
$ticket = new Ticket([
'user_id' => Auth::user()->id,
'category_id' => $request->input('category'),
'ticket_id' => strtoupper(str_random(10)),
'name' => $request->input('name'),
'title' => $request->input('title'),
'priority_id' => $request->input('priority'),
'message' => $request->input('message'),
]);
$ticket->status_id = '1';
$ticket->save();
return 'Success';
}
Model Code
class Ticket extends Model
{
protected $fillable = [
'user_id', 'category_id', 'ticket_id', 'name', 'title', 'priority_id', 'message', 'status_id',
];
public function category()
{
return $this->belongsTo(Category::class);
}
public function priority()
{
return $this->belongsTo(Priority::class);
}
public function status()
{
return $this->belongsTo(Status::class);
}
public function comments()
{
return $this->hasMany(Comment::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
}
Routes
Route::get('/', 'HomeController#index')->name('home');
Route::get('/home', 'HomeController#index')->name('home');
Route::get('/compliance', 'HomeController#Compliance')->name('compliance');
Route::get('/messages', 'HomeController#Messages')->name('messages');
Route::get('/tickets', 'TicketsController#userTickets')->name('tickets');
Route::get('/tickets/create', 'TicketsController#create')->name('tickets/create');
Route::post('/tickets/store', 'TicketsController#store');
Thanks for all the help I figured it I had two mistakes in the controller this took me 2 days to figure it out LOL
$this->validate($request, [
'name' => 'required', // I removed this
'title' => 'required|min:15',
'category' => 'required',
'priority' => 'required',
'message' => 'required|min:100',
]);
and in the $ticket
$ticket = new Ticket([
'user_id' => Auth::user()->id,
'category_id' => $request->input('category'),
'ticket_id' => strtoupper(str_random(10)),
'name' => $request->input('name') // I replaced this with 'name' => Auth::user()->name,
'title' => $request->input('title'),
'priority_id' => $request->input('priority'),
'message' => $request->input('message'),
]);

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

Categories