How to get current cart items for logged in user - magento-1.9

Following is my code:-
try
{
$store = $this->_getStore();
Mage::app()->setCurrentStore($store->getId());
$customer_ID = 3;
$customer = Mage::getModel('customer/customer')->load($customer_ID);
// load quote by customer
$quote = Mage::getModel('sales/quote')->loadByCustomer($customer_ID);
$quote->assignCustomer($customer);
$product = Mage::getModel('catalog/product')
// set the current store ID
->setStoreId(Mage::app()->getStore()->getId())
// load the product object
->load(3);
// Add Product to Quote
$quote->addProduct($product,1);
// Calculate the new Cart total and Save Quote
$quote->collectTotals()->save();
return json_encode(array("", $quote->getId()));
}catch(Exception $e)
{
return $e->getMessage();;
}
Using this the product is getting added in cart successfully and returning quote_id, but using this id i want to fetch current cart items details for currently logged in user.

To get cart item details:
$quote = Mage::helper('checkout/cart')->getCart()->getQuote();
$value = [];
foreach ($quote->getAllItems() as $item) {
$value[]= array (
'id' => $item->getSku(),
'quantity' => $item->getQty(),
'price' => $item->getParentItemId()? $item->getParentItem()->getPrice(): $item->getPrice()
);
}

Related

Last inserted id Inside transaction with Lumen/Laravel

How can I get the last inserted id
I use the following code which works:
DB::insert("INSERT INTO members (name,email)values($name,$email)");
$lastID = DB::getPdo() -> lastInsertId();
But the following code doesn't give me the last inserted id.
DB::transaction(function () {
$result = DB::insert("INSERT INTO members (name,email)values($name,$email)");
$lastID = DB::getPdo() -> lastInsertId();
}, 5);
return $lastID;
Even when I use the variable($lastID) outside the transaction it still doesn't work.
What am I doing wrong here?
When using the query builder, Laravel has the function insertGetId which inserts the row and returns the newly created id.
$lastid = DB::table('members')->insertGetId(['name' => $name, 'email' => $email]);
Please see sample code below. Hope it helps.
public function testModel($data) {
$id = DB::transaction(function() use ($data) {
$record_id = DB::table('users')->insertGetId($data);
DB::update('update users set votes = 100 where name = ?', ['John']);
return $record_id;
});
return $id; // this will return the last inserted id which is the $record_id inside the DB::transaction
}
You can get it easily:
$last_id = DB::table('members')->insertGetId(['name => $name, 'email => $email]);
this worked for me
public function testModel($data) {
$last_id = DB::transaction(function() use ($data) {
Table::create($data);
return DB::getPdo()->lastInsertId();
});
return $last_id; // this will return the last inserted id
}
The trick should be quite simple if you use Model. Let's assume you've Member model. So when you try to insert record it returns the inserted record in response.
/** Insert record **/
$member = Member::create(['name' => $name, 'email' => $email])
/** your last inserted id will be in $member **/
$lastInsertedId = $member->id
Hope this works for you.

Yii2 - update record with child records

