In my Ticket.php when I create something from CRUD, I want it to get the current time in the Timezone. But I'm getting an error "Object of class DateTime could not be converted to string" I've used TIMESTAMP in my db time_start
I've done this so far:
public function actionCreate()
{
$model = new Ticket();
if ($model->load(Yii::$app->request->post()) && $model->save())
{
return $this->redirect(['view', 'id' => $model->id]);
} else {
// $employeeIDs = ArrayHelper::map(Employee::find()->all(), 'id', 'emp_name');
$my_date = new \DateTime("now", new \DateTimeZone('Asia/Manila'));
$model->time_start = $my_date;
$model->status = ('On Going');
// $model->employee_respond_id = array_rand($employeeIDs);
return $this->renderAjax('create', [
'model' => $model,
]);
}
}
You should format $my_date when assigning to $model->time_start, because in this way you are assigning a DateTime Object to a primitive member. For example:
$model->time_start = $my_date->format('Y-m-d H:i:s');
Related
There is my controller code
if ($this->request->isPost) {
$model->created_by = Yii::$app->user->identity->id;
$model->created_at = date('Y/m/d');
// echo $model->created_at;die;
if ($model->load($this->request->post()) && $model->save()) {
return $this->redirect(['index', 'id' => $model->id]);
}
}
and there is my model rule
public function rules()
{
return [
[['deduction_type'], 'required'],
[['created_at'], 'safe'],
[['created_by'], 'integer'],
[['deduction_type'], 'string', 'max' => 100],
];
}
My problem is, every time I pass the value in create_at and create_by data save in database as a null.
I want my actual value in db.
Instead of your way
if ($this->request->isPost) {
//Move that two Lines inside the if
$model->created_by = Yii::$app->user->identity->id;
$model->created_at = date('Y/m/d');
// echo $model->created_at;die;
if ($model->load($this->request->post()) && $model->save()) {
return $this->redirect(['index', 'id' => $model->id]);
}
}
I usually do the following:
if ($this->request->isPost) {
if ($model->load($this->request->post()) && $model->validate()) {
$model->created_by = Yii::$app->user->identity->id;
$model->created_at = date('Y/m/d');
$model->save();
return $this->redirect(['index', 'id' => $model->id]);
}
}
validate()->Checks if the Inputs are Correct according to your rules.
Afterwards you know that the entries were correct and you can set your values.
This is my usual way of tackling this problem.
You can also wrap $model->save(); with an if to check your changes as well and to catch the potential falseof save().
Check your POST, is it send empty filds created_at and created_by? don't send this fields in post and load() method will not replace it on null values.
If you are really want to insert current user id and current time, use the BlameableBehavior and TimestampBehavior.
BlameableBehavior automatically fills the specified attributes with the current user ID.
https://www.yiiframework.com/doc/api/2.0/yii-behaviors-blameablebehavior
TimestampBehavior automatically fills the specified attributes with the current timestamp.
https://www.yiiframework.com/doc/api/2.0/yii-behaviors-timestampbehavior
Theres the action
public function actionEfetuarPedidoReserva($idQuarto){
$modelPedidoReservaQuarto = new PedidoReservaQuarto();
$modelPedidoReserva = new PedidoReserva();
$model = new ComodidadesExtra();
$modelListaComodidades = new ListaComodidadesQuarto();
$modelPedidoReservaQuarto->quartoId = $idQuarto;
if($modelPedidoReservaQuarto->save()){
$modelPedidoReserva->nPessoas = 2;
$modelPedidoReserva->preco = 70.00;
$modelPedidoReserva->reservaQuartoId = $modelPedidoReservaQuarto->id;
$modelPedidoReserva->userInfoId = Yii::$app->user->id;
if($modelPedidoReserva->save()){
$model->pedidoReservaId = $modelPedidoReserva->id;
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['efetuar-pedido-reserva', 'idQuarto' => $idQuarto]);
}
return $this->render('../comodidades-extra/create', [
'model' => $model, 'modelLista' => $modelListaComodidades
]);
}
}
}
When i refresh page, it add the last pedidoreservaid inserted + 1;
i Would like to know if am i doing it the right way.
Your problem is that you create new instance of ComodidadesExtra each time when you call $model = new ComodidadesExtra();. Yii2 consider it as new independent row and you need to tell Yii2 that you should take existing row instead, using:
$model = ComodidadesExtra::find()
->where(['pedidoReservaId' => $modelPedidoReserva->id])
->one();
And your controller should look like:
if($modelPedidoReserva->save()){
if(null===($model = ComodidadesExtra::find()->where(['pedidoReservaId' => $modelPedidoReserva->id])
->one())) {
$model = new ComodidadesExtra();
}
$model->pedidoReservaId = $modelPedidoReserva->id;
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['efetuar-pedido-reserva', 'idQuarto' => $idQuarto]);
}
return $this->render('../comodidades-extra/create', [
'model' => $model, 'modelLista' => $modelListaComodidades
]);
}
I have a code where I use map to create a new collection of high scores.
The problem I have is that it overrides the default user collections. Which is not my intention.
Here is the code
$users = Users::all();
$highscore = $users->map(
function ($user) {
$calls = $user->calls->filter(
function ($call) {
$date = Carbon::parse($call->datetime)->format("Y-m-d");
$today = Carbon::now()->format("Y-m-d");
return $date == $today;
}
);
return [
'id' => $user->id,
'duration' => $calls->sum('duration'),
];
}
);
If i dump the first user after getting all the users I get the first user. Like this.
$users = Users::all();
dd($users->first());
If I dump the first user after the high score map. I get all Calls from that user which is another model. Which means that the users collection has been modified. Like this.
$highscore = $users->map(
function ($user) {
$calls = $user->calls->filter(
function ($call) {
$date = Carbon::parse($call->datetime)->format("Y-m-d");
$today = Carbon::now()->format("Y-m-d");
return $date == $today;
}
);
return [
'id' => $user->id,
'duration' => $calls->sum('duration'),
];
}
);
dd($users->first()):
Any idea on how to handle this behaviour?
The map function returns an array of [[$userId => $duration], ...]. What you want to do is to order your users by the sum of their calls.
I believe that, in order to do that easily, you should add to your User model:
public function getTodayCallSum() {
return $user->calls->filter(function($call) {
$date = Carbon::parse($call->datetime)->format("Y-m-d");
$today = Carbon::now()->format("Y-m-d");
return $date == $today;
})->sum('duration');
}
And then edit your query:
$users = User::all();
$firstUser = $users->sortBy('todayCallSum')->first();
I haven't tested this code, but I think it should help you towards the right direction.
I'm using two models in one controller. one of them is database model (model) another model is for sending sms (smsModel).
I have problem in smsModel.
I got this error in my result:
Class 'fcadmin\models\SoapClient' not found
How can I fix it?
My controller:
public function actionCreate($id) {
$model = new Requestresult();
$smsModel = new SmsSender();
$request_model = Request::findOne(['id' => $id]);
$model->CodeKargah = $request_model->CodeKargah;
$model->month = $request_model->month;
$model->trackingCode = $request_model->trackingCode;
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$smsModel->sendSms('09193452126', 'sdf');
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
smsModel:
public function sendSms($to, $text) {
$options = [
'login' => 'myusername',
'password' => 'mypassword'
];
$client = new SoapClient('http://sms.hostiran.net/webservice/?WSDL', $options);
$messageId = $client->send($to, $text);
sleep(3);
return ($client->deliveryStatus($messageId));
}
You need to read up about namespaces. If you're in a namespace and don't tell PHP that you want to use the global namespace, it will look for classes of name x in the current namespace.
In your case you need to be using new \SoapClient.
I want to create record where the particular field to be save contains the value of current model's id plus the format I made.
To get the id value I've tried to make Controller like this:
public function actionCreate()
{
$model = new NomorSurat();
if ($model->load(Yii::$app->request->post()))
{
// Save nosurat field with particular format name
$model->save(); // I save to get the current ID here, but return value still nothing
$number = $model->id;
$bulan = date('m');
$tahun = date('Y');
// Save with current id + custom format
$model->nosurat = $number.'/'.'BTPN-TMH'.'/'.Yii::$app->joenmarz->romanic_number($bulan).'/'.$tahun;
... // some stuff
// Then save it all, once again
$model->save();
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
But the variable $number saved in nosurat field returns only the custom format I've made, when I tried it in my View:
...
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'nosurat',
... // some attributes
],
]) ?>
Here's screenshot of the result:
Just add a method to your model which returns the current id and what you have saved in your database on the attribute nosurat like below and use this function for display.
public function getNosuratDisplay()
{
return $this->id.$this->nosurat;
}
This of course would make it more difficult if you want to query for that attribute because the id isn't saved in the database.
So i guess the best solution would be to generate and save this attribute in afterSave (e.g. only generate the id in insert mode i guess this is what you want).
public function generateNosurat()
{
$number = $this->id;
$bulan = date('m');
$tahun = date('Y');
$this->nosurat = $number.'/'.'BTPN-TMH'.'/'.Yii::$app->joenmarz->romanic_number($bulan).'/'.$tahun;
}
public function afterSave($insert, $changedAttributes)
{
parent::afterSave($insert, $changedAttributes);
if ($insert) {
$this->generateNosurat();
$this->save();
}
}