Can not save data but the message has been save - cakephp-3.0

I have created Cake PHP 3, I want to add data, but when I clik submit button, the data is didn't save but the message show data has been save. I add into two different tables. When I try to add data in one table is fine.
This is my controller
StoreController.php
public function add()
{
$this->loadComponent('General');
$setStatus = 1;
$store = $this->Stores->newEntity();
if ($this->request->is('post')) {
// dd( $this->request->getData());exit;
$connection = ConnectionManager::get('ora');
$connection->begin();
$store = $this->Stores->patchEntity($store, $this->request->getData());;
$merchantTable = TableRegistry::get('MasterFile.Merchants');
$merchant = $merchantTable->find()->where(['MERCHANT_CODE'=>$store->MERCHANT_CODE])->first();
$store->MERCHANT_ID = $merchant->MERCHANT_ID;
$store->CREATED_DATE = date("Y-m-d h:i:s");
$store->LAST_UPDATED_DATE = date("Y-m-d h:i:s");
$store->LAST_APPROVED_DATE = date("Y-m-d h:i:s");
$store->LAST_VERSION_DATE = date("Y-m-d h:i:s");
// $store->store_address->LINE1 = $store->LINE1;
// Start - Controller Code to handle file uploading
if(!empty($this->request->data['STORE_LOGO']['name']))
{
$file = $this->request->data['STORE_LOGO']; //put the data into a var for easy use
$ext = substr(strtolower(strrchr($file['name'], '.')), 1); //get the extension
$arr_ext = array('jpg', 'jpeg', 'png'); //set allowed extensions
$fileName = $this->request->data['STORE_LOGO']['name'];
$uploadPath = WWW_ROOT.'img/store_logo/';
$uploadFile = $uploadPath.$fileName;
//only process if the extension is valid
if(in_array($ext, $arr_ext))
{
if(move_uploaded_file($this->request->data['STORE_LOGO']['tmp_name'],$uploadFile))
{
$store['STORE_LOGO'] = $uploadFile;
}
}
}
if(!empty($this->request->data['BACKGROUND_PICTURE']['name']))
{
$fileName = $this->request->data['BACKGROUND_PICTURE']['name'];
$uploadPath = WWW_ROOT.'img/background_picture/';
$uploadFile = $uploadPath.$fileName;
if(move_uploaded_file($this->request->data['BACKGROUND_PICTURE']['tmp_name'],$uploadFile))
{
$store['BACKGROUND_PICTURE'] = $uploadFile;
}
}
// now do the save
if ($this->Stores->save($store)) {
$setStatus = 1;
$message = 'The store has been saved.';
if($setStatus == 1){
$this->loadComponent('General');
$this->loadModel('MasterFile.Addresss');
$setStatus = 1;
$address = $this->Addresss->newEntity();
//dd($this->request->data);
$this->request->data['Address']['LINE1'] = $this->request->data['LINE1'];
$this->request->data['Address']['LINE2'] = $this->request->data['LINE2'];
$this->request->data['Address']['LINE3'] = $this->request->data['LINE3'];
//dd($this->request->data['Address']);
$connection = ConnectionManager::get('ora');
$connection->begin();
$address = $this->Addresss->patchEntity($address, $this->request->data['Address']);
// dd($address);
// now do the save
if ($this->Addresss->save($address)) {
$setStatus = 1;
$message = 'The store has been saved.';
}else{
$setStatus = 0;
$message = 'The store could not be saved. Please, try again.';
}
$this->Flash->set(__($message));
}
}else{
$setStatus = 0;
$message = 'The store could not be saved. Please, try again.';
}
$this->Flash->set(__($message));
if($setStatus){
$connection->commit();
return $this->redirect(['action' => 'index']);
}else {
$connection->rollback();
}
}
$this->set(compact('store'));
$this->set('_serialize', ['store']);
}
What should i do?
Thank you for your help!