I have a form which allows the user to add many child records, in my case they are called "Items". When updating the master record, the user can add, edit or delete child records. Everything works fine, but I am looking for a better way to do this.
Currently, in my Update action, I first delete any existing child records. I then save all the child records from the form post.
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
// first delete all existing child records
Item::deleteAll(['parent_id' => $model->id]);
// get the new set of posted Items
$items = Yii::$app->request->post('Item');
if (!empty($items) && is_array($items)) {
// save each Item
foreach ($items as $index => $values) {
$item = new Item();
$item->attributes = $values;
$item->parent_id = $model->id;
$item->save();
}
}
return $this->redirect(['view', 'id' => $model->id]);
}
return $this->render('update', [
'model' => $model,
]);
}
Form View:
<form method="post" action="">
<?php foreach ($model->items as $index => $item): ?>
<?php echo Html::activeTextInput($item, "[$index]name"); ?>
<!-- Example output -->
<!-- <input id="item-0-name" name="Item[0][name]" value="Test" type="text"> -->
Remove this Item
<?php endforeach; ?>
<button type="submit">Submit</button>
</form>
Add a new Item
In the above $model->items refers to the relation in the parent model:
public function getItems()
{
return $this->hasMany(Item::className(), ['parent_id' => 'id']);
}
When the user clicks "Add a new Item" it simply uses JavaScript to clone the last item and replaces its index with the next value.
Very often, the user does not change any child records. So the process of deleting and re-adding child records in that case is pointless.
What I want to know is, is there a way I can intelligently handle this? For example:
Only delete child records if they do not exist in the POSTed Item array
Only edit the child records if they are different to the ones in the database
Only add new child records that do not currently exist in the database
Otherwise leave everything as it is
You can use indexBy() to define your relation to index related items by their ID:
public function getItems() {
return $this->hasMany(Item::class, [/*...*/])->indexBy('id');
}
Then you can check if record with this ID already exist and do update/delete/create action:
// get the new set of posted Items
$items = Yii::$app->request->post('Item');
$existing = $model->items;
if (!empty($items) && is_array($items)) {
// save each Item
foreach ($items as $index => $values) {
if (!isset($existing[$index])) {
// create new item
$item = new Item();
$item->attributes = $values;
$item->parent_id = $model->id;
$item->save();
} else {
// update existing
$existing[$index]->attributes = $values;
$existing[$index]->save();
// remove from $existing array as already processed
unset($existing[$index]);
}
}
// right now $existing has only existing and not updated items - it means
// that they're not available in POST data so we should remove it
foreach ($existing as $item) {
$item->delete();
}
}

Codeigniter - insert batch - multiple inputs with same name

I am trying to insert a batch of rows for wholesale, dealer and customer
Note : i am using 'append' to add row of inputs but then they carry the same input names.
I am trying to apply this to wholesale first but it is not happening
when i add another row to my wholesale input list it is taking only one row(my last row) input and my other row of inputs are discarded. the var_dump of array reveals that.
This is my controller file
$range = $this->input->post('wrange1');
$usertype = $this->input->post('wusertype');
$uom = $this->input->post('wuom1');
$price = $this->input->post('wamount1'); //array of price
$vat = $this->input->post('wvat1');
var_dump($range);// i am getting only one output
$updateArray = [];
for($x = 0; $x < sizeof($price); $x++){
$updateArray[$x] = array(
'product_id'=> $id,
'range' => $range[$x],
'usertype' => $usertype[$x],
'uom' => $uom[$x],
'price' => $price[$x],
'vat' => $vat[$x]
);
}
$this->productmodel->updatepricinglist($updateArray);
This is my model file:
public function updatepricinglist($updateArray) {
$this->db->insert_batch('product_pricing', $updateArray);
}
use insert operation inside for loop.and if you get the array in all the field then you have to use array of index like in for loop , since you said you get only one range at output then don't use array of index in loop.
$range = $this->input->post('wrange1');
$usertype = $this->input->post('wusertype');
$uom = $this->input->post('wuom1');
$price = $this->input->post('wamount1'); //array of price
$vat = $this->input->post('wvat1');
var_dump($range);// i am getting only one output
for($x = 0; $x < sizeof($price); $x++){
$updateArray = array(
'product_id'=> $id,
'range' => $range,
'usertype' => $usertype[$x],
'uom' => $uom[$x],
'price' => $price[$x],
'vat' => $vat[$x]
);
$this->productmodel->updatepricinglist($updateArray);
}

'Cannot create an empty shipment' while trying to create shipment in magento

