how to update session data in Laravel (session cart) - shopping-cart

i am making an e commerce shopping cart where i have used session to store cart item. But the problem is when i am trying to update (increase or decrease) cart item's quantity i am not getting the accurate total price. i am trying to update the whole cart not by single item...
This is update function in cart Model
public function update($id, $qty){
//reset qty and price in the cart
$this->totalQty -= $this->items[$id]['qty'];
$this->totalPrice -= $this->items[$id]['price'] * $this->items[$id]['qty'];
//add item with new qty
$this->items[$id]['qty'] = $qty;
//total price and total qty in cart
$this->totalQty += $qty;
$this->totalPrice += $this->items[$id]['price'] * $qty;
}
This is update function in controller
//update cart
public function updateQty(Request $request){
$id = $request->item_id;
$qty = $request->qty;
$oldCart = Session::has('cart') ? Session::get('cart') : null;
$cart = new Cart($oldCart);
for ($i=0; $i <count($id) ; $i++) {
$cart->update($id[$i], $qty[$i]);
Session::put('cart', $cart);
}
return redirect()->back();
}
The cart
cart image in browser

This should go outside the for loop.
Session::put('cart', $cart);
I will be surprised if this solves your problem but definitely something that you need to fix.
Also I don't understand the echo part in your for loop. Remove the echo and give it a try.
echo($cart->update($id[$i], $qty[$i]));
$cart->update($id[$id], $qty[$i]);
Also providing the constructor for Cart model in the question would be a good idea.

Related

move cursor of datasource to the next record on form extension [duplicate]

