yii2 save date format how 1970-01-01 Database - yii2

I have a problem saving the data in the database . It saves them as 1970-01-01 , invalid date . I would read them as dd-mm-yyyy and convert them to the database in yyyy-mm-dd .
my model
public function behaviors()
{
return [
[
'class' => AttributeBehavior::className(),
'attributes' => [
attribute ['created','updated']
ActiveRecord::EVENT_BEFORE_INSERT => ['data_arrivo','data_part'],
ActiveRecord::EVENT_BEFORE_UPDATE => 'data_arrivo', 'data_part'
],
'value' => function ($event) {
return date('Y-m-d', strtotime($this->data_part));
},
],
];
Any suggestions?

You can use beforeSave event in model file. It will get call before saving the record into the table.
public function beforeSave($insert) {
if($this->data_part){
$this->data_part = Yii::$app->formatter->asDate(strtotime($this->data_part), "php:Y-m-d");
}
return parent::beforeSave($insert);
}
Don't work i post my code
public function beforeSave($insert) {
if($this->data_part){
$this->data_part = Yii::$app->formatter->asDatetime(strtotime($this->data_part), "php:Y-m-d");
if($this->data_arrivo)
$this->data_arrivo = Yii::$app->formatter->asDatetime(strtotime($this->data_arrivo), "php:Y-m-d");
}
return parent::beforeSave($insert);
}

Related

Laravel validation with custom json respons

Quick question.
Would it be possible to changes the JSON validation response of laravel?
This is for a custom API that I am building in Laravel.
Validation process
$validation = $this->validate(
$request, [
'user_id' => 'required',
]);
The response shows up like this in json
{
"message": "The given data was invalid.",
"errors": {
"user_id": [
"The user id field is required."
],
}
}
Preferable it would become something like this.
{
"common:" [
"status": "invalid",
"message": "Param xxxx is required",
],
}
What would be the best way to changes this?
Is it even possible?
Thank you.
You can do this, and it will be reflected globally.
Navigate to below folder and use Controller.php
app/Http/Controllers
use Illuminate\Http\Request;
Write below method in Controller.php and change response as you want.
public function validate(
Request $request,
array $rules,
array $messages = [],
array $customAttributes = [])
{
$validator = $this->getValidationFactory()
->make(
$request->all(),
$rules, $messages,
$customAttributes
);
if ($validator->fails()) {
$errors = (new \Illuminate\Validation\ValidationException($validator))->errors();
throw new \Illuminate\Http\Exceptions\HttpResponseException(response()->json(
[
'status' => false,
'message' => "Some fields are missing!",
'error_code' => 1,
'errors' => $errors
], \Illuminate\Http\JsonResponse::HTTP_UNPROCESSABLE_ENTITY));
}
}
I have tried it with Laravel 5.6, maybe this is useful for you.
#Dev Ramesh solution is still perfectly valid for placing inline within your controller.
For those of you looking to abstract this logic out into a FormRequest, FormRequest has a handy override method called failedValidation. When this is hit, you can throw your own response exception, like so...
/**
* When we fail validation, override our default error.
*
* #param ValidatorContract $validator
*/
protected function failedValidation(\Illuminate\Contracts\Validation\Validator $validator)
{
$errors = $this->validator->errors();
throw new \Illuminate\Http\Exceptions\HttpResponseException(
response()->json([
'errors' => $errors,
'message' => 'The given data was invalid.',
'testing' => 'Whatever custom data you want here...',
], 422)
);
}
I was searching for an answer to this and I think I found a better way. There is an exception handler in a default Laravel app - \App\Exceptions\Handler - and you can override the invalidJson method:
<?php
namespace App\Exceptions;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Validation\ValidationException;
class Handler extends ExceptionHandler
{
// ...
protected function invalidJson($request, ValidationException $exception)
{
$errors = [];
foreach ($exception->errors() as $field => $messages) {
foreach ($messages as $message) {
$errors[] = [
'code' => $field,
'message' => $message,
];
}
}
return response()->json([
'error' => $errors,
], $exception->status);
}
}

How to get count of items which are created today in yii2?

Sample data in my collection :
created_at : 2018-04-29 05:25:28.000Z
I'm using TimestampBehavior,
'timestamp' => [
'class' => TimestampBehavior::className(),
'attributes' => [
ActiveRecord::EVENT_BEFORE_INSERT => 'created_at',
ActiveRecord::EVENT_BEFORE_UPDATE => 'updated_at',
],
'value' => function() { $now = new \DateTime('NOW'); return new \MongoDB\BSON\UTCDateTime(strtotime($now->format("Y-m-d H:i:s"))*1000); },
],
This is my count function :
public function count_users () {
$cnt = Users::find ()->select (['_id', 'created_at'])->where (['created_at'=>date ('Y-m-d')])->all ();
return count ($cnt);
}
How to use find select with a date?
You could use the count() function
You could use the count() function and new Expression('NOW()')
public function count_users () {
$cnt = Users::find ()->select (['_id', 'created_at'])
->where (['created_at' => new \yii\db\Expression('curdate()')]->count();
retur $cnt;
}
yii-db-query
yii-db-query#count()-detail
Change your where condition like below and try
public function count_users () {
$cnt = Users::find ()->where('DATE(created_at)=CURDATE()')->count();
return $cnt;
}
yii-db-query#count()-detail
You can reduce it to one-liner by using count() as per suggestions above or using scalar()
scalar(): returns the value of the first column in the first row of
the query result.
public function count_users(){
return Users::find()
->select([new \yii\db\Expression('COUNT(id) as total')])
->where(['DATE(created_at)'=>new \yii\db\Expression('CURDATE()')])
->scalar();
}

creation time is invalid when update in yii2

when I want to update form in yii2
It tells me this error
creation time is invalid -- update time is invalid
What do you think is it?
public function beforeSave($insert)
{
$date = new \DateTime();
$date->setTimestamp(time());
$date->setTimezone(new \DateTimezone('Istanbul'));
$this->update_time = $date->format('Y-m-d H:i:s');
if($this->isNewRecord)
$this->creation_time = $date->format('Y-m-d H:i:s');
return parent::beforeSave($insert);
}
My problem has been resolved
change date to safe in rules
[['creation_time', 'update_time'], 'safe'],
Your code is correct "Nader" but some time assigning the value not work so just remove the value or use this
public function behaviors()
{
return [
[
'class' => TimestampBehavior::className(),
'createdAtAttribute' => 'create_time',
'updatedAtAttribute' => 'update_time',
//'value' => new Expression('NOW()'),
],
];
}
Just comment the value,
it will work.
For more detail https://www.yiiframework.com/doc/api/2.0/yii-behaviors-timestampbehavior
Just could just use the available TimestampBehavior behavior
use yii\behaviors\TimestampBehavior;
use yii\db\Expression;
use yii\db\ActiveRecord;
class Mymodel extends ActiveRecord{
public function behaviors() {
return [
[
'class' => TimestampBehavior::className(),
'createdAtAttribute' => 'creation_time',
'updatedAtAttribute' => 'update_time',
'attributes' => [
ActiveRecord::EVENT_BEFORE_INSERT => 'creation_time',
ActiveRecord::EVENT_BEFORE_UPDATE => 'update_time',
],
'value' => new Expression('NOW()')
]
];
}
}
Remove any validation rules from your model you may have for this two attributes
creation_time and update_time

Setting default values on create and update in yii

I am trying to update some fields in yii 1.1 using the following rules, but it is not working.
public function rules()
{
return [
['CreatedOn','default','value'=>time(),'isEmpty'=>true,'on'=>'insert'],
['CreatedBy','default','value'=>\Yii::$app->user->identity->id,'isEmpty'=>true,'on'=>'insert'],
['ModifiedOn','default','value'=>time(),'isEmpty'=>true,'on'=>'update'],
['ModifiedBy','default','value'=>\Yii::$app->user->identity->id,'isEmpty'=>true,'on'=>'update'],
];
}
I am looking to update CreatedBy and CreatedOn when inserting, and ModifiedBy and ModifiedOn when updating.
From soju's excellent answer, with Yii2:
By default, a model supports only a single scenario named default
You should therefore set the scenario manually in your controller i.e:
$model->scenario = 'insert';
You could also use when instead of on i.e:
['CreatedOn', 'default', 'value'=>time(), 'isEmpty'=>true, 'when'=>
function($model) { return $model->isNewRecord; }
],
['ModifiedOn', 'default', 'value'=>time(), 'isEmpty'=>true, 'when'=>
function($model) { return !$model->isNewRecord; }
],
An alternative to setting them in rules() would be to use beforeSave() to set them:
public function beforeSave($insert) {
if ($insert) {
$this->CreatedBy = \Yii::$app->user->identity->id;
$this->CreatedOn = time();
} else {
$this->ModifiedBy = \Yii::$app->user->identity->id;
$this->ModifiedOn = time();
}
return parent::beforeSave($insert);
}
This is the correct way to do it:
Behaviors:
public function behaviors()
{
return [
'timestamp' => [
'class' => TimestampBehavior::className(),
'attributes' => [
ActiveRecord::EVENT_BEFORE_INSERT => 'created_on',
ActiveRecord::EVENT_BEFORE_UPDATE => 'modified_on',
ActiveRecord::EVENT_BEFORE_DELETE => 'deleted_at',
],
'value' => function () {
return date('Y-m-d H:i:s');
}
],
[
'class' => BlameableBehavior::className(),
'createdByAttribute' => 'created_by_id',
'updatedByAttribute' => 'updated_by_id',
],
];
}
If you need just a simple rule for default value, this is enough:
public function rules()
{
return [
['CreatedOn','default','value'=>time()],
['ModifiedOn','default','value'=>time(),'isEmpty'=>true],
...
]
}
The 'isEmpty'=>true option override the default isEmpty() function and returns true (it is always seen as empty) dues it is always populated with time()
For Yii2 version 2.0.8 from April 2016 I had an error with 'isEmpty'=>true because according to documentation it expects a function so you must to do like this:'isEmpty' => function ($value) {return true;}.
When you use this solution you get a value for ModifiedBy even on create and I believe that was not an intention. It is possible to write isEmpty to return true in case of an update but I simply used 'when' because it is much more readable for me. So, my solution for rules in a model was :
['CreatedBy', 'default', 'value' => Yii::$app->user->id],
['ModifiedBy', 'default', 'value' => Yii::$app->user->id,
'when' => function ($model) { return !$model->isNewRecord;}],
As a side note for this question is that for timestamps you should rely on database to fill them, CreatedOn with default value and a before update trigger for ModifiedOn.

Yii2: Returning an array of primary keys

Maybe I'm missing the essentials but why the following code will throw a Bad Request error (#400) complaining on "Missing parameter id" when rendering a view on a MySQL view?
In model:
public static function primaryKey()
{
return [
'vcostumbre_id',
'vbibliografia_id',
'vpagina_inicial',
];
}
In controller:
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
But this will work:
public function actionView($vcostumbre_id, $vbibliografia_id, $vpagina_inicial)
{
$id = [
'vcostumbre_id' => $vcostumbre_id,
'vbibliografia_id' => $vbibliografia_id,
'vpagina_inicial' => $vpagina_inicial,
];
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
Because in the URL you have not the parameter "id".
It should be /mycontroller/view?id=42".
Check the view file where the link is. It should be :
Url::to(['/controller/view', 'id' => 42])