How to hide the TIME value in record update? - yii2

I use Yii2 Framework,
I have this code for a column in the grid view:
[
'attribute' => 'ultimamodifica',
'value' => function ( $model ) {
$stampa= "";
if( $model->Utenteup_elenchi ){
$tip1= $model->Utenteup_elenchi;
//$tip1= ($tip1) ? User::findOne($tip1) : null;
//$tip1n= ($tip1) ? $tip1->id : "";
$stampa= $tip1;
}
return $model->ultimamodifica." utente ".$stampa;
},
'label' => 'Ultima modifica'],
Now, "ultimamodifica" is a column that contain the CURRENT_TIMESTAMP and is typing like "TIMESTAMP".
This show me this value: "2021-02-22 11:58:14 utente 734".
I wish to show only the date and the user, so I want to hide the hour of update. The record will be "2021-02-22 utente 734". What I have to do for this?
Thank you very much!!!!

Use asDate()
[
'attribute' => 'ultimamodifica',
'value' => function ($model) {
$stampa = '';
if ($model->Utenteup_elenchi) {
$tip1 = $model->Utenteup_elenchi;
$stampa = $tip1;
}
return Yii::$app->formatter->asDate($model->ultimamodifica) . ' utente ' . $stampa;
},
'label' => 'Ultima modifica',
],

Related

How to retrive from other table and input it again into another table in laravel?

I want to retrieve some data from 'tbl_karyawan' and input into 'tbl_absen' which is if the NIP exist from 'tbl_karyawan' then parshing some data into 'tbl_absen'. I was create the code, and the data is going well. but i have something trouble with
i want the data input in Nip_kyn be like 'KIP001' not [{"Nip_kyn":"KIP001"}].
this is my Model
public function presensi($data)
{
$isExist = DB::table('tbl_karyawan')
->where('Nip_kyn', $data)->exists();
if ($isExist) {
$namakyn = DB::table('tbl_karyawan')->where($data)->get('Nama_kyn');
$nippppp = DB::table('tbl_karyawan')->where($data)->select('Nip_kyn')->get($data);
$values = array('Nip_kyn' => $nippppp, 'Nama_kyn' => $namakyn, 'Jam_msk' => now(), 'Log_date' => today());
DB::table('tbl_absen')->insert($values);
} else {
echo 'data not available';
}
}
this is my controller
public function get()
{
$day = [
'time_in' => $this->AbsenModel->timeIN(),
'time_out' => $this->AbsenModel->timeOut(),
'break' => $this->AbsenModel->break(),
// absen here
's' => $this->AbsenModel->absensi(),
];
$data = [
'Nip_kyn' => Request()->Nip_kyn,
];
$this->AbsenModel->presensi($data);
return view('v_absen', $data, $day);
}
Yup, I finally got it, the problem is on my model.
$nama_karyawan = DB::table('tbl_karyawan')->where($data)->value('Nama_kyn');
$nipkyn = DB::table('tbl_karyawan')->where($data)->value('Nip_kyn');
I just change 'get' to 'value'.

How to update field in user table yii2

I have modified user table to add one column, the column's name is id_periode, I have advanced template, so from backend controler i want update that column value. I create controller like this
public function actionPindahPeriode($id)
{
$model2 = $this->findModel2($id);
if ($model2->load(Yii::$app->request->post()) ) {
$model2->save();
return $this->render('view',
'model2' => $this->findModel2($id),
]);
}
date_default_timezone_set('Asia/Makassar');
$jam_sekarang = date('h:i:s', time());
$tgl_sekarang=date('Y-m-d');
$model_periode = Periode::find()
->andWhere(['>','mulai_daftar_ulang',$tgl_sekarang ])
->asArray()
->all();
return $this->renderAjax('pindah_periode', [
'model_periode' => $model_periode,
'model2' => $this->findModel2($id),
]);
}
The findModel2 function is like this
protected function findModel2($id)
{
if (($model = User::findOne($id)) !== null) {
return $model;
}
throw new NotFoundHttpException('The requested page does not exist.');
}
I render that model into a form
<?php $form = ActiveForm::begin(); ?>
<?php $listData=ArrayHelper::map($model_periode,'id',function($model_periode){
return $model_periode['nama_periode'].' Tahun '.$model_periode['tahun'];});?>
<?= $form->field($model2, 'id_periode')->dropDownList($listData, ['prompt' => '']) ?>
<div class="form-group">
<?= Html::submitButton('Save', ['class' => 'btn btn-danger']) ?>
</div>
<?php ActiveForm::end(); ?>
The form is working but i can not update the value id_periode column in table user. There is not error showing, any suggestion?
Make sure your new attribute id_periode has a rule defined in the public function rules(){} function, this way $model2->load(Yii::$app->request->post()) will assign this value from the data submitted.
$model->save() returns a bool value whether the record was saved or not. You can use this to your advantage and check whether there are any validation errors.ie:
if($model2->save()) {
return $this->render('view',
'model2' => $this->findModel2($id),
]);
} else {
return $this->renderAjax('pindah_periode', [
'model_periode' => $model_periode,
'model2' => $this->findModel2($id),
]);
}
Option 1 : Check your column fields in User model's validation rules. You need to shift unwanted column fields from required attribute to safe attribute.
Option 2 : try $model2->save(false);. false will override your model rules.

