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;
Related
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;
}
I have an function get() on my controller. This function I use to get data from database and I save it to $data variable.
It's possible to call get() function on another function and I send the $data variable to the view? I want to make two view, one is classic and another one is modern view.
This is my code:
public function get()
{
$data['all'] = $this->genbamodel->getAll();
$data['delay'] = $this->genbamodel->getDelay();
$data['ontime'] = $this->genbamodel->getOntime();
$data['ahead'] = $this->genbamodel->getAhead();
$data['unloading'] = $this->genbamodel->getUnloading();
$data['topdelay'] = $this->genbamodel->getTopDelay();
$data['topahead'] = $this->genbamodel->getTopAhead();
$data['jumlah'] = count($this->genbamodel->getID())+1;
for ($j=1; $j < $data['jumlah']; $j++) {
$datas['lalax'.$j] = $this->genbamodel->getRecord($j);
$data['lala'.$j] = array_reverse($datas['lalax'.$j]);
}
$data['time'] = $this->genbamodel->getTime();
}
public function home_classic()
{
$this->get();
$this->load->view('home_classic',$data);
}
public function home_modern()
{
$this->get();
$this->load->view('home_modern',$data);
}
Hope this will help you :
Your get() method should return $data
public function get()
{
$data['all'] = $this->genbamodel->getAll();
$data['delay'] = $this->genbamodel->getDelay();
$data['ontime'] = $this->genbamodel->getOntime();
$data['ahead'] = $this->genbamodel->getAhead();
$data['unloading'] = $this->genbamodel->getUnloading();
$data['topdelay'] = $this->genbamodel->getTopDelay();
$data['topahead'] = $this->genbamodel->getTopAhead();
$data['jumlah'] = count($this->genbamodel->getID())+1;
for ($j=1; $j < $data['jumlah']; $j++) {
$datas['lalax'.$j] = $this->genbamodel->getRecord($j);
$data['lala'.$j] = array_reverse($datas['lalax'.$j]);
}
$data['time'] = $this->genbamodel->getTime();
return $data;
}
in home_classic() do it like this
public function home_classic()
{
$data = $this->get();
$this->load->view('home_classic',$data);
}
in home_modern() do the same
public function home_modern()
{
$data = $this->get();
$this->load->view('home_modern',$data);
}
for more : https://www.codeigniter.com/user_guide/general/views.html#adding-dynamic-data-to-the-view
I have used more time with Laravel 5.0 on database transaction but when I change to Laravel 5.3.* it not work as I want even I have disabled commit() method all data still continue insert into database.
if ($request->isMethod('post')) {
DB::beginTransaction();
$cats = new Cat();
$cats->parent_id = $this->request->input('category_id');
$cats->status = ($this->request->input('status')) ? $this->request->input('status') : 0;
if ($res['cat'] = $cats->save()) {
$catD = new CategoryDescriptions();
$catD->category_id = $cats->id;
$catD->language_id = 1;
$catD->name = $this->request->input('en_name');
if ($res['cat2'] = $catD->save()) {
$catD2 = new CategoryDescriptions();
$catD2->category_id = $cats->id;
$catD2->language_id = 2;
$catD2->name = $this->request->input('kh_name');
$res['all'] = $catD2->save();
}
}
if ($res) {
//DB::commit();
return $res;
}
return [false];
}
Check this line ($res['cat'] is a boolean):
if($res['cat'] = $cats->save()) {
And this ($res is an array. You compare an array as boolean!):
if($res){
The right condition should be:
$res = array(); // the first line of your method
// .... your http method check, start transaction, etc.
if (!in_array(false, $res, true)) { // check if array doesn't contain 'false values'
DB::commit();
}
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
I am using Joomla! K2 v2.4.1 component on Joomla! v1.5.23. I want to display latest items by category in the item view page, the category being the current one which the current viewed item belongs to.
There are modules which I can use to display most recent items by category but I want to modify item.php and other related files (actually I don't know which files to edit except the item.php template file) to accommodate this requirement. Is it possible to achieve this? If yes, which files do I need to edit and with what code?
Given below is what I think is used to retrieve latest items by category.
class K2ViewLatest extends JView {
function display($tpl = null) {
$mainframe = &JFactory::getApplication();
$params = &JComponentHelper::getParams('com_k2');
$user = &JFactory::getUser();
$cache = &JFactory::getCache('com_k2_extended');
$limit = $params->get('latestItemsLimit',3);
$limitstart = JRequest::getInt('limitstart');
$model = &$this->getModel('itemlist');
$itemModel = &$this->getModel('item');
if($params->get('source')){
$categoryIDs = $params->get('categoryIDs');
if(is_string($categoryIDs) && !empty($categoryIDs)){
$categoryIDs = array();
$categoryIDs[]=$params->get('categoryIDs');
}
$categories = array();
JTable::addIncludePath(JPATH_ADMINISTRATOR.DS.'components'.DS.'com_k2'.DS.'tables');
if(is_array($categoryIDs)){
foreach($categoryIDs as $categoryID){
$category = & JTable::getInstance('K2Category', 'Table');
$category->load($categoryID);
if ($category->published && ($category->access <= $user->get('aid', 0))) {
//Merge params
$cparams = new JParameter($category->params);
if ($cparams->get('inheritFrom')) {
$masterCategory = &JTable::getInstance('K2Category', 'Table');
$masterCategory->load($cparams->get('inheritFrom'));
$cparams = new JParameter($masterCategory->params);
}
$params->merge($cparams);
//Category image
if (! empty($category->image)) {
$category->image = JURI::root().'media/k2/categories/'.$category->image;
} else {
if ($params->get('catImageDefault')) {
$category->image = JURI::root().'components/com_k2/images/placeholder/category.png';
}
}
//Category plugins
$dispatcher = &JDispatcher::getInstance();
JPluginHelper::importPlugin('content');
$category->text = $category->description;
$dispatcher->trigger('onPrepareContent', array ( & $category, &$params, $limitstart));
$category->description = $category->text;
//Category K2 plugins
$category->event->K2CategoryDisplay = '';
JPluginHelper::importPlugin('k2');
$results = $dispatcher->trigger('onK2CategoryDisplay', array(&$category, &$params, $limitstart));
$category->event->K2CategoryDisplay = trim(implode("\n", $results));
$category->text = $category->description;
$dispatcher->trigger('onK2PrepareContent', array ( & $category, &$params, $limitstart));
$category->description = $category->text;
//Category link
$link = urldecode(K2HelperRoute::getCategoryRoute($category->id.':'.urlencode($category->alias)));
$category->link = JRoute::_($link);
$category->feed = JRoute::_($link.'&format=feed');
JRequest::setVar('view', 'itemlist');
JRequest::setVar('task', 'category');
JRequest::setVar('id', $category->id);
JRequest::setVar('featured', 1);
JRequest::setVar('limit', $limit);
JRequest::setVar('clearFlag', true);
$category->name = htmlspecialchars($category->name, ENT_QUOTES);
$category->items = $model->getData('rdate');
JRequest::setVar('view', 'latest');
JRequest::setVar('task', '');
for ($i = 0; $i < sizeof($category->items); $i++) {
if ($user->guest){
$hits = $category->items[$i]->hits;
$category->items[$i]->hits = 0;
$category->items[$i] = $cache->call(array('K2ModelItem', 'prepareItem'), $category->items[$i], 'latest', '');
$category->items[$i]->hits = $hits;
}
else {
$category->items[$i] = $itemModel->prepareItem($category->items[$i], 'latest', '');
}
$category->items[$i] = $itemModel->execPlugins($category->items[$i], 'latest', '');
//Trigger comments counter event
$dispatcher = &JDispatcher::getInstance();
JPluginHelper::importPlugin ('k2');
$results = $dispatcher->trigger('onK2CommentsCounter', array ( & $category->items[$i], &$params, $limitstart));
$category->items[$i]->event->K2CommentsCounter = trim(implode("\n", $results));
}
$categories[]=$category;
}
}
}
$source = 'categories';
$this->assignRef('blocks', $categories);
} else {
$usersIDs = $params->get('userIDs');
if(is_string($usersIDs) && !empty($usersIDs)){
$usersIDs = array();
$usersIDs[]=$params->get('userIDs');
}
$users = array();
if(is_array($usersIDs)){
foreach($usersIDs as $userID){
$userObject = JFactory::getUser($userID);
if (!$userObject->block) {
//User profile
$userObject->profile = $model->getUserProfile($userID);
//User image
$userObject->avatar = K2HelperUtilities::getAvatar($userObject->id, $userObject->email, $params->get('userImageWidth'));
//User K2 plugins
$userObject->event->K2UserDisplay = '';
if (is_object($userObject->profile) && $userObject->profile->id > 0) {
$dispatcher = &JDispatcher::getInstance();
JPluginHelper::importPlugin('k2');
$results = $dispatcher->trigger('onK2UserDisplay', array(&$userObject->profile, &$params, $limitstart));
$userObject->event->K2UserDisplay = trim(implode("\n", $results));
}
$link = K2HelperRoute::getUserRoute($userObject->id);
$userObject->link = JRoute::_($link);
$userObject->feed = JRoute::_($link.'&format=feed');
$userObject->name = htmlspecialchars($userObject->name, ENT_QUOTES);
$userObject->items = $model->getAuthorLatest(0,$limit,$userID);
for ($i = 0; $i < sizeof($userObject->items); $i++) {
if ($user->guest){
$hits = $userObject->items[$i]->hits;
$userObject->items[$i]->hits = 0;
$userObject->items[$i] = $cache->call(array('K2ModelItem', 'prepareItem'), $userObject->items[$i], 'latest', '');
$userObject->items[$i]->hits = $hits;
}
else {
$userObject->items[$i] = $itemModel->prepareItem($userObject->items[$i], 'latest', '');
}
//Plugins
$userObject->items[$i] = $itemModel->execPlugins($userObject->items[$i], 'latest', '');
//Trigger comments counter event
$dispatcher = &JDispatcher::getInstance();
JPluginHelper::importPlugin ('k2');
$results = $dispatcher->trigger('onK2CommentsCounter', array ( & $userObject->items[$i], &$params, $limitstart));
$userObject->items[$i]->event->K2CommentsCounter = trim(implode("\n", $results));
}
$users[]=$userObject;
}
}
}
$source = 'users';
$this->assignRef('blocks', $users);
}
//Look for template files in component folders
$this->_addPath('template', JPATH_COMPONENT.DS.'templates');
$this->_addPath('template', JPATH_COMPONENT.DS.'templates'.DS.'default');
//Look for overrides in template folder (K2 template structure)
$this->_addPath('template', JPATH_SITE.DS.'templates'.DS.$mainframe->getTemplate().DS.'html'.DS.'com_k2'.DS.'templates');
$this->_addPath('template', JPATH_SITE.DS.'templates'.DS.$mainframe->getTemplate().DS.'html'.DS.'com_k2'.DS.'templates'.DS.'default');
//Look for overrides in template folder (Joomla! template structure)
$this->_addPath('template', JPATH_SITE.DS.'templates'.DS.$mainframe->getTemplate().DS.'html'.DS.'com_k2'.DS.'default');
$this->_addPath('template', JPATH_SITE.DS.'templates'.DS.$mainframe->getTemplate().DS.'html'.DS.'com_k2');
//Assign params
$this->assignRef('params', $params);
$this->assignRef('source', $source);
//Set layout
$this->setLayout('latest');
//Display
parent::display($tpl);
}
}
But this file is somehow used to retrieve items in using menu link. I am sorry if this is not the case.
In order to make this work the way you want you would have to modify the K2 item model. The data you want to display (recent items in category) is not currently being pulled from the database so you'd have to change to model to accommodate that. You would be much better off using the K2 content module to pull the most recent items instead. It wouldn't require hacking any core K2 code.
Also, you really need to update your software. K2 is on v2.5.4 and Joomla is on 2.5.1.