Try debugging the entity:
if ($this->Stores->save($store)) {
debug($store);
...

Related

Skip the first line of a CSV file in Yii2

public function actionUpload(){
$model = new CsvForm();
if($model->load(Yii::$app->request->post())){
$file = UploadedFile::getInstance($model,'file');
$filename = 'Data.'.$file->extension;
$upload = $file->saveAs('uploads/'.$filename);
if($upload){
define('CSV_PATH','uploads/');
$csv_file = CSV_PATH . $filename;
$filecsv = file($csv_file);
print_r($filecsv);
foreach($filecsv as $data){
$modelnew = new Customer1();
$hasil = explode(",",$data);
$nim = $hasil[0];
$nama = $hasil[1];
$jurusan = $hasil[2];
$angkatan = $hasil[3];
$modelnew->username = $nim;
$modelnew->firstname = $nama;
$modelnew->lastname = $jurusan;
$modelnew->password = $angkatan;
$modelnew->save();
}
unlink('uploads/'.$filename);
return $this->redirect(['site/index']);
}
}else{
return $this->render('upload',['model'=>$model]);
}
}
This is my CSV data
user1,name,pass,info
user2,name,pass,info
etc..,
So I want to skip Bold content and proceed my execution.
You could shift the array
$filecsvtemp = file($csv_file);
$filecsv = array_shift($filecsvtemp );
in this way the first row of the array is not present in the resulting array
otherwise use a counter
$cnt = 0;
$filecsv = file($csv_file);
print_r($filecsv);
foreach($filecsv as $data){
if ($cnt!=0){
$modelnew = new Customer1();
$hasil = explode(",",$data);
$nim = $hasil[0];
$nama = $hasil[1];
$jurusan = $hasil[2];
$angkatan = $hasil[3];
$modelnew->username = $nim;
$modelnew->firstname = $nama;
$modelnew->lastname = $jurusan;
$modelnew->password = $angkatan;
$modelnew->save();
}
$cnt++;
}

yii2 active record transaction still commit when the validation failed

I'm using Yii2 active record transaction, but the validation failed in the middle of the codes, it still commit the transaction.
Please advice.
public function actionCreate()
{
$model = new PoAgen();
$seq = Sequence::FindOne(['seq_id' => 'INV/AG', 'seq_name' => (int)date('ymd')]);
if(is_null($seq))
{
$_seq = new Sequence();
$_seq->seq_id = 'INV/AG';
$_seq->seq_name = (int)date('ymd');
$_seq->value = 0;
$_seq->save();
$model->trx_id = $_seq->seq_id . '/' . $_seq->seq_name . str_pad($_seq->value+1, 3, "0", STR_PAD_LEFT);
}
else {
$seq->value += 1;
$model->trx_id = $seq->seq_id . '/' . $seq->seq_name . str_pad($seq->value, 3, "0", STR_PAD_LEFT);
$seq->update();
}
$model->pot_cong = 0;
$model->pot_basah_kg = 0;
$model->pot_tangkai = 0;
$model->ppn = 0;
$model->pot_pinjaman = 0;
$model->pot_panjar = 0;
$model->ongkos_angkut = 0;
$model->pot_angkut = 0;
$model->is_transfer = true;
$model->buy_date = date('Y-m-d');
if ($model->load(Yii::$app->request->post())) {
$transaction = Yii::$app->db->beginTransaction();
try
{
$model->created_by = Yii::$app->user->identity->id;
$model->created_time = date('Y-m-d H:i:s');
$saldo = Saldo::findOne(1);
$kas = Kas::findOne(1000); // pembelian agen pks
$agen = Agen::findOne($model->agen_id);
if(!$model->is_transfer)
{
if($kas->code == 'D')
{
$saldo->balance -= $model->total_bayar;
}
else
{
$saldo->balance += $model->total_bayar;
}
$saldo->update();
}
$model->save();
// posting to kasbook
$kasbook = new KasBook();
$kasbook->kasbook_id = uniqid();
$kasbook->kas_date = $model->buy_date;
$kasbook->ref_trxid = $model->trx_id;
$kasbook->kas_id = $kas->kas_id;
$kasbook->code = $kas->code;
$kasbook->total = $model->total_bayar;
$kasbook->balance = $saldo->balance;
$kasbook->received_by = '['. $model->agen_id . '] ' . $agen->agen_name;
$kasbook->remark = 'Berat Bersih : ' . $model->r_bersih . ', Harga : ' . $model->price;
$kasbook->vehicle_id = $model->vehicle_id;
$kasbook->is_transfer = $model->is_transfer;
$kasbook->created_by = Yii::$app->user->identity->id;
$kasbook->created_time = date('Y-m-d H:i:s');
$kasbook->save();
if($model->ppn != 0)
{
$kb_1 = new KasBook();
$kb_1->kasbook_id = uniqid();
$kb_1->kas_date = $model->buy_date;
$kb_1->ref_trxid = $model->trx_id;
$kb_1->kas_id = 2000;
$kb_1->code = 'K';
$kb_1->total = $model->ppn;
$kb_1->balance = $saldo->balance;
$kb_1->remark = 'Ppn Pembelian Agen';
$kb_1->vehicle_id = $model->vehicle_id;
$kb_1->is_transfer = true;
$kb_1->created_by = Yii::$app->user->identity->id;
$kb_1->created_time = date('Y-m-d H:i:s');
$kb_1->save();
}
// kurang posting ke purchase order barang
$transaction->commit();
return $this->redirect(['view', 'id' => $model->trx_id]);
}
catch(Exception $e) {
$transaction->rollBack();
throw $e;
}
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
validation failed in if($model->ppn !=0) { ... }
because there is no any primary key in the master table, but the transaction still do commit and the model inserted to database.
Please advice. Thanks before.
save() method does not throw exceptions but returns boolean so you need to throw it explicitly. Replace every
...->save();
in try-catch with
if (! ...->save()) {
throw new \yii\db\Exception('Error while saving ... model!');
// or use general \Exception()
}
so now it can be caught.
You can do this by :
$flag=true;
if($model->ppn != 0)
{
$kb_1 = new KasBook();
$kb_1->kasbook_id = uniqid();
$kb_1->kas_date = $model->buy_date;
$kb_1->ref_trxid = $model->trx_id;
$kb_1->kas_id = 2000;
$kb_1->code = 'K';
$kb_1->total = $model->ppn;
$kb_1->balance = $saldo->balance;
$kb_1->remark = 'Ppn Pembelian Agen';
$kb_1->vehicle_id = $model->vehicle_id;
$kb_1->is_transfer = true;
$kb_1->created_by = Yii::$app->user->identity->id;
$kb_1->created_time = date('Y-m-d H:i:s');
if(!$kb_1->save())
{
$flag=false;
}
}
if($flag)
$transaction->commit();
else
$transaction->rollback();

insert data to the database from csv file

i am trying to insert data from the csv excel file to the database but the code seem not to work,
i don't know where am doing wrong.
here is my code:
public function postUploadS(){
$file = array('file' => Input::file('file'));
$rule = array('file' => 'required');
$mime = array( 'text/csv',
'text/plain',
'application/csv',
'text/comma-separated-values',
'application/excel',
'application/vnd.ms-excel',
'application/vnd.msexcel'
);
$uploaded_mime = Input::file('file')->getMimeType();
$staff_list=$_FILES['file']['tmp_name'];
$linecount = "";
$cols = 5;
$numx ="";
$mimes = array(
'text/csv',
'application/csv',
'text/comma-separated-values',
'application/excel',
'application/vnd.ms-excel',
'application/vnd.msexcel',);
if(empty($staff_list)){
$_SESSION['error']="<font color='#FF0000'>Please choose the csv file to upload</font>";
}
elseif(!in_array($_FILES['file']['type'], $mimes)) {
$_SESSION['error']="<font color='#FF0000'>Invalid file format, Please choose only csv exel format</font>";
}
else{
$staff_list=$_FILES['file']['tmp_name'];
$handle=fopen($staff_list,"r");
// read the first line and ignore it
fgets($handle);
//count number of lines of uploaded csv file
$fh = fopen($staff_list,'rb') or die("ERROR OPENING DATA");
while (fgets($fh) !== false) $linecount++;
fclose($fh);
var_dump($fh); exit();
while(($fileop=fgetcsv($handle,1000,",")) !==false){
$fullname = $fileop[1];
$staff_id = $fileop[0];
$gender = $fileop[2];
$position= $fileop[3];
$department= $fileop[4];
$numx = count($fileop);
$tfulname = trim($fullname);
$lfulname = strtolower($tfulname);
$name_full = explode(' ', $lfulname);
$firstname = $name_full[0];
$middlename = implode(array_slice($name_full, 1, -1));
$lastname = end($name_full);
$phone = '';
$email = '';
$college = '';
if($gender == 'M'){
$gender == 'Male';
}
elseif ($gender =='F') {
$gender == 'Female';
}
DB::beginTransaction();
try{
$staff = new Staff;
$staff->staff_id = $staff_id;
$staff->firstname = $firstname;
$staff->middlename = $middlename;
$staff->lastname = $lastname;
$staff->gender = $gender;
$staff->position = $position;
$staff->phone = $phone;
$staff->email = $email;
$staff->college = $college;
$staff->department = $department;
$staff->save();
}
catch(Exception $e){
Session::put('key','There is a duplicate row in your data,check the file and try again');
}
$cPass = ucfirst($lastname);
$hashed_pass = Hash::make($cPass);
$user = new User;
$user->username = $staff_id;
$user->password = $hashed_pass;
$user->save();
}
if($numx!=$cols){
DB::rollback();
Session::put("error","<font color='#FF0000'>Error,number of columns does not match the defined value,please check your file and try again</font>");
}
elseif(Session::has('key')){
DB::rollback();
Session::put("error","<font color='#FF0000'>Error,duplicate entry detected in your file,please check your file and try again</font>");
}
else{
DB::commit();
Session::put("success","<font color='#0099FF'>Staff list has been uploaded successfully</font>");
}
}
}
when i run above code no data is inserted and i don't get any error. help please
$file = Reader::createFromPath('path-to-your-file');
$result = $file->fetchAll();
foreach($result as $data){
// do database add here
}

Show URL in JSON

I make service from json but i have problem to show url in json, this url http://git.drieanto.net/LagiDimanaAPI/index.php/user/get_following/1 i try to show url from database but in json show "avatar":"http:\/\/git.drieanto.net\/LagiDimanaAPI\/assets\/image\/avatar\/edwin.png".
how to make to show normal url like this http://git.drieanto.net/LagiDimanaAPI/assets/image/avatar/edwin.png
i used codeigniter this the code
function get_following($id_follower) {
if ($this->muser->cek_following($id_follower) == TRUE) {
$query = $this->muser->get_list_id($id_follower);
$feedback["following"] = array();
foreach ($query->result() as $row) {
$query_list_user = $this->muser->get_all_name_user_from_id($row->id_user);
if ($query_list_user->num_rows() > 0) {
$row_ = $query_list_user->row();
$query_status = $this->muser->get_status($row_->id_user);
$query_status->num_rows();
$row2 = $query_status->row();
$response['status'] = $row2->status;
$response['regid'] = $row_->regid;
$response['id_user'] = $row_->id_user;
$response['email'] = $row_->email;
$response['nama'] = $row_->nama;
$response['jenis_kelamin'] = $row_->jenis_kelamin;
$response['tanggal_lahir'] = $row_->tanggal_lahir;
$response['instansi'] = $row_->instansi;
$response['jabatan'] = $row_->jabatan;
$response['avatar'] = $row_->avatar;
$feedback['success'] = 1;
} else {
$feedback['success'] = 0;
}
array_push($feedback["following"], $response);
}
$feedback['success'] = 1;
echo json_encode($feedback);
} else {
$feedback['success'] = 0;
echo json_encode($feedback);
}
}
thanks
It's just escaping the forwardslashes. You can use str_replace($search_char, $replace_char, $string_to_search), to remove them.
$stuff = json_decode($response);
$url = str_replace("\\", "", $stuff['url']);
It does sound like you're not decoding the JSON because I do believe PHP will unescape all of that stuff for you automatically.

No data from the database after the files downloaded

I want to display the data on a particular condition of the table after the user enters the data you want to display.
But always failed to display the data. I am confused where the fault lies.
It looks like the variable $thn = $ _POST['thn'], $bln = $ _POST['bln'], $periode = $ _POST['periode'] is empty.
please help.
I have four files.
Here the codes:
1.absen_xls.php:
<?php
include '../../inc/inc.koneksi.php';
ini_set('display_errors', 1); ini_set('error_reporting', E_ERROR);
include '../../excel/PHPExcel.php';
include '../../excel/PHPExcel/IOFactory.php';
$table = 'absen_karyawan';
$bln = $_POST['bln']; //this not work, I don't know why?
$thn = $_POST['thn']; //this not work, I don't know why?
$periode = $_POST['periode']; //this not work, I don't know why?
$where = "WHERE tahun = '$thn' AND bulan = '$bln' AND periode = '$periode'";
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
$sql = "SELECT namakaryawan,tahun,bulan,periode,absen FROM $table $where";
$query = mysql_query($sql);
// bold
$objPHPExcel->getActiveSheet()->getStyle("A2:C2")->applyFromArray(array("font" => array( "bold" => true)));
// Add some data
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A2', 'No')
->setCellValue('B2', 'Nama')
->setCellValue('C2', 'Kehadiran');
$baris = 3;
$no = 0;
while($row=mysql_fetch_array($query)){
$no = $no +1;
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue("A$baris", $no)
->setCellValue("B$baris", $row['namakaryawan'])
->setCellValue("C$baris", $row['absen']);
$baris = $baris + 1;
}
//border
$border = $baris - 1;
$styleArray = array(
'borders' => array(
'allborders' => array(
'style' => PHPExcel_Style_Border::BORDER_THIN
)
)
);
$objPHPExcel->getActiveSheet()->getStyle('A2:C'.$border)->applyFromArray($styleArray);
unset($styleArray);
//width
$objPHPExcel->getActiveSheet()->getColumnDimension("A")->setWidth(5);
$objPHPExcel->getActiveSheet()->getColumnDimension("B")->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension("C")->setWidth(15);
//align center
$objPHPExcel->getActiveSheet()->getStyle('A2:C'.$border)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
// Rename sheet
$objPHPExcel->getActiveSheet()->setTitle('Absen');
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);
// Redirect output to a client’s web browser (Excel5)
header('Content-Type: application/vnd.ms-excelformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="absen.xlsx"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
exit;
?>
2.ajax.php:
// JavaScript Document
$(document).ready(function(){
$(function(){
$('button').hover(
function() { $(this).addClass('ui-state-hover'); },
function() { $(this).removeClass('ui-state-hover'); }
);
});
$("#tampil_data").load('modul/lap-absen/tampil_data.php');
$("#print").click(function(){
var thn = $("#thn").val();
var bln = $("#bln").val();
var periode = $("#periode").val();
cetakabsen(thn,bln,periode);
});
function cetakabsen(c1,c2,c3){
var thn = c1;
var bln = c2;
var periode = c3;
$.ajax({
type : "POST",
url : "modul/lap-absen/absen_xls.php",
data : "thn="+thn+"&bln="+bln+"&periode="+periode,
success : function(data){
window.open('http://localhost/gudang/modul/lap-absen/absen_xls.php');
}
});
}
});
Change your function to this one:
function cetakabsen(c1,c2,c3){
var thn = c1;
var bln = c2;
var periode = c3;
var data = "thn="+thn+"&bln="+bln+"&periode="+periode;
window.open('http://localhost/gudang/modul/lap-absen/absen_xls.php?'+data);
}
And receive your values like this in absen_xls.php:
$bln = mysql_real_escape_string($_GET['bln']);
$thn = mysql_real_escape_string($_GET['thn']);
$periode = mysql_real_escape_string($_GET['periode']);
PS: Go for mysqli or PDO, dont use the mysql extension.