How to force data update on laravel validation custom unique

I'm new in laravel. I have a table with menu_id and title I tried to make this title field unique when have the same menu_id. I found the solution here
But I got problem when update it. Can anyone help please?
My code
Validator::extend('unique_custom', function ($attribute, $value, $parameters)
{
// Get the parameters passed to the rule
list($table, $field, $field2, $field2Value) = $parameters;
// Check the table and return true only if there are no entries matching
// both the first field name and the user input value as well as
// the second field name and the second field value
return \DB::table($table)->where($field, $value)->where($field2, $field2Value)->count() == 0;
});
public function updateSubmenu( Request $request) {
$this->validate( $request, [
'menu_id' => 'required',
'title' => 'required|unique_custom:posts,title,menu_id,'.$request->menu_id,
'order_by' => 'required|integer',
'description' => 'required'
],
[
'title.unique_custom' => 'This title already token'
]
);
}
Can you explain what problem have you got on update? Some exception?
Edit:
If you couldn't update record if title not changes, you need to add one condition to Validator:
Validator::extend('unique_custom', function ($attribute, $value, $parameters)
{
// Get the parameters passed to the rule
list($table, $field, $field2, $field2Value) = $parameters;
// If old value not changed, don't check its unique.
$current = \DB::table($table)->where('title')->first();
if( $current->{$field} == $value) {
return true;
}
return \DB::table($table)->where($field, $value)->where($field2, $field2Value)->count() == 0;
});

Yii2 model custom validate method / function does not work

I want to validate my fine_amount against 2 input date. But it does not return any error. Without validating this method it saved data.
I also looked into
Yii2: how to use custom validation function for activeform? but for me no solution.
Below is my code
Controller method
$model = $this->findModel($id);
$model->payment_date=date('d-M-Y',strtotime($model->payment_date));
$model->payment_expected_date=date('d-M-Y',strtotime($model->payment_expected_date));
if ($model->load(Yii::$app->request->post())) {
$model->payment_date=date('Ymd',strtotime($model->payment_date));
$model->payment_expected_date=date('Ymd',strtotime($model->payment_expected_date));
if($model->validate()){
$model->save();
return $this->redirect(['view', 'id' => $model->id]);
}
else{
$model->payment_date=date('d-M-Y',strtotime($model->payment_date));
$model->payment_expected_date=date('d-M-Y',strtotime($model->payment_expected_date));
return $this->render('update', [
'model' => $model,
]);
}
}
return $this->render('update', [
'model' => $model,
]);
My Rule
['fine_amount' , 'fine_required'] ,
Validation function
public function fine_required() {
$this->payment_date = date ( 'Ymd' , strtotime ( $this->payment_date ) );
$this->payment_expected_date = date ( 'Ymd' , strtotime ( $this->payment_expected_date ) );
if ( $this->payment_date > $this->payment_expected_date ) {
if ( $this->fine_amount <= 0 ) {
$this->addError ( 'fine_amount' , 'Fine Amount Must be add.' );
}
return false;
}
return true;
}
You need to use conditional validation for your case, use when and whenClient respectively see below add to your rules section and remove any other validations. This will handle frontend and backend both validations
[ 'fine_amount' , 'required' , 'when' => function($model) {
if ( $model->payment_date > $model->payment_expected_date ) {
if ( $model->fine_amount <= 0 ) {
return true;
}
}
return false;
} , 'whenClient' => 'function (attribute, value) {
var d1 = new Date($("#' . Html::getInputId($this, 'payment_date') . '").val());
var d2 = new Date($("#' . Html::getInputId($this, 'payment_expected_date'). '").val());
if(d1>d2){
if(value<=0){
return true;
}
}
return false;
}' , 'message' => 'Fine Amount Must be add.' ] ,
EDIT
Replaced strtolower ( \yii\helpers\StringHelper::basename ( get_class ( $this ) ) ) with Html::getInputId as it is more suitable for this case.

