I'm trying to add some data to a codeigniter (HMVC codeigniter) chopping cart and display it, i'm using this method in the main cart controller:
function add_to_cart(){
$this->load->library('cart');
// Get data
$userID = $this->input->post('userID');
$eventID = $this->input->post('eventID');
$tickedID = $this->input->post('tickedID');
// Get ticket data
$this->load->module('ticket');
$ticket_query = $this->ticket->get_where($tickedID);
//echo $this->session->all_userdata();
foreach($ticket_query->result() as $ticket_data){
$ticketPrice = $ticket_data->price;
$ticketCategory = $ticket_data->category;
}
//echo 'tickedID: '.$tickedID.' price: '.$ticketPrice.' category: '.$ticketCategory;
// Add item to cart
$data_items = array(
'id' => $tickedID,
'qty' => 1,
'price' => $ticketPrice,
'category' => $ticketCategory,
'options' => array()
);
$this->cart->insert($data_items);
$cart = $this->cart->contents();
echo '<pre>';
echo print_r($cart);
echo '</pre>';
}
Basically i'm getting the userID, eventID and tickedID variables from the session, then I run a query to get the ticked with the specific id. I run through the results of the query and get the $thicketPrice and $ticketCategory variables from it. Then I attempt to set the variables in $data_items to insert in the cart itself. FInally I attempt to echo the contents of the care and all I get is an empty array.
The session, database and cart libraries are all autoloaded and the sessions are using the database, they have the ci_sessions table. THe sessions also have an ecrypted key, what is wrong?
Some attention for successful cart insert:
'price' > 0
'name' (or similar field) better not in unicode
You need a name index as it's mandatory.
id - Each product in your store must have a unique identifier. Typically this will be an "sku" or other such identifier.
qty - The quantity being purchased.
price - The price of the item.
name - The name of the item.
options - Any additional attributes that are needed to identify the product. These must be passed via an array.
Important: The first four array indexes above (id, qty, price, and name) are required. If you omit any of them the data will not be saved to the cart. The fifth index (options) is optional. It is intended to be used in cases where your product has options associated with it. Use an array for options, as shown above.
From http://ellislab.com/codeigniter/user-guide/libraries/cart.html
So, something like this then:
$data_items = array(
'id' => $tickedID,
'qty' => 1,
'price' => $ticketPrice,
'name' => $someName,
'options' => array('category'=>$ticketCategory)
);
Related
I have here the following output in a Query String:
add_to_cart.php?product_id=4&product_name=Pizza&quantity=1&additional_id[]=1&additional_quantity[]=3&additional_id[]=4&additional_quantity[]=5
I'm trying to set up an array with each of additional IDs and their respective quantities. Each ID corresponds to an additional product in the database in the table additionals, and I need to make a SQL query for each ID to get the price and the name of the additional and then show the price multiplicated with their quantity.
If I use:
foreach ($_GET['additional_id'] as $value)
{
echo "<p>{$value}</p>";
}
If the output is based in the example Query String above I get:
1
4
But I need to add each ID with their quantity inside of this array in the file add_to_cart.php:
$columns = array
(
'product_id_session' => $product_id_session,
'product_id' => $product_id,
'product_name' => $product_name,
'product_price' => $product_price,
'quantity' => $quantity,
'additional_id' => //Maybe I need a foreach here or another array to add all the additionals of Query String?
'additional_quantity' => //Here too?
'additional_name' => //Retrieved from database, like price below
'additional_price' => //Like additional_name, I will need to connect to database and get the price of each additional ID present in the Query String
);
I was trying to do something like:
add_to_cart.php?product_id=4&product_name=Pizza&quantity=1&additionals=additional_id[]=1&additional_quantity[]=3&additional_id[]=4&additional_quantity[]=5
This can be the right way? Maybe I can create an array with additionals and parse it to the columns array? And how to get the additional_price and additional_name for each additional ID present in Query String by a SQL connection to the table additionals? This is being very complicated for me. I appreciate any help!
Try
foreach ($_GET['additional_id'] as $key=>$value)
{
$id = htmlspecialchars($value);
$qty = htmlspecialchars($_GET['additional_quantity'][$key]);
echo "<p>ID: $id, Quantity: $qty</p>";
}
This assumes that the additional_id and additional_quantity arrays are of the same length and each index of additional_id matches the same index of additional_quantity.
You should probably be using another method to pass these sorts of values though. Doing it this way is really insecure and brittle.
I have a store using osCommerce with the Dynamo one page checkout addon. I added a new column called "drop_ship_id" to the orders_products table and products table. Under the checkout_process.php file is where I believe the products that the user has ordered, are entered into the orders_products table in the database. I'm trying to pull the drop_ship_id field from each ordered product, and enter it into the orders_products table where I can call on it later on in the checkout process. Here is my current code snip:
// initialized for the email confirmation
$products_ordered = '';
$subtotal = 0;
$total_tax = 0;
for ($i=0; $i<sizeof($order->products); $i++) {
if (!in_array($payment, $suspended_payment)) {
$checkout->reduce_stock($order->products[$i]);
}
$sql_data_array = array('orders_id' => $insert_id,
'products_id' => tep_get_prid($order->products[$i]['id']),
'products_model' => $order->products[$i]['model'],
'products_name' => $order->products[$i]['name'],
'products_price' => $order->products[$i]['price'],
'final_price' => $order->products[$i]['final_price'],
'products_tax' => $order->products[$i]['tax'],
'products_quantity' => $order->products[$i]['qty'],
'drop_ship_id' => $order->products[$i]['drop_ship_id']);
tep_db_perform($database['ORDERS_PRODUCTS'], $sql_data_array);
$order_products_id = tep_db_insert_id();
Not sure if this is where it belongs, but I'm unable to get it to transfer the drop_ship_id field with this code. Does anyone know a good way of getting this to work?
You can use the error log to try and dump some information to the logs:
error_log("product id: " . $order->products[$i]['products_id'] . ", dropship order id: " . $order->products[$i]['drop_ship_id']);
As to why the value is not being transferred, I would check a few things in includes/classes/order.php - when creating a new order, it will copy the values from the cart's list of products. So you should ensure either:
the products in the cart contain this field (i.e. this field should be one of the select values in the SQL when the product is retrieved from the database and put into the cart).
you add the field in afterwards by explicitly writing the value within order.php.
And later on, when loading a saved order from the database, you should ensure you add the drop_ship_id to your SQL query.
I've been handed a project to complete and the clients have asked for a field from a customrecord attached to each customer to appear on their website. We're integrating with Netsuite on login, and saving their data in our database so we don't have to keep accessing Netsuite (very slow).
On login, we access Netsuite to do a SearchMultiSelectCustomField and find the customer's company, and then do a CustomRecordSearchBasic and use their company ID to get a list of items they have access to.
We loop over each of those items, and then loop over their custom fields. One of the fields has a typeId of -10, which means we do an ItemSearchBasic to get this item's record and the item's custom fields, saving the internalId of this item.
At the end of this loop, we have an array of item IDs that a company is linked to. We also have the company ID (custrecord_nn_item_customer) and the Item ID (custrecord_nn_item_customer_list).
I need to perform a get request on a custom record to check if that customer has been approved for that item.
The customrecord's ID is 'customrecord_custitem', and internal Id is '1'.
The record has 3 fields (although only 2 show up for the customer's Netsuite Record page):
custrecord_lookup_item - this is the Item record code (custrecord_nn_item_customer_list from above)
custrecord_custitem_code is the code I need
My question (after all that) is does anyone have any examples or can point me in the right direction on how I can access a customrecord attached to a customer? I think all of the necessary information is provided, but I've never used Netsuite before or the PHP toolkit.
$this->depends('netsuite');
$this->netsuite->start();
// get the "customer" (aka company) that the user's contact record belongs to
$companySearch = $this->netsuite->complexObject('SearchMultiSelectCustomField')
->setFields(array(
'searchValue' => new nsListOrRecordRef(array('internalId' => $companyId)),
'internalId' => 'custrecord_nn_item_customer',
'operator' => 'anyOf'
));
// Fetch items that the user's company has access to
$search = $this->netsuite->complexObject('CustomRecordSearchBasic')
->setFields(array(
'recType' => new nsCustomRecordRef(array(
'internalId' => 260,
'type' => 'customRecord')
),
'customFieldList' => array($companySearch)
));
$response = $this->netsuite->client->search($search);
// loop over the items
foreach($this->netsuite->complexToSimple($response->recordList) as $record){
//var_dump($record);
$processor = null;
$this_item = '';
$this_person = '';
// foreach custom field (all the fields we're interested in, common name etc. are custom)
foreach($record['customFieldList']['customField'] as $customField){
$processor = $customField['value'];
$id = $processor['internalId'];
$typeId = $processor['typeId'];
if($customField['internalId']=='custrecord_nn_item_customer'){
$this_person = $id;
}elseif($customField['internalId']=='custrecord_nn_item_customer_list'){
$this_item = $id;
}
// a typeId of -10 = an Inventory Item
if($typeId == -10){
// do an ItemSearchBasic to fetch the item with it's custom fields
$itemSearch = $this->netsuite->complexObject('ItemSearchBasic')
->setFields(array(
'internalId' => array(
'operator' => 'anyOf',
'searchValue' => array('type' => 'inventoryItem', 'internalId' => $id)
)
));
$itemSearch = $this->netsuite->client->search($itemSearch);
// foreach custom item field
if($v=#$this->netsuite->complexToSimple($itemSearch->recordList)){
foreach($v as $itemRecord){
//var_dump($itemRecord);
$item = array('id' => $itemRecord['internalId']);
$items[] = $item;
}
}
}
}
}
It is inside the foreach loop that I need to get the customrecord field for the company ID and the current iteration of the item ID.
Set up a saved search with the results columns you need. Don't worry about filtering by customer.
Call the search from your code, and dynamically filter for the current customer.
Your code should be about 5-10 lines long to get that done, and should be super quick.
I have the following code in CakePHP 2:
$this->Order->id = 5;
$this->Order->saveAll(array(
'Order' => array(
'person_id' => $this->Session->read('Person.id'),
'amount' => $total,
'currency_id' => $code
),
'Lineitem' => $lineitems /* a correctly-formatted array */
));
I would expect this to update the row with the Primary Key of 5 in the Order table and then insert the Lineitem rows with an order_id of 5.
However, all it does is create a new row in Order and then use the new id from the new Order record to create the Listitem rows.
Note: I'm only setting the ID as above for debugging purposes and to easily demonstrate this question. In my final code, I'll be checking to see if there's already a pending order with the current person_id and doing $this->Order->id = $var; if there is and $this->Order->create(); if there isn't.
In other words, sometimes I will want it to INSERT (in which case I will issue $this->Order->create(); ) and sometimes I will want it to UPDATE (in which case I will issue $this->Order->id = $var; ). The test case above should produce an UPDATE but it's producing an INSERT instead.
Any idea what I am doing wrong here?
The array you pass to Model->saveAll() doesnt't contain the order's id, so Cake creates a new one. If you wanto to update an existing record, either you set the order id in the passed array, or you retrieve it with a find. The documentation explicitly remarks
If you want to update a value, rather than create a new one, make sure
your are passing the primary key field into the data array
$order = $this->Order->findById(5);
// ... modify $order if needed
$this->Order->saveAll(array('Order' => $order, 'LineItem' => $items));
In your case, you may want to use something like the following to be as concise as possible. Model::saveAssociated() is smart enough to create or update depending on the id, but you must provide suitable input. Model::read($fields, $id) initializes the internal $data: for an existing record all fields will be read from the database, but for a nonexistent id, you'll need to supply the correct data for it to succeed. Assuming an order belongsTo a customer, I supply the customer id if the order doesn't exist
// set the internal Model::$data['Order']
$this->Order->read(null, 5);
// You may want to supply needed information to create
// a new order if it doesn't exist, like the customer
if (! $this->Order->exists()) {
$this->Order->set(array("Customer" => array("id" => $customer_id)));
}
$this->Order->set(array('LineItem' => $items));
$this->Order->saveAssociated();
As a final note, it seems you are implementing a shopping cart. If that's the case, maybe it'd be clearer to use a separate ShoppingCart instead of an Order with a finalized flag.
Have you tried following:
$this->Order->saveAll(array(
'Order' => array(
'id' => 5,
'person_id' => $this->Session->read('Person.id'),
'amount' => $total,
'currency_id' => $code
),
'Lineitem' => $lineitems /* a correctly-formatted array */
));
Its pretty much the same what you did with :
$this->Order->id = 5;
Maybe that would fix your problem.
Cake is checking if you set id field and if its there it updates record, if not found it creates new record instead.
update:
Then maybe check before you saveAll if there is id field, then save result of check to some boolean and create array to save determined by this boolean for example:
if($id_exist) $order['Order']['id'] = 5;
$order['Order']['id'] = 5;
$order['Order']['person_id'] = $this->Session->read('Person.id'),
$order['Order']['amount'] = $total;
$order['Order']['currency_id'] = $code;
$this->Order->saveAll(array(
'Order' => $order,
'Lineitem' => $lineitems /* a correctly-formatted array */
));
I’m having a heck of a time figuring out how to post a rating for an individual item in a list of items,
this code let’s me rate multiple items, but not single items:
for($i=0;$i<2;$i++){
$doc_item_id = $_POST['item_id0'][$i];
$doc_rating = $_POST['document_rating'][$i];
$it_rt = array(
'item_id' => $doc_item_id,
'rating' => $doc_rating,
);
$this->purchases_model->update_document($it_rt);
}
whereas this code let’s me rate only the first item (or last item depending on where i put the "break;"):
foreach($_POST['item_id0'] as $doc_item_id){
foreach($_POST['document_rating'] as $doc_rating){
}
break;
}
$it_rt = array(
'item_id' => $doc_item_id,
'rating' => $doc_rating,
);
$this->purchases_model->update_document($it_rt);
any thoughts on how to correct either of these such that the user could rate the individual item of their choosing would be greatly appreciated,
If the user is supposed to choose the item to rate (instead of rating all items at the same time), you should allow him to do so (showing only one item, let him select one using radio buttons...), and then you should be able, by PHP side, to retrieve the index of the item to modify.
Finally, in order to modify only one item, your code should look like (PHP side, you will certainly have to update your HTML form as well)
$i = $_POST['item_index']; // Here I'm supposing that you have added radio buttons
// named 'item_index' to allow user to choose the item to rate
$doc_item_id = $_POST['item_id0'][$i];
$doc_rating = $_POST['document_rating'][$i] ;
$it_rt = array(
'item_id'=> $doc_item_id,
'rating' => $doc_rating,
);
$this->purchases_model->update_document($it_rt);
In fact it would be nearly your original code without the for loop.
Looping through the entire list just to limit the item you want, is kinda bad.
Here's an example on how to do it using some array functions:
$last=true; // false for first
if($last){
$id=end($_POST['item_id0']);
}else{
$id=reset($_POST['item_id0']);
}
// alternative: $id=($last)?end($_POST['item_id0']):reset($_POST['item_id0']);
// test id
if($id===false){
// no item was supplied
}
if(!isset($_POST['document_rating'][$id])){
// somehow, the item id doesn't have a matching document rating
}
// everything is okay!
$doc_item_id = $_POST['item_id0'][$id];
$doc_rating = $_POST['document_rating'][$id];
$it_rt = array(
'item_id' => $doc_item_id,
'rating' => $doc_rating,
);
$this->purchases_model->update_document($it_rt);