This question already has an answer here:
Iterate through selected grid data and get field values of n-th datasource
(1 answer)
Closed 2 months ago.
[ExtensionOf(formControlStr(BankReconciliation ,ClearALL))]
final class ClearAll_Extension
{
void clicked(){
next clicked();
FormRun formrunn = this.FormRun();
FormDataObject myField;
FormCheckBoxControl BankAccountTrans_Included = formrunn.design().controlName("BankAccountTrans_Included");
FormDataSource BankAccounttable_ds = formrunn.dataSource("BankAccountTable");
BankAccountTable BankTable = BankAccounttable_ds.cursor();
// BankAccountTable BankTable ;
FormDataSource BankAccountTran = formrunn.dataSource("BankAccountTrans");
myField = BankAccountTran.object(fieldnum(BankAccountTrans,Included));
BankAccountTrans Bankacc ;
/// Bankacc = BankAccountTran.getFirst();
// if(Bankacc.AccountId == BankTable.AccountID)
// {
Bankacc = BankAccountTran.getFirst();
while(Bankacc){
if (Bankacc.Included == NoYes::No)
{
BankAccountTran.object(fieldNum(BankAccountTrans,Included)).setValue(NoYes::Yes) ;
}
else
{
BankAccountTran.object(fieldNum(BankAccountTrans,Included)).setValue(NoYes::No) ;
}
BankAccountTran.write();
Bankacc = BankAccountTran.getNext();
}
I want to select all record by clicking on (clear all) button and run methods of datasource in all record selected .
this button select all records but methods of datasource run on only first record doesn't run on all record , cursor still on first record not moving to the next
Why do you need to use datasource methods?
If you're doing something on all the records in a table, it makes more sense to do it with a method on the table. Or possibly create a SysOperation and do it in the service class, just loop through all the records. Doing the changes on datasource level makes sense only if you want to change the marked records, in which case you can do it with multiselect.

Calendar and dropdopwn connections

I am making a calendar and have a dropdown with all the months in so you can pick a month from the dropdown and the lazyrow should go to that index. Now my question is how would you go about doing it the other way around so that the dropdown changes when you swipe in the calendar would you update it every time you touch the lazy row or would you do it in a side effect?
So would you do it this way
LazyRow(state = calendarViewModel.listState, modifier = Modifier.fillMaxWidth()) {
calendarYears.forEach {
items(it.months.count()) { index ->
calendarViewModel.onEvent(CalendarEvent.setMonth(index))
CalendarRowItem(
modifier = Modifier.fillParentMaxWidth(),
calendarSize = it.months[index].amountOfDays,
initWeekday = it.months[index].startDayOfMonth.ordinal,
textColor = MaterialTheme.colors.secondaryVariant,
clickedColor = MaterialTheme.colors.primary,
textStyle = MaterialTheme.typography.body1
)
}
}
}
or would you do it by a side effect and can someone in that case give me an example of how to do that?

Transactions in Google Sheet - Move value from, to

I'm trying to make a document to manage my finances on google sheet, actually, I would like to be able to track the transactions I make between my accounts.
I made this sheet to be able to sum things up.
Actually, I would be able to tell the document i'm making a transaction from - to (in that case, from content 1 to content 3) and to add a new value.
I don't know how to tell google sheet to "move" 25 from content 1 to content 3 or any other content.
Thanks for the precious help.
You can use an Apps Script onEdit trigger so fire the transactions, and use checkboxes to track which transaction should be fired, so that the transaction takes place whenever the corresponding checkbox is checked.
First, add the checkboxes to the transaction rows by selecting the appropriate cells and click Insert > Checkbox.
Then, open the script bound to your spreadsheet by selecting Tools > Script editor, copy the following function, and save the project. Now every time a checkbox is checked, the corresponding transaction takes place in B2:E3, and when it is unchecked the transaction gets undone (the from and the to exchange places, and the money goes the other way):
function onEdit(e) {
var range = e.range;
var col = range.getColumn();
var row = range.getRow();
var checkbox = e.value;
var sheet = range.getSheet();
if (col === 6 && row > 8) {
var from = sheet.getRange(row, 3).getValue();
var to = sheet.getRange(row, 4).getValue();
var value = sheet.getRange(row, 5). getValue();
var valuesToUpdate = sheet.getRange("B2:E2").getValues();
var fromIndex = valuesToUpdate[0].findIndex(contents => contents === from);
var toIndex = valuesToUpdate[0].findIndex(contents => contents === to);
var fromRange = sheet.getRange(3, fromIndex + 2);
var toRange = sheet.getRange(3, toIndex + 2);
if (checkbox === "TRUE") { // MAKE TRANSACTION
fromRange.setValue(fromRange.getValue() - value);
toRange.setValue(toRange.getValue() + value);
} else if (checkbox === "FALSE") { // UNDO TRANSACTION
fromRange.setValue(fromRange.getValue() + value);
toRange.setValue(toRange.getValue() - value);
}
}
}
This function will fire every time the spreadsheet is edited, but you only want to update the transaction summary whenever the edited cell is a checkbox and this checkbox is checked. The function is checking for that, using the information passed to the onEdit function through the event object (e), which contains information on the edited cell (its value, its range, etc.):
Reference:
onEdit(e)
Event Objects: Edit

Ember context passed to a view

I'm trying to figure out what's wrong about sending action from parentView to one of its children view:
I've made a PhotoUploadView used to resize and then upload images; it adds canvas drawing the resized image in a div inside its template:
<div class="img-list">
//here the canvas will be added
</div>
The action "saveImages" in this view, acts like this:
var list = this.$('.img-list');
$.each(list.children(), function(index, value) {
//here the code to save
}
But this action is not called directly; because I need to save not only the images but also some records (an offer record and many products records, children of the offer; the images are associated to the product record);
So I have the action "save" on the parentView that is like this:
//save records
offer.save().then(function(savedOffer) {
newProducts.forEach(function(product, indexP) {
product.set('offer', savedOffer);
product.save().then(function(savedProduct) {
}
}
}
//save photos by cycling the PhotoUploadViews that are inside ProductViews that are inside the mainView
this.get('childViews').forEach(function(view, index) {
if (index >= 4) { //the childView from the 4th are the ProductViews
var productId = view.get('product').get('id');
var folder = 'offer-' + controller.get('model').get('id') + '/product-' + productId + '/';
view.get('childViews')[0].send('saveImages', folder, productId); //the first childView of a ProductView is the UploadView
}
});
Well, this works and save the images correctly when you add images to an existing offer with existing product; but when you are creating a new offer, it fails since the folder will becone "offer-undefined/product-undefined" because of course you must wait the records to be saved in order to get their ID;
So I'm trying now to move the send action into the .then callback of product save:
var childViews = this.get('childViews'); //the childView starting from the 4th are the productsViews
offer.save().then(function(savedOffer) {
newProducts.forEach(function(product, indexP) {
product.set('offer', savedOffer);
product.save().then(function(savedProduct) {
var currentPview = (childViews[4 + indexP]); //get the productView associated with the current product
var productId = savedProduct.get('id');
var folder = 'offer-' + savedOffer.get('id') + '/product-' + productId + '/';
currentPview.get('_childViews')[2].send('saveImages', folder, productId); //the object at index 2 of _childViews array is the photoUploadView
Here, the folder is built correctly but after sending action, the saveImages action crashes saying that list is undefined; trying to log the value of "this" inside "saveImages" I can see that also its value is undefined; Someone can please explain why calling the action from one point, it works, and calling it inside the .then callback of product save it doesn't?
I also would like to understand why in the first case I can do
.get('childViews')[0]
to get the PhotoUploadView, but in the second I must do
.get('_childViews')[2]
since using get('childViews) it doesn't work anymore; What is the difference between childViews and _childViews? And why _childViews has more elements than childView?

Sitecore workbox change sort order

By default Sitecore workbox displays the Item name, and sort the item list by Item name.
In one of my previous posts regarding this I managed to change the item name to a custom field.
Now I need to sort workbox by this field. How can I do this?
Assuming that you already have your own implementation of the WorkboxForm as described in the post you linked in your question, you need to change the code of the DisplayState method.
The DataUri[] items inflow parameter of this method gives you the list of all items which are in given state of the workflows. You need to retrieve all the Sitecore items from this parameter and sort them:
DataUri[] items = new DataUri[0];
List<Item> sitecoreItems = items
.Select(uri => Context.ContentDatabase.Items[uri])
.OrderBy(item => item["YourCustomField"])
.ToList();
And use the new list for selecting the current page items. This solution is not optimized for the performance - you need to get every item in given state from database so you can access the custom field.
After studying Sitecore workbox modifications, I came across with following solution.
Step 1 - Modify the GetItems method as follows,
private DataUri[] GetItems(WorkflowState state, IWorkflow workflow)
{
if (workflow != null)
{
var items = workflow.GetItems(state.StateID);
Array.Sort(items, new Comparison<DataUri>(CompareDataUri));
return items;
}
return new DataUri[] { };
}
Here comes the "CompareDataUri" method,
private int CompareDataUri(DataUri x, DataUri y)
{
//Custom method written to compare two values - Dhanuka
Item itemX = Sitecore.Context.ContentDatabase.GetItem(x);
Item itemY = Sitecore.Context.ContentDatabase.GetItem(y);
string m_sortField = "__Updated";
bool m_descSort = false;
var res = 0;
res = string.Compare(itemX[m_sortField], itemY[m_sortField]);
if (m_descSort)
{
if (res > 0)
return -1;
if (res < 0)
return 1;
}
return res;
}
This approach is optimized for performance.