Hi I have a cart in Codeigniter that works well. I tried to look for a discount/coupon handling but can't.
This is my cart code:
public function addToCart($id){
$this->load->model('products_model');
$products = $this->products_model->getItemDetail($id);
foreach ($products as $product) {
$insert = array(
'id' => $product->id,
'name' => $product->name,
'qty' => '1',
'price' => $product->item_eur,
'image' => $product->image,
'options' => array(
'info' => $product->cart_description,
'qty_description' => $product->qty_description
)
);
$this->cart->insert($insert);
}
$last = end($this->cart->contents());
echo $last['rowid'];
}
I thought of making a Coupon Code read from the DB and insert a discount as an item in the cart:
public function addCoupon(){
$this->load->model('products_model');
$res = $this->products_model->getCoupon($_POST['value']);
if($res){
foreach($res as $result){
$coupon = array(
'id' => $result->id,
'name' => $result->name,
'qty' => '1',
'price' => $result->discount,
'options' => array(
'info' => 'coupon',
'qty_description' => ''
)
);
$this->cart->insert($coupon);
}
echo '1';
}else{
$this->lang->load('products');
echo $this->lang->line('cart_notok');
}
}
Where the DB is
[name:type] (example)
id:int (1)
name: varchar ('Discount of 20€')
code: varchar ('AFD1234')
discount: decimal (-20)
[Edit]
And the model:
public function getCoupon($code){
$results = $this->db->get_where('coupons', array('code' => $code));
return $results->result();
}
The item gets added to the cart but if the 'price' => $result->discount is set to -20 or a percentage it gets set as +20€ and not -20€.
Any way to do this?
Related
I am working on partials payments by creating order programmatically.
I am stuck with the issue when I am doing partials payments of a product in order. I created the order total successfully but woo commerce add remaining amount as a coupons, whereas I did not any coupons.
Here is my Function:
public function createNewOrder($order_array){
$address = array(
'first_name' => $order_array['first_name'],
'last_name' => $order_array['last_name'],
'company' => $order_array['company'],
'email' => $order_array['email'],
'phone' => $order_array['phone'],
'address_1' => $order_array['address_1'],
'address_2' => $order_array['address_2'],
'city' => $order_array['city'],
'state' => $order_array['state'],
'postcode' => $order_array['postcode'],
'country' => $order_array['country']
);
$args = array(
'customer_id' => $order_array['customer_id'],
'status' => $order_array['order_status'],
);
$order = wc_create_order($args);
$productArray = json_decode(stripslashes($order_array["productArray"]), true);
// This is an existing SIMPLE product
foreach ($productArray as $key => $value) {
$itemData=$value['id'];
$wc_deposit_enabled = get_post_meta( $itemData, '_wc_deposit_enabled', true );
$wc_deposit_amount = get_post_meta( $itemData, '_wc_deposit_amount', true );
$wc_amount = get_post_meta( $itemData,'_price',true );
if ($wc_deposit_enabled!="") {
$order->add_product( get_product($itemData), $value['quantity'], array(
'totals' => array(
'subtotal' => $wc_amount,
'total' => $wc_deposit_amount,
'subtotal_tax' => 0,
'tax' => 0,
)));
[enter image description here][1]
}else{
$order->add_product( get_product($itemData), $value['quantity']);
}
}
if(!empty($order_array['order_status']))
{
$order->update_status($order_array['order_status']);
}
$order->set_address( $address, 'billing' );
$order->calculate_totals();
$order->save();
}
I'm using a Laravel 8 with darryldecode/laravelshoppingcart Cart Package. I'm struggling a bit with updating product quantity if it exists in users cart.
For example: If cart is empty, while adding a product and then clicking mutliple times on "Add To Cart" it adds only one product and then updates quantity to its maximum. But when I'm adding a second product, and then adding again product 1 it adds another product to the cart. It definitely should not add another product but it has to be restricted to maximum quantity of first product.
My cart store method:
public function store(CartStoreRequest $request) {
$validated = $request->validated();
$product = Product::findOrFail($validated['product_id']);
$rowId = uniqid();
$userID = $validated['user_id'];
// get current user cart
$currentCart = \Cart::session($userID);
if(!empty($currentCart->getContent()->toArray())) {
foreach($currentCart->getContent() as $item) {
$productID = $item->associatedModel->id;
if($productID === $product->id) {
$currentCart->update($item->id, [
'quantity' => [
'relative' => false,
'value' => $product->minStock($item->quantity + $validated['quantity']),
]
]);
} else {
$currentCart->add(array(
'id' => $rowId,
'name' => $product->name,
'price' => $product->price->amount(),
'quantity' => $validated['quantity'],
'associatedModel' => $product,
'attributes' => array(
'first_image' => $product->firstImage,
'formatted_price' => $product->formattedPrice,
'product_stock' => $product->stockCount()
)
));
}
}
} else {
$currentCart->add(array(
'id' => $rowId,
'name' => $product->name,
'price' => $product->price->amount(),
'quantity' => $validated['quantity'],
'associatedModel' => $product,
'attributes' => array(
'first_image' => $product->firstImage,
'formatted_price' => $product->formattedPrice,
'product_stock' => $product->stockCount()
)
));
}
return redirect()->back();
}
I hope that's someone had similar problem and knows how to solve this.
Okay, so the solution is to use product ID as $rowId,
$validated = $request->validated();
$product = Product::findOrFail($validated['product_id']);
$rowId = $product->id;
$userID = $validated['user_id'];
$currentCart = \Cart::session($userID);
$currentCart->add(array(
'id' => $rowId,
'name' => $product->name,
'price' => $product->price->amount(),
'quantity' => $product->minStock($validated['quantity']),
'associatedModel' => $product,
'attributes' => array(
'first_image' => $product->firstImage,
'formatted_price' => $product->formattedPrice,
'product_stock' => $product->stockCount()
)
));
$currentCartContents = $currentCart->get($rowId);
$quantity = $product->minStock($currentCartContents->quantity);
if($currentCartContents->quantity !== $quantity) {
$currentCart->update($rowId, [
'quantity' => [
'relative' => false,
'value' => $quantity,
]
]);
}
return redirect()->back();
I am working with Codeigniter cart
my problem is how to update the quantity of items if the item is already exist in the cart.
My model
function addToCart(){
$data = array(
'id' => $this->input->post('product_id'),
'qty' => $this->input->post('qty'),
'price' => $this->input->post('price'),
'name' => $this->input->post('product_name'),
);
$this->cart->insert($data);
redirect(base_url().'shopping-cart-view');
}
This may help:
function addToCart(){
$data = array(
'id' => $this->input->post('product_id'),
'qty' => $this->input->post('qty'),
'price' => $this->input->post('price'),
'name' => $this->input->post('product_name'),
);
/* modification starts */
$db_query = $this->db->get_where('cart', $data) ;
$rows = $query->num_rows();
if($rows > 0){
// update the record
}else{
//insert record..
}
// modification ends
redirect(base_url().'shopping-cart-view');
}
So, I have a daily cron job running a file that calls another file that in combination export our product list to an XML file. These are the two files.
arrayxml.php
<?php
class ArrayXml {
private $xml;
public function __construct($root='store') {
$this->xml = new SimpleXMLElement("<$root></$root>");
}
private function iterate($element, $xmlNode) {
foreach($element as $name=>$value) {
if(is_string($value) || is_numeric($value)) {
$xmlNode->$name = $value;
}
else {
$xmlNode->$name = null;
$this->iterate($value, $xmlNode->$name);
}
}
}
public function toXML($array) {
$this->iterate($array, $this->xml);
return $this->xml->asXML();
}
}
?>
and export.php
<?php
header('Content-Type: text/xml');
include '../app/Mage.php';
include 'arrayxml.php';
Mage::app();
$_products = Mage::getModel('catalog/product')->getCollection();
$_result = array();
foreach($_products as $_product) {
$_product = $_product->load();
$categoryIds = $_product->getCategoryIds();
if (isset($categoryIds[0])){
$category = Mage::getModel('catalog/category')->setStoreId(Mage::app()->getStore()->getId())->load($categoryIds[0]);
$categoryName = $category->getName();
}
$_result['products']['product'][] = array(
'productId' => $_product->getSku(),
'title' => $_product->getName(),
'description' => $_product->getDescription(),
'price' => $_product->getFinalPrice(),
'image' => 'http://dissios.com/media/catalog/product'.$_product->getImage(),
'url' => 'http://dissios.com/'.$_product->getUrlPath(),
'instock' => 'Y',
'availability' => 'Διαθέσιμο',
'category_id' => $categoryIds[0],
'category_name' => $categoryName
);
}
$_converter = new ArrayXML();
echo $_converter->toXML($_result);
$f = fopen("bestprice.xml", "w");
fwrite($f, $_converter->toXML($_result));
fclose($f);
?>
Since then, I've split the site to separate stores/views, so there are two domains that i want the products to have URLs of, not the parent store's (dissios.com in the code above).
I'd like this code to check the store code and adjust the URL accordingly, so I'd have for example http://eclock.gr/media/catalog/product'.$_product->getImage() for the one and http://lourakiahirsch.gr/media/catalog/product'.$_product->getImage() for the other.
Thanks!
EDIT: Solved!
Here is the code i changed:
// Get the product's store IDs
$storeCode = $_product->getStoreIds();
if ($storeCode[2] == '5') {
$_result['products']['product'][] = array(
'productId' => $_product->getSku(),
'title' => $_product->getName(),
'description' => $_product->getDescription(),
'price' => $_product->getFinalPrice(),
'image' => 'http://lourakiahirsch.gr/media/catalog/product'.$_product->getImage(),
'url' => 'http://lourakiahirsch.gr/'.$_product->getUrlPath(),
'instock' => 'Y',
'availability' => 'Διαθέσιμο',
'category_id' => $categoryIds[0],
'category_name' => $categoryName
);
}
else if ($storeCode[2] == '6') {
$_result['products']['product'][] = array(
'productId' => $_product->getSku(),
'title' => $_product->getName(),
'description' => $_product->getDescription(),
'price' => $_product->getFinalPrice(),
'image' => 'http://eclock.gr/media/catalog/product'.$_product->getImage(),
'url' => 'http://eclock.gr/'.$_product->getUrlPath(),
'instock' => 'Y',
'availability' => 'Διαθέσιμο',
'category_id' => $categoryIds[0],
'category_name' => $categoryName
);
}
else {
$_result['products']['product'][] = array(
'productId' => $_product->getSku(),
'title' => $_product->getName(),
'description' => $_product->getDescription(),
'price' => $_product->getFinalPrice(),
'image' => 'http://dissios.com/media/catalog/product'.$_product->getImage(),
'url' => 'http://dissios.com/'.$_product->getUrlPath(),
'instock' => 'Y',
'availability' => 'Διαθέσιμο',
'category_id' => $categoryIds[0],
'category_name' => $categoryName
);
}
As one possible way to do this, you can store your stores' ID (you can find them in Magento Admin panel) in one array and then loop through them using something like this:
foreach($arrayOfStores as $storeId) {
$store = Mage::app()->getStore($storeId);
And then you load your collection:
$collection = Mage::getModel('catalog/product')
->getCollection()
->setStoreId( $storeId )
->addAttributeToSelect('*');
I followed the tutorial. But I can find no way to populate a form select from a database like this:
// Blog/src/Blog/Form/BlogItemForm.php
$blogCategoryTable = new Model\BlogCategoryTable;
$this->add(new Element\Select('category_id',
array('label' => 'Category', 'value_options' => $blogCategoryTable->getFormChoices())
));
Does anyone have any ideas?
I use a function to retrieve the data and set it to the form:
From my factory:
$option_for_select = $this->model->getWhatEver();
$this->add($factory->createElement(array(
'name' => 'what_ever',
'type' => 'Zend\Form\Element\Select',
'attributes' => array(
'options' => $option_for_select,
),
'options' => array(
'label' => 'What ever:',
),
)));
From the model:
public function getWhatEver()
{
$sql = "SELECT something";
$statement = $this->adapter->query($sql);
$res = $statement->execute();
// set the first option
$rows[0] = array (
'value' => '0',
'label' => 'Top',
'selected' => TRUE,
'disabled' => FALSE
);
foreach ($res as $row) {
$rows[$row['triplet_id']] = array (
'value' => $row['col1'],
'label' => $row['col2'],
);
}
return $rows;
}