Generate pdf of wishlist items in magento - magento

Can anyone guide me how to generate pdf of wishlist items (products) in magento?

Wrap this code in your custom controller.
public function whishlistAction()
{
$session = Mage::getSingleton('customer/session', array('name'=>'frontend'));
if(!$session->isLoggedIn())
{
$this->_redirect(Mage::getUrl('customer/account'));
}
$customer = Mage::getModel('customer/customer')->load($session->getId());
$wishList = Mage::getModel('wishlist/wishlist')->loadByCustomer($customer);
$wishListItemCollection = $wishList->getItemCollection();
$pdf = new Zend_Pdf();
$pageCount = 0;
$collectionPreperedForPagesKey=0;
$collectionPreperedForPages = array();
foreach ($wishListItemCollection as $w)
{
$pageCount = $pageCount+1;
if($pageCount==4)
{
$collectionPreperedForPagesKey=$collectionPreperedForPagesKey+1;
$pageCount=0;
}
$collectionPreperedForPages[$collectionPreperedForPagesKey][]=$w;
}
foreach ($collectionPreperedForPages as $c)
{
$pdf->pages[] = $this->createWhishlistPage($c);
}
$pdfString = $pdf->render();
header("Content-Disposition: attachment; filename=whishlist.pdf");
header("Content-type: application/x-pdf");
echo $pdfString;
exit;
}
public function getImagePath($product)
{
$imageUrl = Mage::getModel('catalog/product_media_config')
->getMediaUrl( $product->getImage() );
$baseDir = Mage::getBaseDir() ;
$withoutIndex = str_replace('index.php/','', Mage::getBaseUrl());
$imageWithoutBase = str_replace($withoutIndex,'' , $imageUrl);
$imagePath = $baseDir.DIRECTORY_SEPARATOR.$imageWithoutBase ;
return $imagePath;
}
public function getImageSizesWithAspectRatio($widthImage,$heightImage,$widthBox,$heightBox)
{
if (($widthBox >= $widthImage) && ($heightBox >= $heightImage))
{
return array('width'=>$widthImage,'height'=>$heightImage);
}
$resizeRatio = 1;
if($widthBox < $widthImage)
{
$resizeRatio = $widthImage/$widthBox;
$widthImage = $widthBox;
}
if($heightBox < $heightImage)
{
if($resizeRatio!=1)
{
$heightImage = $heightImage/$resizeRatio;
}
if($heightImage>$heightBox)
{
$resizeRatio = $heightImage/$heightBox;
$heightImage = $heightBox;
$widthImage = $widthImage/$resizeRatio;
}
}
return array('width'=>$widthImage,'height'=>$heightImage);
}
public function createWhishlistPage($wishListItemCollection)
{
$lightFont = Zend_Pdf_Font::fontWithPath($this->getFont('light'));
$regularFont = Zend_Pdf_Font::fontWithPath($this->getFont('regular'));
$boldFont = Zend_Pdf_Font::fontWithPath($this->getFont('bold'));
$page1 = new Oxidian_Pdf_Helper_Page(Zend_Pdf_Page::SIZE_A4);
$page1->setFillColor(Zend_Pdf_Color_Html::color('#75645E'));
$page1->setLineColor(Zend_Pdf_Color_Html::color('#75645E'));
$page1->setLineWidth(1);
$headerFontSize = 40;
$headerLeft = 20;
$headerTop = $page1->getHeight()-$headerFont-50;
$page1->setFont($lightFont, $headerFontSize);
$contentTopFreeSpace = $headerTop-70;
$contentLeft = 20;
$contentRight = $page1->getWidth()-20;
$page1->drawText('JORDAN', $headerLeft,$headerTop);
$page1->setFont($regularFont, $headerFontSize/2);
$page1->drawText('My dreamboard', $page1->getWidth()/2+40,$headerTop);
$tableHeaderFont = 15;
$page1->setFont($boldFont, $tableHeaderFont);
$columnHeaderPadding = 5;
$productColumnSize = 100;
$previewColumnSize = 100;
$imagePreviewSize = 100;
$previewTableHeaderPosition = $columnHeaderPadding+$productColumnSize+$contentLeft;
$commentTableHeaderPosition = $previewTableHeaderPosition+$previewColumnSize+$columnHeaderPadding;
$productTableHeaderPosition = columnHeaderPadding+$contentLeft;
$commentColumnSize = $page1->getWidth()-$commentTableHeaderPosition ;
$page1->drawText('Product', $productTableHeaderPosition ,$contentTopFreeSpace);
$page1->drawText('Preview', $previewTableHeaderPosition,$contentTopFreeSpace);
$page1->drawText('Comments', $commentTableHeaderPosition,$contentTopFreeSpace);
$paddingRowHeaderFromLine = 5;
$contentTopFreeSpace = $contentTopFreeSpace-$paddingRowHeaderFromLine;
$tableStart = $contentTopFreeSpace;
$contentFont = 15;
$rowHeight= 125;
$page1->setFont($regularFont, $contentFont);
foreach($wishListItemCollection as $w)
{
$page1->drawLine($contentLeft,$contentTopFreeSpace ,$contentRight,$contentTopFreeSpace);
$contentTopFreeSpace =$contentTopFreeSpace- $contentFont-$paddingRowHeaderFromLine;
$product = $w->getProduct();
$product = Mage::getModel('catalog/product')->load($product->getId());
$page1->drawTextBlock($product->getName(), $productTableHeaderPosition,$contentTopFreeSpace,$productColumnSize);
$page1->drawTextBlock($w->getDescription(), $commentTableHeaderPosition,$contentTopFreeSpace,$commentColumnSize);
$imagePath = $this->getImagePath($product);
// Load image
$image = Zend_Pdf_Image::imageWithPath($imagePath);
$imageObj = new Varien_Image($imagePath);
$imageSizes = $this->getImageSizesWithAspectRatio($imageObj->getOriginalWidth(),$imageObj->getOriginalHeight(),$imagePreviewSize,$rowHeight);
$imageBottom = ($rowHeight-$imageSizes['height'])+$contentTopFreeSpace;
$imageLeft = $previewTableHeaderPosition;
$page1->drawImage($image,$imageLeft,$imageBottom-$imageSizes['height'],$previewTableHeaderPosition+$imageSizes['width'],$contentTopFreeSpace);
$contentTopFreeSpace = $contentTopFreeSpace-$rowHeight-$paddingRowHeaderFromLine;
$page1->drawLine($contentLeft,$contentTopFreeSpace ,$contentRight,$contentTopFreeSpace);
};
$tableLineProductsStartX = $previewTableHeaderPosition-$columnHeaderPadding;
$tableLineProductsStartY = $tableStart+$paddingRowHeaderFromLine+$tableHeaderFont;
$tableLineProductsStartX1 = $previewTableHeaderPosition-$columnHeaderPadding;
$tableLineProductsStartY1 = $contentTopFreeSpace;
$tableLinePreviewStartX = $commentTableHeaderPosition-$columnHeaderPadding;
$tableLinePreviewStartY = $tableStart+$paddingRowHeaderFromLine+$tableHeaderFont;
$tableLinePreviewStartX1 = $commentTableHeaderPosition-$columnHeaderPadding;
$tableLinePreviewStartY1 = $contentTopFreeSpace;
$page1->drawLine($tableLineProductsStartX ,$tableLineProductsStartY ,$tableLineProductsStartX1,$tableLineProductsStartY1);
$page1->drawLine($tableLinePreviewStartX ,$tableLinePreviewStartY ,$tableLinePreviewStartX1,$tableLinePreviewStartY1);
return $page1;
}
Source: http://gorrc.blogspot.in/2012/05/magento-print-whishlist-to-pdf.html

