I am trying to set array, but it is not getting set. Everytime the Buy function called, the array gets declared.
This is the function is controller.
public function buy() {
if($this->session->userdata('counter')){
$counter = $this->session->userdata('counter');
$this->session->set_userdata('counter', $counter + 1);
} else {
$this->session->set_userdata('counter', 1);
}
if(isset($bought)){
$name = $this->input->post('name');
$price = $this->input->post('price');
$qty = $this->input->post('qty');
$product = array('name' => $name, 'price' => $price, 'qty'=> $qty);
array_push($bought, $product);
var_dump($bought);
die();
} else {
$bought = array();
redirect("");
}
As you can see, it should remember that $bought is set, but it gets declared anew. For now I
tried to make it global, before "public function __construct()",
tried "if (!empty),
tried to put into session,
tried to find the answer across whole stackoverflow...
Please let me know if additional info needed.
Thanks a lot!
In your code when you are checking for $bought, it is not present so it is going to the else part everytime. Instead define a blank array and then set the values inside it. Try with -
if(isset($_SESSION['bought'])){
$name = $this->input->post('name');
$price = $this->input->post('price');
$qty = $this->input->post('qty');
$product = array('name' => $name, 'price' => $price, 'qty'=> $qty);
array_push($_SESSION['bought'], $product);
var_dump($_SESSION['bought']);
die();
} else {
$_SESSION['bought'] = array();
}
And start the session at top of the page.
I got it working.
I made a workaround with sgt's help, so now my code looks like this:
if($this->session->userdata('bought')){
$name = $this->input->post('name');
$price = $this->input->post('price');
$qty = $this->input->post('qty');
$product = array('name' => $name, 'price' => $price, 'qty'=> $qty);
// please see that here I just returned from old one and added new data to the old one.
// Then I just added the result to the session.
$old_session = $this->session->userdata('bought');
array_push($old_session, $product);
$this->session->set_userdata('bought', $old_session);
redirect("");
} else {
$this->session->set_userdata('bought', array());
}
Related
I've a system that I need to get a minor tweak made to and hope someone can advise.I've a custom field from a modal called 'cancle_order_reason' that needs to be added to a transactions table when a internal refund is made. Currently the table says just 'internal', but I want it to give the info from the 'cancle_order_reason' field for greater info.
From what I can see the relevant controllers are
packages/catalyst/controllers/dashboard/catalyst/orders.php which is where the modal is.
public function add_refund_order(){
$valt = Loader::helper('validation/token');
if (!$valt->validate('add_refund_order', $this->post('token'))) {
throw new Exception($valt->getErrorMessage());
}
Loader::model('proforms_item','proforms');
$pfo = ProFormsItem::getByID($this->post('orderID'));
$orderID = $this->request('orderID');
$question_set = $pfo->asID;
$setAttribs = AttributeSet::getByID($question_set)->getAttributeKeys();
foreach ($setAttribs as $ak) {
if($ak->getAttributeType()->getAttributeTypeHandle() == 'price_total'){
$value = $pfo->getAttributeValueObject($ak);
$db = Loader::db();
$avID = $value->getAttributeValueID();
$amount = money_format('%(#4n',$this->post('credit_amount'));
$ak->getController()->savePayment($avID,$amount,2);
}
}
$desc = trim($amount . ' ' . $this->request('cancle_order_reason'));
$date = date('Y-m-d');
$u = new User();
$data = array(
'ProformsItemID'=> $this->request('orderID'),
'action'=> 'Refund (Internal)',
'amount'=> $amount,
'description'=> $desc,
'uID'=> $u->uID,
'date' => $date
);
Loader::model('order_history', 'catalyst');
$oh = new OrderHistory();
$oh->addOrderHistoryItem($data);
$this->redirect('/dashboard/catalyst/orders/refund_added_order/?view_order='.$orderID);
}
and then the model controller:
models/attribute/types/price_total/controller.php
public function savePayment($avID=null, $amount, $credit=null, $transID='internal', $type='internal', $status=1){
// $credit == 2 is refund
$this->load();
$db = Loader::db();
if($this->getAttributeValueID()){
$avID = $this->getAttributeValueID();
}
$db->Execute("INSERT INTO atPriceTotalPayments (avID,amount,payment_date,credit,transactionID,type,status) VALUES(?,?,?,?,?,?,?)", [$avID, $amount, date('Y-m-d'), $credit, $transID, $type, $status]);
$this->updatePaidAmount($avID);
}
What is needed is for the details contained in field name ‘cancle_order_reason’ on the modal to be used in place of the ‘internal’ on $transID=‘internal’ on the models/attribute/types/price_total/controller.php. I’ve tested replacing ‘internal’ with some other text, and it updates, so it is the correct one to update.
I’ve tried:
$amount = money_format('%(#4n',$this->post('credit_amount'));
$transID = $this->request('cancle_order_reason');
$ak->getController()->savePayment($avID,$amount,$transID);
And nothing changes.
Changing the other controller so
$transID='internal'
becomes
$transID
results in an error:
Too few arguments to function
PriceTotalAttributeTypeController::savePayment(), 3 passed in
/home/bookinme/web/test.book-in.me/public_html/packages/catalyst/controllers/dashboard/catalyst/orders.php
on line 842 and at least 4 expected.
php codeigniter i want to redirect this function print_view and also pass the data $this->db->insert('invoice_main',$datas);$result = $this->db->insert_id();
Public function insert_invoice(){
$item_name = $_POST['item'];
$rate = $_POST['rate'];
$quantity = $_POST['quantity'];
$tax = $_POST['tax'];
$amount = $_POST['amount'];
$invoice_id = $this->input->post('invoice_id');
//$invoice_id++;
$datas = array(
'user_id' => $this->session->userdata('user_id'),
'invoice_id' => $this->input->post('invoice_id'),
'pt_opnum' => $this->input->post('pt_opnum'),
'pt_uhid' => $this->input->post('pt_uhid'),
'doc_name' => $this->input->post('doc_name'),
'status'=>1
);
$this->db->insert('invoice_main',$datas);
$result = $this->db->insert_id();
for ($i=0; $i <count($item_name) ; $i++) {
$data=array(
'invoice_id' =>$invoice_id,
'pt_name'=> $this->input->post('pt_opnum'),
'date'=>date('d-m-Y'),
'name'=>$item_name[$i],
'rate'=>$rate[$i],
'quantity'=>$quantity[$i],
'tax'=>$tax[$i],
'amount'=>$amount[$i],
'sub_total'=>$_POST['sub_total'],
'o_tax'=>$_POST['o_tax'],
'grand_total'=>$_POST['grand_total'],
'status'=>1
);
$this->db->insert('invoice_details',$data);
}
return($this->db->affected_rows()!=1)?false:true;
$this->print_view($result);
}
public function print_view($result){
redirect(base_url()."invoice/print_view/".$result);
}
You can pass the any data with flashdata.
$this->session->set_flashdata('something',$result);
On the other page you can access it
$something = $this->session->flashdata('something);
But on your case you don't have to use flash data, you can get the params from url and you can search on your DB.
Is there a way to compare two attributes in the cart function?
$data = array(
'id' => $id,
'qty' => $qty,
'price' => $price,
'name' => $name,
'stock' =>$quan
);
So if I have to compare the qty and stock elements,how should I implement them at the controller?
Sorry for the late submission. Here is the controller code:
function update_c()
{
$data = $_REQUEST;
foreach ($this->cart->contents() as $items)
{
$name = $items['name'];
$quantity = $items['qty'];
$price = $items['price'];
$sub = $items['subtotal'];
$total = $this->cart->total();
$id = $items['id'];
$quan=$items['stock'];
if($items['quantity']<=$items['quan'])
{
$this->data['err_message'] = 'Your cart is added!';
$this->cart->update($data);
redirect($_SERVER['HTTP_REFERER']);
}
else
{
$this->data['err_message'] = 'quantity mismatch';
}
}
}
$data is the variable passed to your view from the controller so i am assuming you are already in the controller. If that's the case why don't you compare before putting them in the variable, but if that isn't the case a simple if statement with the array will suffice
if($data["qty"]==$data["stock"]){
//Some statements
}
I hope i'm on the right course. Let me know what happens
i am adding products to session as array but before adding that product to session how to check that product is present in session array or not.
If the product is present i want to increase the count of that product, if not add that product to session array. My php code is given below.
session_start();
if(empty( $_SESSION['fields1'] )) {
$_SESSION['fields1'] = array();
}
$qty = 1;
$id = $_POST['id'];
$name = $_POST['name'];
$description = $_POST['description'];
$cnt = 0;
print_r($_SESSION['fields1']);
if (! empty($_SESSION['fields1'])){
foreach ($_SESSION['fields1'] as $key=>$val){
if ($id == $val['id']){
$qty = $val['qty']++;
//echo "qty ===".$qty;
$_SESSION['fields1'][$cnt]['qty'] = $val['qty']++;
}
else
{
$arrayval = array('id' => $id,'name' => $name,'description' => $description,'qty' => $qty);
array_push($_SESSION['fields1'] ,$arrayval );
}
$cnt++;
}
}else{
$arrayval = array('id' => $id,'name' => $name,'description' => $description,'qty' => $qty);
array_push($_SESSION['fields1'] ,$arrayval );
}
//print_r($_SESSION['fields1']);
echo json_encode($_SESSION['fields1']);
If $id is ID of product and fields is array of products, try something like this:
if(empty($_SESSION['fields'][$id]))
$_SESSION['fields'][$id]['qty'] = 1;
else
$_SESSION['fields'][$id]['qty']++;
I am using "ajaxSubmitButton" to send some values of 3 fields: registrant, product id and quantity to controller (controller name: actionCart). After submitting the button I receive those values in session array what I did successfully. At this point, if I submit same product id but different quantity, I want to update the quantity key with new value. I have done this by php global $_SESSION but can't using Yii session variable.
public function actionCart()
{
if(isset($_POST["Order"])){
$item = $_POST["Order"];
$registration_id = $item["registration_id"];
$this->productId = $item["item"];
$quantity = $item["quantity"];
$quantity = $item["quantity"]=='' ? 1 : $item["quantity"];
$productInfo = Products::model()->findByPk(array('id'=>$this->productId));
$totalPrice = $productInfo->price * $quantity;
$newItem = array("product_id" => $this->productId , "product_name" => $productInfo->name, "quantity" => $quantity,"price" => $productInfo->price,"totalPrice" => $totalPrice);
$session = Yii::app()->session;
$cartArray = $session['cart'];
$searchArrResult = $this->searchSubArray($session['cart'],'product_id',$this->productId);
if (!empty($searchArrResult)) {
/***** this works *****/
foreach ( $_SESSION['cart'] as $key=>$cart ) {
if ( $cart["product_id"] == $this->productId ) {
$_SESSION['cart'][$key]['quantity']=$quantity;
$_SESSION['cart'][$key]['totalPrice']=$totalPrice;
}
}
/***** following commented code does not work *****
*
foreach($session['cart'] as $key=>$cart){
if ($cart["product_id"] == $this->productId){
$session['cart'][$key]['quantity'] == $quantity;
$session['cart'][$key]['totalPrice'] == $totalPrice;
}
}*/
}
else {
$cartArray[] = $newItem;
$session['cart'] = $cartArray;
}
print_r($session['cart']);
//unset(Yii::app()->session['cart']);
}
}
In the above code I marked by commenting where I want to update session values. Please help me someone if it is possible do in yii.
Try this:
$carts = $session['cart'];
foreach($carts as $key=>&$cart){
if ($cart["product_id"] == $this->productId){
$cart['quantity'] == $quantity;
$cart['totalPrice'] == $totalPrice;
}
}
$session['cart'] = $carts;
Yii::app()->session return object of CHttpSession, not reference to $_SESSION.
$carts = $session['cart'] equals operation $carts = $session->get('cart'); (by means magic method __get in CHttpSession) and $session['cart'] = $carts; equals to $session->set('cart', $carts); (by __set)
That's why you can't setting by $session['cart'][$key]['quantity'] = $quantity;
UPDATED full solution (I change logic of saving products - $key = product_id)
public function actionCart()
{
if(isset($_POST["Order"])){
$item = $_POST["Order"];
$registration_id = $item["registration_id"];
$this->productId = $item["item"];
$quantity = empty(intval($item["quantity"])) ? 1 : intval($item["quantity"]);
$productInfo = Products::model()->findByPk(array('id'=>$this->productId));.
if(empty($productInfo))
return false; // or other action
$newItem = array(
"product_id" => $this->productId ,
"product_name" => $productInfo->name,
"quantity" => $quantity,
"price" => $productInfo->price,
"totalPrice" => ($productInfo->price * $quantity)
);
$cartArray = Yii::app()->session['cart'];
$cartArray[$this->productId] = $newItem;
Yii::app()->session['cart'] = $cartArray;
}
}