Yii2 karthik editable column first row not working

I used karthik grid view and editable column to edit my grid view data. it not work for the first row of the grid view and work for the other rows when i enter value to the first row it give error like this
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
my gridview code is.
<?= GridView::widget([
'dataProvider' => $dataProvider,
'pjax' => true,
'pjaxSettings' => [
'options' => [
'id' => 'grid',
]
],
'export'=>false,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
[
'header'=>'Sub Category',
'value'=>'item.subCategory.name',
],
'item.code',
[
'header'=>'Brand',
'value'=>'item.brand.name',
],
'item.description',
'item.pack_size',
[
'header'=>'Unit',
'value'=>'item.unit',
],
[
'header'=>'Last Price',
'value'=>function($model){
$customerId = $model->customerOrderRequest->customer_id;
$lastPurchasedPrice = Item::getLastPurchasedPrice($customerId,$model->item_id);
return '$ ' . number_format($lastPurchasedPrice, 2);
}
],
[
'class' => 'kartik\grid\EditableColumn',
'attribute'=>'qty',
'editableOptions' =>
[
'formOptions' => ['action' => 'customer-order-request']
],
'header' => 'Qty',
],
[
'header'=>'Estimate',
'value'=>function($model)
{
return '123123.00';
}
],
[
'header'=>'Price (UNIT)',
'format'=>'raw',
'value'=>function($modal){
$salse_rep_id = Yii::$app->user->identity->ref_id;
$exsist_respond = Respond::find()->where(['sales_rep_id'=>$salse_rep_id,'customer_order_request_id'=>$modal->customer_order_request_id])->one();
if(!empty($exsist_respond)){
$exsist_respond_item = RespondItem::find()->where(['item_id'=>$modal->item_id,'respond_id'=>$exsist_respond->id])->one();
if(!empty($exsist_respond_item)){
$price = $exsist_respond_item->price;
} else {
$price = NULL;
}
} else {
$price = NULL;
}
if(!empty($exsist_respond) && $exsist_respond->status !="Pending"){
return $price;
}else{
return "<input type='text' class='respond-item' cor='$modal->customer_order_request_id' value='$price' item_id='$modal->item_id' />";
}
},
'visible'=>(Yii::$app->user->identity->ref_table =="sales_rep")? true:false
],
],
]); ?>
and my controller is
public function actionEditable()
{
if (Yii::$app->request->post('hasEditable'))
{
$customerItemsId = Yii::$app->request->post('editableKey');
print_r($customerItemsId);die();
$model = RequestItem::findOne($customerItemsId);
$out = Json::encode(['output'=>'', 'message'=>'']);
$post = [];
$posted = current($_POST['RequestItem']);
$post['RequestItem'] = $posted;
if ($model->load($post))
{
$model->save();
$output = '';
$out = Json::encode(['output'=>$output, 'message'=>'']);
}
echo $out;
return;
}
}
any one can help me with this problem.
Form tag nested.
a trick: Add a fake form to let browser remove it.
I meet this problem today, cause I put a form in another, they are nested.
So the browser remove the first nested form.
In the official W3C XHTML specification, Section B. "Element Prohibitions", states that:
"form must not contain other form elements."
official website
Following is sample code:
<form id="thisisMainForm">
<form id="dummy"> ->This will get Removed
<gridview id="thisisEditableGridView">
Gridviewcode.....
</gridview>
</form>
</form>