Related

laravel controller "Trying to get property 'cm_number' of non-object"

I have a problem in my controller, it doesn't get the value of what declare in getCMnumber, it needs to get the format of getCMNumber to cm_number and automatically save it to the database, but there was an error that says "Trying to get property 'cm_number' of non-object"
this my controller
public function store(Request $request)
{
try {
$userEmployment = UserEmployment::where('emp_xuser',Auth::user()->status_xuser)->first();
$stages = "UR,DH,SO,ITOPS,ITSA,ITSEC";
$cm = new ChangeManagement;
$cm->cm_user = Auth::user()->status_xuser;
$cm->cm_number = self::getCMNumber();
$cm->cm_company = $request->xcompany;
$cm->cm_projectname = $request->xproject;
$cm->cm_requesttype = $request->xcmtype;
$cm->cm_userdep = $request->xdepartment;
$cm->cm_depthead = $userEmployment->emp_xdepartment;
$cm->cm_remarks = $request->xremarks;
$cm->cm_status = "Open";
$cm->cm_priority = "Standard";
$cm->cm_stages = $stages;
$cm->cm_current = "UR";
$cm->cm_Requested = $request->xdateneeded;
$cm->save();
$dh_email = "";
$stgray = explode(',', $stages);
$stagecount = count($stgray);
$count = 0;
while($count<$stagecount) {
$cmstg_stage = $stgray[$count];
switch($cmstg_stage){
case "UR":
$cmstg_stageuser = Auth::user()->status_xuser;
break;
case "DH":
$cmstg_user = self::getdephead($userEmployment->emp_xdepartment);
$dh_email = $cmstg_user;
break;
case "SO":
$cmstg_user = self::getdephead('System Owner');
break;
case "ITOPS":
$cmstg_user = self::getdephead('IT-Operations');
break;
case "ITSA":
$cmstg_user = self::getdephead('System Administrator');
break;
case "ITSEC":
$cmstg_user = self::getdephead('IT-System Administrator');
break;
}
$cmstg = new ChangeManangementStages;
$cmstg->prstg_prnumber = $cm->cm_number;
$cmstg->prstg_stage = $cmstg_stage;
$cmstg->prstg_stageuser = $cmstg_stageuser;
$cmstg->save();
$count++;
}
$firewallcount = 0;
while ($firewallcount < count($request->pr_item)) {
$firewall = new FirewallRequest;
$firewall->cm_fw_number =$cm->cm_number;
$firewall->fw_number =self::getfirewallNumber($cm->cm_number);
$firewall->fw_user =Auth::user()->status_xuser;
$firewall->fw_stage =$stages;
$firewall->fw_purpose =$request->xpurpose[$firewallcount];
$firewall->fw_expected_result =$request->xresult[$firewallcount];
$firewall->fw_server_instance =$request->xinstance[$firewallcount];
$firewall->fw_src_servername =$request->xsrcname[$firewallcount];
$firewall->fw_src_ip =$request->xsrcip[$firewallcount];
$firewall->fw_dest_servename =$request->xdestname[$firewallcount];
$firewall->fw_dest_ip =$request->xdestip[$firewallcount];
$firewall->fw_port_services =$request->xprsr[$firewallcount];
$firewall->fw_remarks =$request->xremarks[$firewallcount];
$firewall->fw_date_requested =$request->xdatecr[$firewallcount];
$firewall->save();
$firewallcount++;
}
if($request->hasFile('filename'))
{
$path = storage_path('ChangeManagement/'.$cm->cm_number);
if(!File::exists($path)) {
Storage::disk('fw_upload')->makeDirectory($cm->cm_number);
}
$uploadcount = 0;
while ($uploadcount < count($request->filename)) {
$filename = $request->filename[$uploadcount];
$prupload = new ChangeManagementUploads;
$prupload->pr_number =$pr->pr_number;
$prupload->filename =$filename->getClientOriginalName();
$prupload->save();
Storage::disk('fw_upload')->put( '/'.$cm->cm_number.'/'.$filename->getClientOriginalName(),File::get($filename));
$uploadcount++;
}
}
alert()->success('Request submitted',$cm->cm_number.' has been submitted for review and approval')
->showConfirmButton(
$btnText = '<a class="add-padding" href="'.route('cm.show',$cm->cm_number).'">View Request</a>', // here is class for link
$btnColor = '#fa0031',
['className' => 'no-padding'],
)->autoClose(false);
return redirect()->back();
}
catch (\Throwable $th)
{
alert()->error($th->getMessage())->showConfirmButton('Return', '#fa0031');
return redirect()->back();
}
getcmNUmber
public static function getCMNumber() {
$cm = ChangeManagement::orderBy('cm_id','desc')->first();
$last_ticket = $cm->cm_number;
$tick_date = substr($last_ticket, 0, 10);
$tick_date_now = date('Y-m-d');
$tick_pre = "-CM-";
$tick_start = "000";
$tick_num = substr($last_ticket, 14, 17);
if ($tick_date == $tick_date_now) {
$tick_d1 = $tick_date;
$tick_d2 = $tick_pre;
$tick_dx = $tick_num + 1;
$tick_d3 = str_pad($tick_dx, 3, '0', STR_PAD_LEFT);
} else {
$tick_d1 = $tick_date_now;
$tick_d2 = $tick_pre;
$tick_d3 = $tick_start;
}
return $tick_dt = $tick_d1.$tick_d2.$tick_d3;
}
Just try this:
public static function getCMNumber()
{
$cm = ChangeManagement::whereNotNull('cm_number')->orderBy('cm_id', 'desc')->first();
if (!$cm) {
return null;
}
$last_ticket = $cm->cm_number;
$tick_date = substr($last_ticket, 0, 10);
$tick_date_now = date('Y-m-d');
$tick_pre = "-CM-";
$tick_start = "000";
$tick_num = substr($last_ticket, 14, 17);
if ($tick_date == $tick_date_now) {
$tick_d1 = $tick_date;
$tick_d2 = $tick_pre;
$tick_dx = $tick_num + 1;
$tick_d3 = str_pad($tick_dx, 3, '0', STR_PAD_LEFT);
} else {
$tick_d1 = $tick_date_now;
$tick_d2 = $tick_pre;
$tick_d3 = $tick_start;
}
return $tick_dt = $tick_d1 . $tick_d2 . $tick_d3;
}

issue with reduce time to open in laravel

I am making a report in which user can check due balance of them invoice day wise like between 1-30 days how many amount due. between 30-60 days how many amount due etc for that I have make below function.
I don't know how can I optimize this process time.
public function yajraAgingARSummaryByDueDate()
{
$customerData = GenerateInvoice::select('orders.customer_id','customers.first_name', 'customers.last_name','customers.terms','customers.account_id','customers.account_suffix','invoice.due_date','invoice.invoice_number')
->leftJoin('orders','orders.id','=','invoice.order_id')
->leftJoin('customers', 'customers.id', 'orders.customer_id')
->whereDate('invoice.due_date','<=',date('Y-m-d'))
->whereNotNull('orders.customer_id')
->where('invoice.is_invoice_paid','=','no')
->whereNull('invoice.deleted_at')
->groupBy('orders.customer_id')
->get();
$resultArr = [];
if(count($customerData))
{
foreach($customerData as $key => $row)
{
$current = 0;
$b_1_30 = 0;
$b_31_60 = 0;
$b_61_90 = 0;
$b_over_90 = 0;
$total_ar = 0;
$balance = 0;
$invoiceData = GenerateInvoice::select('invoice.id')
->leftJoin('orders','orders.id','=','invoice.order_id')
->where('orders.customer_id',$row['customer_id'])
->whereDate('invoice.due_date','<=',date('Y-m-d'))
->whereNotNull('orders.customer_id')
->whereNull('invoice.deleted_at')
->where('invoice.is_invoice_paid','=','no')
->get();
if(count($invoiceData))
{
foreach($invoiceData as $row1)
{
$data = GenerateInvoice::select(DB::raw("abs(DATEDIFF(STR_TO_DATE(due_date, '%Y-%m-%d'),CURDATE())) AS Days"),'orders.total_order_value','payments.payment_amount')
->selectRaw(' (select sum(auto_cash_distributions.payment_amount) from auto_cash_distributions where auto_cash_distributions.order_id = invoice.order_id and payment_amount is not null ) as acd_payament_amount ')
->leftJoin('orders','orders.id','=','invoice.order_id')
->leftJoin('payments','payments.order_id','=','orders.id')
->where('invoice.id',$row1['id'])
->whereNotNull('orders.customer_id')
->whereNull('invoice.deleted_at')
->whereNull('payments.deleted_at')
->where('invoice.is_invoice_paid','=','no')
// ->groupBy('payments.invoice_id')
->first();
$days = $data['Days'];
$acd_payament_amount = !(empty($data['acd_payament_amount'])) ? $data['acd_payament_amount'] : 0;
$payment_amount = $data['payment_amount'] + $acd_payament_amount;
$amount = $data['total_order_value'] - $payment_amount;
// H 30/12
$amount = $amount;
$balance =$balance + $amount;
$total_ar = $total_ar + $amount;
// $total_ar = $amount;
if($days>90)
{
$b_over_90 = $b_over_90 + $amount;
}
else if($days <=90 && $days>=61)
{
$b_61_90 = $b_61_90 + $amount;
}
else if($days <=60 && $days>=31)
{
$b_31_60 = $b_31_60 + $amount;
}
else if($days <=30 && $days>=1)
{
$b_1_30 = $b_1_30 + $amount;
}
else
{
$current = $current + $amount;
}
}
}
$resultArr[$key]['account_id'] = $row['account_id'];
$resultArr[$key]['account_suffix'] = $row['account_suffix'];
$resultArr[$key]['first_name'] = $row['first_name'];
$resultArr[$key]['terms'] = $row['terms'];
$resultArr[$key]['due_date'] = $row['due_date'];
$resultArr[$key]['invoice_number'] = $row['invoice_number'];
$resultArr[$key]['balance'] = number_format($balance,2,'.','');
$resultArr[$key]['current'] = number_format($current,2,'.','');
$resultArr[$key]['b_1_30'] = number_format($b_1_30,2,'.','');
$resultArr[$key]['b_31_60'] = number_format($b_31_60,2,'.','');
$resultArr[$key]['b_61_90'] = number_format($b_61_90,2,'.','');
$resultArr[$key]['b_over_90'] = number_format($b_over_90,2,'.','');
$resultArr[$key]['total_ar'] = number_format($total_ar,2,'.','');
}
}
return Datatables::of($resultArr)
->addColumn('due_date',function($sql){
return !empty($sql['due_date']) ? date(get_config('date_format'),strtotime($sql['due_date'])) : '';
})
->addIndexColumn()
->rawColumns(['due_date'])
->make(true);
}
but this code is taking to much time to open. can anybody help me to optimize this code?

how to store the primary key values to the foreign key at same time of save

I am new to the laravel and trying to store the primary key values of patientid to the foreign key of patient_id in address table
$patdet = $request->patdet;
foreach ($patdet as $patdets) {
$pdet = new Patient();
$pdet->fname = $patdets['fname'];
$pdet->mname = $patdets['mname'];
$pdet->lname = $patdets['lname'];
$pdet->age = $patdets['age'];
$pdet->blood_group = $patdets['bloodgroup'];
$pdet->gender = $patdets['gender'];
$ptid = $pdet->save();
}
$addr = $request->address[0];
$address = new Address;
$address->gps_lat = $addr['gps_lat'];
$address->gps_log = $addr['gps_long'];
$address->house_no = $addr['houseno'];
$address->zipcode = $addr['zip_code'];
$address->street = $addr['street'];
$address->chowk = $addr['chowk'];
$address->city = $addr['city'];
$address->patient_id = $patid->id;
$address->save();
I know that $ptid is a local variable and cannot be used in address table, so how can I store it in address table?
Try the following and ask me if it doesn't work
foreach($request->patdet as $key => $patdets)
{
$pdet = new Patient();
$pdet->fname = $patdets['fname'];
$pdet->mname = $patdets['mname'];
$pdet->lname = $patdets['lname'];
$pdet->age = $patdets['age'];
$pdet->blood_group = $patdets['bloodgroup'];
$pdet->gender = $patdets['gender'];
$pdet->save();
$addr = $request->address[$key];
if($pdet->id > 0 && !empty($addr)){
$addrss = new Address;
$addrss->gps_lat = $addr['gps_lat'];
$addrss->gps_log = $addr['gps_long'];
$addrss->house_no = $addr['houseno'];
$addrss->zipcode = $addr['zip_code'];
$addrss->street = $addr['street'];
$addrss->chowk = $addr['chowk'];
$addrss->city = $addr['city'];
$addrss->patient_id = $pdet->id;
$addrss->save();
}
}
Try the following
$patArray = $request->patdet;
$addressArray = $request->address;
$pId = array();
foreach($patArray as $key => $patdets){
$pdet = new Patient();
$pdet->fname = $patdets['fname'];
$pdet->mname = $patdets['mname'];
$pdet->lname = $patdets['lname'];
$pdet->age = $patdets['age'];
$pdet->blood_group = $patdets['bloodgroup'];
$pdet->gender = $patdets['gender'];
$pdet->save();
$pId[$key] = ($pdet->id > 0) ? $pdet->id : 0;
}
foreach($addressArray as $key => $addr){
$addrss = new Address;
$addrss->gps_lat = $addr['gps_lat'];
$addrss->gps_log = $addr['gps_long'];
$addrss->house_no = $addr['houseno'];
$addrss->zipcode = $addr['zip_code'];
$addrss->street = $addr['street'];
$addrss->chowk = $addr['chowk'];
$addrss->city = $addr['city'];
$addrss->patient_id = array_key_exists($key ,$pId) ? $pId[$key] : 0;
$addrss->save();
$i++;
}

when i store function submit from create blade i get this error "Array to string conversion"

This is my controller in store function save for ministries table.
$ministries = new Ministry;
$ministries->country_id = $request->country_name;
$ministries->township_id = $request->township_name;
$ministries->city_id = $request->city_name;
$ministries->division_id = $request->division_name;
$ministries->ministryCode = $request->ministry_code;
$ministries->ministryName = $request->ministry_name;
$ministries->ministryNameMm = $request->ministry_mm_name;
$ministries->address = $request->address;
$ministries->phone = $request->phone;
$ministries->fax = $request->fax;
$ministries->email = $request->email;
$ministries->website = $request->website;
$ministries->save();
$ministries_id = $ministries->id;
this is save for other table(contact_persons)
for ($i=0; $i < count($request->position_id); $i++) {
$contact_persons = new ContactPerson();
$contact_persons->responsibility_id = $request->responsibility_id[$i];
$contact_persons->position_id = $request->position_id[$i];
$contact_persons->country_id = $request->email[$i];
$contact_persons->township_id = $request->email[$i];
$contact_persons->city_id = $request->email[$i];
$contact_persons->division_id = $request->email[$i];
$contact_persons->customer_id = $request->email[$i];
$contact_persons->address = $request->email[$i];
$contact_persons->home_phone = $request->email[$i];
$contact_persons->mobile = $request->email[$i];
$contact_persons->email = $request->email[$i];
$contact_persons->ministries_id = $ministries_id;
$contact_persons->save();
}
please how to solve and thanks.

Strange error session get destroyed

I have a problem when I execute controller method it process controller code but destroy all session including user.
So after process thus controller and I try to open home page, there is no logged in account.
I'm sure no destroy session code, nor logout code in my controller. and I can say this is not about session expired.
I don't know what wrong is this about code, yii2 configuration or logic, but is someone have similar problem in past?
Hope you can guide me to solve this problem.
If you need more information, please let me know.
This not related to code maybe, but here is my controller code.
<?php
namespace frontend\controllers;
use Yii;
use common\models\TbCustomer;
use yii\web\Controller;
use common\models\Model;
use common\models\VwProdukAgent;
use common\models\TbCart;
use yii\helpers\VarDumper;
use common\models\VwProduk;
use yii\data\ActiveDataProvider;
use common\models\VwProdukCustomer;
use common\models\TbCustomerShipment;
use common\component\BeoHelper;
use common\models\TbProdukEkspedisi;
use common\models\TbKota;
use yii\helpers\Url;
/**
* CustomerController implements the CRUD actions for TbCustomer model.
*/
class Pengiriman1Controller extends Controller
{
public function beforeAction($action)
{
Yii::$app->timeZone = 'Asia/Jakarta';
if(Yii::$app->user->isGuest)
{
//$url = Url::to([['home'],'message'=>'Anda Harus Login Terlebih Dahulu']);
\Yii::$app->getSession()->setFlash('message', \Yii::t('app', 'Anda Harus Login Terlebih Dahulu'));
$this->goHome();
return FALSE;
}
//if ($action->id == 'my-method') {
$this->enableCsrfValidation = false;
// }
return parent::beforeAction($action);
}
public function actionIndex()
{
//get alamat customer
//$lsalamat = array();
if(!\Yii::$app->user->isGuest)
{
BeoHelper::refreshCart();
//cek cart kosong atau tidak
if(isset(\Yii::$app->session['produkcart']))
{
$lsproduk = \Yii::$app->session['produkcart'];
if (count($lsproduk)<1)
{
\Yii::$app->getSession()->setFlash('message',"silahkan berbelanja terlebih dahulu");
return $this->redirect(Url::to(['cart/index']));
}
}
$customer_id = Yii::$app->user->id;
$message = '';
$model = null;
if(\Yii::$app->request->post('opsi_alamat',null)!=null)
{
$opsi_pengiriman = \Yii::$app->request->post('opsi_alamat',null);
//return $opsi_pengiriman;
if($opsi_pengiriman == 'new')
{
$model = new TbCustomerShipment();
$model->load(Yii::$app->request->post());
$model->customer_id = $customer_id;
if($model->save())
{
\Yii::$app->session['shipemenadd'] = $model;
//get kurir preselected
if(isset(\Yii::$app->session['produkcart']))
{
$hargatotal = 0;
$lsproduk = \Yii::$app->session['produkcart'];
$i=0;
$lsprodukedit = array();
foreach ($lsproduk as $produk)
{
//pre selected
$pengiriman = TbProdukEkspedisi::find()->where(['produk_id' => $produk->produk_id])->one();
$kode = $pengiriman->idEkspedisi->kode_ekspedisi;
$service = $pengiriman->idEkspedisi->service;
$produk->kurir = $kode;
$kota_asal = TbKota::find()->where("kota_id = $produk->kota_id ")->one();
$kota_tujuan = TbKota::find()->where("kota_id = $model->kota_id ")->one();
$berat_produk = $produk->kuantitas *$produk->berat_produk;
$berat_produk = round($berat_produk);
$result = BeoHelper::getCostEkspedisi($kota_asal->api_id, $kota_tujuan->api_id, $berat_produk, $kode,$service,$produk->produk_id);
if(count($result)!=0)
{
$produk->harga_kurir = $result[0]['value'];
$produk->estimasi_sampai = $result[0]['etd'];
}
else
{
$message = "pilihan kurir untuk lokasi tersebut tidak tersedia";
}
//return VarDumper::dump($result);
$lsprodukedit[$i++] = $produk;
$hargatotal += $produk->kuantitas * $produk->harga_agen;
}
\Yii::$app->session['produkcart'] = $lsprodukedit;
}
if(isset(Yii::$app->session['shipemenadd'])){
return "exists";
}else{
return "doesn't exist";
}
//return $this->redirect(['pengiriman2/index','message'=>$message]);
//print_r(Yii::$app->session['shipemenadd']);
}
//else
//{
// VarDumper::dump($model);
//}
}
else
{
$pengiriman_selected = TbCustomerShipment::find()->where("customer_shipment_id = $opsi_pengiriman")->one();
\Yii::$app->session['shipemenadd'] = $pengiriman_selected;
if(isset(\Yii::$app->session['produkcart']))
{
$hargatotal = 0;
$lsproduk = \Yii::$app->session['produkcart'];
$i=0;
$lsprodukedit = array();
foreach ($lsproduk as $produk)
{
//pre selected
$pengiriman = TbProdukEkspedisi::find()->where("produk_id =$produk->produk_id")->one();
$kode = $pengiriman->idEkspedisi->kode_ekspedisi;
$service = $pengiriman->idEkspedisi->service;
$produk->kurir = $kode;
//get kota id rajaongkir
$kota_asal = TbKota::find()->where("kota_id = $produk->kota_id ")->one();
$kota_tujuan = TbKota::find()->where("kota_id = $pengiriman_selected->kota_id ")->one();
//$result = BeoHelper::getCostEkspedisi($kota_asal->api_id, $kota_tujuan->api_id, $produk->berat_produk, $kode,$service);
//return VarDumper::dump($result);
//if(count($result)!=0)
//{
//$produk->harga_kurir = $result[0]['value'];
//$produk->estimasi_sampai = $result[0]['etd'];
$produk->harga_kurir = 0;
$produk->estimasi_sampai = 0;
//}
//else
//{
// $message = "pilihan kuriri untuk lokasi tersebut tidak tersedia";
//}
$lsprodukedit[$i++] = $produk;
$hargatotal += $produk->kuantitas * $produk->harga_agen;
}
\Yii::$app->session['produkcart'] = $lsprodukedit;
}
return $this->redirect(['pengiriman2/index','message'=>$message]);
}
}
$lsalamat = TbCustomerShipment::find()->where(['customer_id'=>$customer_id])->all();
if(count($lsalamat)==0)
//insert to tb shipment
{
$datacustomer = TbCustomer::find()->where(['customer_id'=>$customer_id])->one();
$newalamat = new TbCustomerShipment();
$newalamat->customer_id = $customer_id;
$newalamat->kota_id = $datacustomer->kota_id;
$newalamat->kecamatan_id = $datacustomer->kecamatan_id;
$newalamat->negara_id = $datacustomer->negara_id;
$newalamat->propinsi_id = $datacustomer->propinsi_id;
$newalamat->alamat = $datacustomer->alamat;
$newalamat->shipment_name = "Alamat Rumah";
$newalamat->penerima = $datacustomer->nama;
$newalamat->hp_penerima = $datacustomer->hp;
$newalamat->save();
}
$lsalamat = TbCustomerShipment::find()->where(['customer_id'=>$customer_id])->all();
return $this->render('index',['lsalamat'=>$lsalamat,'newalamat'=> $model]);
}
else
{
return $this->goHome();
}
}
}
here is the problem
\Yii::$app->session['shipemenadd'] = $model;
it should
$currentTbCustomerShipment = TbCustomerShipment::find()->where(['customer_user_id' => $model->customer_user_id])->one(); //find latest object
Yii::$app->session['shipemenadd'] = $currentTbCustomerShipment;

Resources