I am trying to create shipment and adding tracking number after placing an order,but i am getting an error like Cannot create an empty shipment. when i search through google i got one of the reason for this is item quantity is null, but what i used below is returning the exact quantities of products ordered.
$itemQty = $order->getItemsCollection()->count();
I don't know exactly it is only the reason for that error. what i done mistake? anybody knows please help me on this.
public function salesOrderInvoiceShipmentCreate($observer)
{
// $order = $observer->getEvent()->getOrder();
//$order = Mage::getModel('sales/order')->loadByIncrementId($orderId);
$order_id = $observer->getData('order_ids');
$order = Mage::getModel('sales/order')->load($order_id);
$token = '3acb6561b04117c6cbe3552c90f1d6815507e257';
$waybill_url = 'https://track.delhivery.com/waybill/api/fetch/json/?token='.$token.'&cl=GEECHOO';
$waybill = file_get_contents($waybill_url);
Mage::log($order, Zend_Log::INFO, 'order.log', true);
if (!$order->getId()) {
Mage::throwException('Order does not exist, for the Shipment process to complete');
}
if ($order->canShip()) {
try {
// $shipment = Mage::getModel('sales/service_order', $order)
// ->prepareShipment($this->_getItemQtys($order));
$itemQty = $order->getItemsCollection()->count();
$shipment = Mage::getModel('sales/service_order', $order)->prepareShipment($itemQty);
$shipmentCarrierCode = '';
$shipmentCarrierTitle = '';
$arrTracking = array(
'carrier_code' => isset($shipmentCarrierCode) ? $shipmentCarrierCode : $order->getShippingCarrier()->getCarrierCode(),
'title' => isset($shipmentCarrierTitle) ? $shipmentCarrierTitle : $order->getShippingCarrier()->getConfigData('title'),
'tracking_number' => $waybill,
);
$track = Mage::getModel('sales/order_shipment_track')->addData($arrTracking);
$shipment->addTrack($track);
// Register Shipment
$shipment->register();
// Save the Shipment
$this->_saveShipment($shipment, $order);
// Finally, Save the Order
$this->_saveOrder($order);
} catch (Exception $e) {
throw $e;
}
}
}
Try this for order item quantity
$quote = Mage::helper('checkout/cart')->getCart()->getQuote();
$value = [];
foreach ($quote->getAllItems() as $item) {
$value[]= array (
'id' => $item->getSku(),
'quantity' => $item->getQty(),
}

Add items to query result - Laravel

I'm slowly moving my API to Laravel and coming to grips with the Query Builder.
I'm trying to achieve this:
$data = array();
$query = "SELECT * FROM blog_posts WHERE post_type = 3 AND post_status = 1 ORDER BY id DESC";
$result = mysqli_query($cms_connection, $query);
if($result) {
while($row = mysqli_fetch_assoc($result)) {
$row['post_seo'] = seoUrl($row['post_title']);
$data['data'][] = $row;
}
$data['success'] = true;
$response = json_encode($data);
}
My problem isn't necessarily with getting the query, but as you can see I'm using the result of the query and then injecting it back into the final array.
So essentially, I'm fetching rows, transforming some of the attributes fetched, and then injecting the newly created attributes into the resulting array.
This is what I have so far:
$posts = DB::table('blog_posts')
-where(['post_type' => 1, 'post_status' => 1)
->orderBy('id', 'desc')
->take(5)->get();
You could do it this way
// get your data (yours part of code)
$posts = DB::table('blog_posts')
-where(['post_type' => 1, 'post_status' => 1])
->orderBy('id', 'desc')
->take(5)->get();
// add post_seo
foreach ($posts as $post) {
$post->post_seo = seoUrl($post->post_title);
}
// set result array
$data['data'] = $posts;
$data['success'] = true;
// response
$response = response()->json($data);
// or in case you want to return it just
return response()->json($data);
EDIT
You could do it also a bit better, using Eloquent. If you have such model (you need to add valid namespaces and use statements)
class BlogModel extends Model
{
protected $table = 'blog_posts';
protected $appends = ['post_seo'];
public function getPostSeoAttribute($value)
{
return seoUrl($this->post_title);
}
}
(added accessor to post_seo attribute and added post_seo to results when converting to array)
You can now do (shorter syntax than in previous example):
// get your data
$posts = BlogPost::where('post_type',1)
->where('post_status',1)
->orderBy('id', 'desc')
->take(5)->get();
// response
$response = response()->json(['data' => $posts, 'success' => true]);