I need update 1 item of my session , i send a new quantity from my form, $item['quantity'] change but not Session::get('details_evacuation_file')
It's the structure
Session::push('details_evacuation_file', [
'id' => $p_temp->id,
'quantity' => 1,
'cost' => null,
'discount' => 0,
'product' => $p_temp
]);
My function
public function update_quantity(Request $request) {
$details = Session::get('details_evacuation_file', []);
foreach ($details as $item) {
if ($item['id'] == $request->input('id')) {
var_dump($item['quantity']);
$item['quantity'] = $request->input('quantity');
var_dump($request->input('quantity'));
var_dump($item['quantity']);
}
}
session('details_evacuation_file', $details );
var_dump(Session::get('details_evacuation_file'));
die();
return redirect()->back();
}
Related
I'm trying to create a product label. While I create an array and pass it to the blade it's not working.
-> Controller
$item_name = $request->input('item_name');
$label_quantity = $request->input('label_quantity');
foreach ($item_name as $key => $name) {
$product = Product::find($item_name[$key]);
$barcode = Stock::where('product_id', '=', $item_name[$key])->get();
$data = [
'name' => $product->name,
'price' => $product->sale_price,
'barcode' => $barcode[0]['barcode'],
'quantity' => $label_quantity[$key],
];
return back()->with(compact('data'));
}
-> Blade File
#php
if (isset($data)) {
print_r(json_encode($data));
} else {
echo 'No Data Available';
}
#endphp
Please specify, what is inside the $item_name variable. Does it contain multiple products data?
If it contains only 1 product data then you change your code like this:
$item_name = $request->input('item_name');
$label_quantity = $request->input('label_quantity');
$product = Product::find($item_name[0]);
$barcode = Stock::where('product_id', '=', $item_name[0])->get();
$data = [
'name' => $product->name,
'price' => $product->sale_price,
'barcode' => $barcode[0]['barcode'],
'quantity' => $label_quantity[0],
];
return redirect('/abc', compact('data'));
Here you are redirecting to '/abc' route with $data array. You can also render a view and pass data to it like this:
return view('home', compact('data'));
return view('your view', ['data' => $data]);
if you want to pass many use compact built in function
return view('view name', compact(['data', 'data2', 'data3']));
-> Controller
$item_name = $request->input('item_name');
$label_quantity = $request->input('label_quantity');
foreach ($item_name as $key => $name) {
$product = Product::find($item_name[$key]);
$barcode = Stock::where('product_id', '=', $item_name[$key])->get();
$data = [
'name' => $product->name,
'price' => $product->sale_price,
'barcode' => $barcode[0]['barcode'],
'quantity' => $label_quantity[$key],
];
return back()->with(array('data'=>$data));
}
-> Blade File
#if (session('data'))
#php
print_r(json_encode(session('data')));
#endphp
#endif
I want to send the
function getProductsJson($order,$options) {
$stupid_mode = $options['stupid_mode'];
$items=$order->get_items();
$arr = [];
foreach ($items as $item) {
$data = $item->get_data();
$arr[] = [
'productSKU' => $data['product_id'],
'description' => $data['name'],
'quantity' => $data['quantity'],
'price' => $data['total'] / $data['quantity'],
];
}
}
Here in this part:
'description' => $data['name'],
I want it to send product description next to product name as example below:
Product Name - Product Description
How can achieve this ?
Best Regards
If you need product description saved in $content, you can get this by Product_ID, and then add this to your array:
function getProductsJson($order,$options) {
$stupid_mode = $options['stupid_mode'];
$items=$order->get_items();
$arr = [];
foreach ( $items as $item ) {
$data = $item->get_data();
$product_description = get_post( $data['product_id'] )->post_content;
$arr[] = [
'productSKU' => $data['product_id'],
'name' => $data['name'],
'description' => $product_description,
'quantity' => $data['quantity'],
'price' => $data['total'] / $data['quantity'],
];
}
}
Or if you need built-in woocommerce product description, try this:
function getProductsJson($order,$options) {
$stupid_mode = $options['stupid_mode'];
$items=$order->get_items();
$arr = [];
foreach ( $items as $item ) {
$data = $item->get_data();
$product_instance = wc_get_product( $data['product_id'] );
$product_full_description = $product_instance->get_description();
$product_short_description = $product_instance->get_short_description();
$arr[] = [
'productSKU' => $data['product_id'],
'name' => $data['name'], // or $data['description']
'description' => $product_full_description, // or $product_short_description
'quantity' => $data['quantity'],
'price' => $data['total'] / $data['quantity'],
];
}
}
I want to update my product with product image but it is not updated. I am using woocommerce rest API for adding a product.
I am following these step for update product:
Create a view file for display all the product list
Create edit function in the controller for getting all product data
when uploading a new image from edit form it gives an error
Here is my code:
if($request->hasfile('filename'))
{
foreach($request->file('filename') as $image)
{
$name=$image->getClientOriginalName();
$image->move('C:/xampp/htdocs/New-flex/wp-content/uploads/backend-product-image', $name);
$productimg_path_store_db = "http://localhost/New-flex/wp-content/uploads/backend-product-image/";
$productimg_allimg[] = $productimg_path_store_db.$name;
}
}
$AddContentText = $request->get('AddContentText');
if (!empty($AddContentText)) {
/* For List All product qnumber check in array */
$newallproducts_data = $woocommerce->get('products',array('per_page' => 100));
$array = json_decode(json_encode($newallproducts_data), True);
$partssku = array();
$partid = array();
$parturl = array();
foreach ($array as $key ) {
$partssku[] = $key['sku'];
$partid[] = $key['id'];
$parturl[] = $key['permalink'];
}
/* Create associative array product id and sku for compare */
$comb = array_combine($partssku,$partid);
/* Combine content QNUMBER and QTY in array */
$chunks = array_chunk(preg_split('/(;|,)/', $AddContentText), 2);
$result = array_combine(array_column($chunks, 0), array_column($chunks, 1));
/*Product qnumber allready avilabale array*/
$diff = array_intersect_key($result,$comb);
/*NEW PRODUCT array*/
$newproduct = array_diff($result, $diff);
/* Qnumber insert in database */
$parts_name = implode(',', array_keys($result));
/* count insert in database */
$noofpartsuse = implode(',', array_values($result));
/*echo "<pre>";
echo "main data";
print_r($result);
echo "allproduct array";
print_r($comb);
echo "Product qnumber allready avilabale";
print_r($diff);
echo "NEW PRODUCT";
print_r($newproduct);
echo "</pre>";*/
// print_r($newproduct_data);
//print_r($woocommerce->post('products', $data));
}
else{
$parts_name = '';
$noofpartsuse = '';
}
$productactive = $request->get('productactive');
if(!empty($productactive))
{
$productactive = "publish";
}
else{
$productactive = "draft";
}
$ProductListOrder = $request->get('ProductListOrder');
$producttype = $request->get('producttype');
$ProductQNumber = $request->get('ProductQNumber');
$ProductName = $request->get('name');
$ProductWidthMM = $request->get('ProductWidthMM');
$ProductLengthMM = $request->get('ProductLengthMM');
$ProductWidthInch = $request->get('ProductWidthInch');
$ProductLengthInch = $request->get('ProductLengthInch');
$Productinfotext = $request->get('Productinfotext');
$Producttechnocaldesc = $request->get('Producttechnocaldesc');
$metadescription = $request->get('metadescription');
$proimgalt = $request->get('proimg-alt');
$proyoutubelink = $request->get('proyoutubelink');
$proyoutubelinkalt = $request->get('proyoutubelink-alt');
$provimeolink = $request->get('provimeolink');
$provimeolinkalt = $request->get('provimeolink-alt');
$onshapelink = $request->get('onshapelink');
$onshapelinkalt = $request->get('onshapelink-alt');
$data = [
'name' => $ProductName,
'type' => $producttype,
'status' => $productactive,
'regular_price' => '',
'description' => $Productinfotext,
'short_description' => $Producttechnocaldesc,
'sku' => $ProductQNumber,
'categories' =>array (),
'meta_data' => [
[
'key' => 'list_order',
'value' => $ProductListOrder
],
[
'key' => 'ProductWidthMM',
'value' => $ProductWidthMM
],
[
'key' => 'ProductLengthMM',
'value' => $ProductLengthMM
],
[
'key' => 'ProductWidthInch',
'value' => $ProductWidthInch
],
[
'key' => 'ProductLengthInch',
'value' => $ProductLengthInch
],
[
'key' => 'proyoutubelink',
'value' => $proyoutubelink
],
[
'key' => 'proyoutubelink-alt',
'value' => $proyoutubelinkalt
],
[
'key' => 'provimeolink',
'value' => $provimeolink
],
[
'key' => 'provimeolink-alt',
'value' => $provimeolinkalt
],
[
'key' => 'onshapelink',
'value' => $onshapelink
],
[
'key' => 'onshapelink-alt',
'value' => $onshapelinkalt
],
[
'key' => 'UseParts-link',
'value' => $parts_name
],
[
'key' => 'Noofparts-use',
'value' => $noofpartsuse
]
],
'images' => array ()
];
/* image array for store image */
if(!empty($productimg_allimg)){
$images = &$data['images'];
$n = 0;
foreach($productimg_allimg as $id)
{
$images[] = array( //this array must be created dynamic
'src' => $id,
'position' => $n++
);
}
unset($images);
}
if(!empty($_POST['categories'])){
/* Producta category array */
$categories = &$data['categories'];
foreach($_POST['categories'] as $cat)
{
$categories[] = array( //this array must be created dynamic
'id' => $cat
);
}
unset($categories);
}
$data_insert = $woocommerce->post('products', $data);
if($data_insert){
foreach ($newproduct as $key => $value) {
$newproduct_data = [
'name' => $key,
'sku' => $key
];
$woocommerce->post('products', $newproduct_data);
}
}
return redirect('products')->with('success', 'Product has been Added');
Above code written in laravel
i store one array in to session('cart') last click [add to cart] , when i add another array in session('cart'), but it store one array then session can not save both.
help me !
public function addtocart(Request $req,$id){
$product = _prod::find($id)->toArray();
$item = [
'name' => $product['pName'],
'description' => $product['pDesc'],
'price' => $product['pPrice'],
];
$cart = [
'qtyTotal' => 0,
'priceTotal' => 0,
'item' => [$item]
];
$req->session()->put('cart',$cart);
$a = session()->get('cart');
}
change this
$req->session()->put('cart',$cart);
$a = session()->get('cart');
dd($a);
to this:
$cartvalues[] = $cart;
$req->session()->put('cart',$cartvalues);
$a = session('cart');
dd($a);
because you keep overwriting the previous value inside the session cart
Here you are overwriting cart variable in session every time you add a new item. So store cart items as an array and add item to array. Code should be:
public function addtocart(Request $req, $id) {
$product = _prod::find($id)->toArray();
$item = [
'name' => $product['pName'],
'description' => $product['pDesc'],
'price' => $product['pPrice'],
];
$cart = [
'qtyTotal' => 0,
'priceTotal' => 0,
'item' => [$item]
];
$cartItems = session()->get('cart');
if (empty($cartItems)) {
$cartItems = [];
}
$cartItems[] = $cart;
$req->session()->put('cart', $cartItems);
return view($cartItems);
}
Here is the simple example to update your cart in your case
`
public function addtocart(Request $req,$id){
//return redirect('Resouce/product');
$product = _prod::find($id)->toArray();
$item = [
'name' => $product['pName'],
'description' => $product['pDesc'],
'price' => $product['pPrice'],
];
if($req->session()->has('cart')){
$oldCart = $req->session()->get('cart');
$newCart = [
'qtyTotal' => 0,
'priceTotal' => 0,
'item' => array_merge($item,$oldCart['item'])
];
$req->session()->put('cart',$newCart);
}
$cart = [
'qtyTotal' => 0,
'priceTotal' => 0,
'item' => [$item]
];
$req->session()->put('cart',$cart);
$a = session()->get('cart');
dd($a);
}`
I am trying to create configurable product with the attributes color and size from simple product collection.
To achieve this, I created a custom attribute named configurable_sku for respective simple products and filled with common SKU. Using this SKU we can group to create a configurable product.
I got collection from $product_sku_collection['sku'] like below,
...
array (size=387)
0 =>
array (size=2)
'conf' => string '753315' (length=6)
'simpleprodcollection' =>
array (size=1)
0 =>
array (size=10)
...
1 =>
array (size=2)
'conf' => string '753319' (length=6)
'simpleprodcollection' =>
array (size=1)
0 =>
array (size=10)
...
Below is the php script which i tried so far.
<?php
set_time_limit(0);
error_reporting(E_ALL | E_STRICT);
error_reporting(1);
ini_set('display_errors', 1);
define('D_S', DIRECTORY_SEPARATOR);
require_once 'app/Mage.php';
umask(0);
Mage::app();
if (function_exists('d') === false) {
function d($data, $die = 0, $z = 1, $msg = 1) {
echo"<br/><pre style='padding:2px 5px;background: none repeat scroll 0 0 #E04E19;clear: both;color: #FFFFFF;float: left;font-family: Times New Roman;font-style: italic;font-weight: bold;text-align: left;'>";
if ($z == 1)
Zend_Debug::dump($data);
else if ($z == 2)
var_dump($data);
else
print_r($data);
echo"</pre>";
if ($d == 1)
die();
}
}
function get_attribute_id($option, $type) {
$attributeId = Mage::getResourceModel('eav/entity_attribute')->getIdByCode('catalog_product', $type);
$attribute = Mage::getModel('catalog/resource_eav_attribute')->load($attributeId);
$attributeOptions = $attribute->getSource()->getAllOptions();
foreach ($attributeOptions as $opts_arr) {
if (strtoupper($opts_arr['label']) == strtoupper($option)) {
return $opts_arr['value'];
}
}
return FALSE;
}
$_simple_products = array();
function attributeValueExists($arg_attribute, $arg_value) {
$attribute_model = Mage::getModel('eav/entity_attribute');
$attribute_options_model = Mage::getModel('eav/entity_attribute_source_table');
$attribute_code = $attribute_model->getIdByCode('catalog__simple_product', $arg_attribute);
$attribute = $attribute_model->load($attribute_code);
$attribute_table = $attribute_options_model->setAttribute($attribute);
$options = $attribute_options_model->getAllOptions(false);
foreach ($options as $option) {
if ($option['label'] == $arg_value) {
return $option['value'];
}
}
return false;
}
//$_product = Mage::getModel('catalog/product')->load(46);
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToSelect('*');
// d($collection->getData()); exit;
$in = 0;
$product_sku_collection = array();
$product_dummy_collection = array();
foreach ($collection->getData() as $val) {
$product_dummy_collection[$in] = $val;
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToFilter('confiugrable_sku', array('eq', $val['sku']));
if (count($collection->getData()) > 0) {
$product_sku_collection['sku'][$in]['conf'] = $val['sku'];
$product_sku_collection['sku'][$in]['simpleprodcollection'] = $collection->getData();
$in++;
}
}
$color_attribute = Mage::getModel('eav/config')->getAttribute('catalog_product', 92);
foreach ($color_attribute->getSource()->getAllOptions(true, true) as $option) {
$attributeArray[$option['value']] = $option['label'];
}
//d($attributeArray); exit;
$color_array = array();
$index = 0;
foreach ($attributeArray as $value) {
$value_index = get_attribute_id($value, 'color');
if ($value != '') {
$color_array[$index] = array(
'value_index' => $value_index,
'label' => $value,
'is_percent' => 0,
'pricing_value' => '0',
'attribute_id' => '92'
);
$index++;
}
}
//d($color_array); exit;
$size_attribute = Mage::getModel('eav/config')->getAttribute('catalog_product', 136);
foreach ($size_attribute->getSource()->getAllOptions(true, true) as $option) {
$sattributeArray[$option['value']] = $option['label'];
}
//d($attributeArray); exit;
$size_array = array();
$index = 0;
foreach ($sattributeArray as $value) {
$value_index = get_attribute_id($value, 'size');
if ($value != '') {
$size_array[$index] = array(
'value_index' => $value_index,
'label' => $value,
'is_percent' => 0,
'pricing_value' => '0',
'attribute_id' => '92'
);
$index++;
}
}
//d($size_array); exit;
// exit;
$cProduct = Mage::getModel('catalog/product');
$model = Mage::getModel('catalog/product');
$setConfigurableAttributesData = array(
'0' => array('id' => NULL, 'label' => 'Color', 'position' => NULL,
'values' => $color_array,
'attribute_id' => 92, 'attribute_code' => 'color', 'frontend_label' => 'Color',
'html_id' => 'config_super_product__attribute_0'
),
'1' => array('id' => NULL, 'label' => 'Clothing Size', 'position' => NULL,
'values' => $size_array,
'attribute_id' => 136, 'attribute_code' => 'size', 'frontend_label' => 'Clothing Size',
'html_id' => 'config_super_product__attribute_1')
);
//d(($product_sku_collection['sku'])); exit;
$index = 1;
foreach ($product_sku_collection['sku'] as $key => $value) {
$main_product_data = $model->load($value['simpleprodcollection']['0']['entity_id']);
$main_pd_name = $main_product_data->getData('name');
$setConfigurableProductsData=array();
//d($value['simpleprodcollection']['0']['entity_id']);
foreach ($value['simpleprodcollection'] as $v) {
$clab = Mage::getModel('catalog/product')->load($v['entity_id'])->getAttributeText('color');
$cvalue_index = Mage::getResourceModel('catalog/product')->getAttributeRawValue($v['entity_id'], 'color');
$slab = Mage::getModel('catalog/product')->load($v['entity_id'])->getAttributeText('size');
$svalue_index = Mage::getResourceModel('catalog/product')->getAttributeRawValue($v['entity_id'], 'size');
$setConfigurableProductsData = array(
$v['entity_id'] =>
array('0' =>
array('attribute_id' => '92', 'label' => $clab, 'value_index' => $cvalue_index, 'is_percent' => 0, 'pricing_value' => ''),
'1' =>
array('attribute_id' => '136', 'label' => $slab, 'value_index' => $svalue_index, 'is_percent' => 0, 'pricing_value' => '')
)
);
//d($setConfigurableProductsData);
}
$cProduct
->setTypeId(Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE)
->setTaxClassId(5)
->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH)
->setStatus(Mage_Catalog_Model_Product_Status::STATUS_ENABLED)
->setWebsiteIds(array(1))
->setAttributeSetId(4) // You can determine this another way if you need to.
->setSku("C" . $main_product_data->getData('confiugrable_sku'))
->setName($main_product_data->getData('name'))
->setQty(25)
->setPlayer($main_product_data->getData('player'))
->setBrand($main_product_data->getData('brand'))
->setStyle($main_product_data->getData('style'))
->setShortDescription($main_product_data->getData('short_description'))
->setDescription($main_product_data->getData('description'))
->setPrice($main_product_data->getData('price'));
$cProduct->setStockData(array(
'use_config_manage_stock' => 1,
'is_in_stock' => 1,
'is_salable' => 1,
));
$cProduct->setConfigurableProductsData($setConfigurableProductsData);
$cProduct->setConfigurableAttributesData($setConfigurableAttributesData);
$cProduct->setCanSaveConfigurableAttributes(1);
try {
$cProduct->save();
//$productId = $cProduct->getId();
echo $index.") ".$cProduct->getId() . "====>" . $main_pd_name . " added\n";
} catch (Exception $e) {
echo "$main_pd_name not added\n";
echo "exception:$e";
}
$index++;
}
//****************-----------------*****************//
?>
When I run this script, it has to insert 387 configurable products with their respective simple product. But loop runs one time and stops executing, It inserts only one configurable product with their associated simple product but it has to insert all 387 configurable products.
Where have I gone wrong in this. I checked all the way to find it but could not.
Kindly give some advice on this
Finally i found it, we need to use below code inside for loop
$cProduct->save();
$cProduct->unsetData();
To make magento recognize your data as a new model again, you simply need to unset the model id
Mage::getModel('catalog/product'); this actually queries Magento registry and fetch a cached object of that model type, this style of reusing objects is known as Singleton and Magento is known for that. In cases of loops and continuous need for a new unique object, use the standard constructor call of that model. For example in case of products:
$cProduct = new Mage_Catalog_Model_Product();