Woocommerce rest api update product image gives error - php

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

Related

Send payment gateway woocommerce producct description next to product name

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'],
];
}
}

How to save two array list in one single row in table

How to save two array list in a single row in table?
I have try to foreach every array but I just want to know how to save the array in single row in table just see the picture below. i don't want to have an null value. because this function is like single file that reference in job_orders.
$date = $request->get('date');
$client_name = $request->get('client_name');
$address = $request->get('address');
$service_date = $request->get('service_date');
$service_time = $request->get('service_time');
$contact_person = $request->get('contact_person');
$vehicle = $request->get('vehicles');
$services = $request->input('services');
$supplies = $request->input('supplies');
$accessories = $request->input('accessories');
$miscellaneous = $request->input('miscellaneous');
DB::begintransaction();
try{
$data = [
'vehicle_id' => $request->get('vehicle_id'),
'service_date' => $request->get('service_date'),
'service_time' => $request->get('service_time'),
'discount' => $request->get('discount'),
'total' => $request->get('total'),
'technician' => $request->get('technician'),
'assistant' => $request->get('assistant'),
];
$joborders = $this->joborders->create($data);
if($services !== null){
foreach($services as $service) {
$data = [
'job_order_id' => $joborders->id,
'service_name' => $service['service_name'],
'service_qty' => $service['service_qty'],
'service_cost' => $service['service_cost'],
];
$this->items->create($data);
}
}
if($supplies !== null ){
foreach($supplies as $supply){
$data = [
'job_order_id' => $joborders->id,
'supply_name' => $supply['supply_name'],
'supply_qty' => $supply['supply_qty'],
'supply_cost' => $supply['supply_cost'],
];
$this->items->create($data);
}
}
if($accessories !== null){
foreach($accessories as $accessory){
$data = [
'job_order_id' => $joborders->id,
'accessory_name' => $accessory['accessory_name'],
'accessory_qty' => $accessory['accessory_qty'],
'accessory_cost' => $accessory['accessory_cost'],
];
$this->items->create($data);
}
}
if($miscellaneous !== null)
{
foreach($miscellaneous as $misc){
$data = [
'job_order_id' => $joborders->id,
'misc_name' => $misc['miscellaneous_name'],
'misc_qty' => $misc['miscellaneous_qty'],
'misc_cost' => $misc['miscellaneous_cost'],
];
$this->items->create($data);
}
}

Sort mixed models with one dataprovider using ArrayDataProvider

I used ArrayDataProvider to mix models and then merged them into one data-provider. I used the data-provider in grid-view and everything is works fine.
But I need to order the grid-view by one column I tried a lot of solutions but none of them are worked.
This my model code (order by item_order )
public function getAllSelectedItemsInTheUnit($unitId, $grid = false)
{
$finalList = array();
$storiesList = array();
$activityList = array();
$breakList = array();
$stories = UnitStories::find()->joinWith(['story'])->where("unit_id=$unitId")->all();
if (count($stories) > 0) {
foreach ($stories as $item) {
$storiesList[] = [
'key' => self::TYPE_STORY . $item->id,
'id' => $item->id,
'title' => $item->story->title,
'type' => self::TYPE_STORY,
'item_order' => $item->unit_order,
];
}
}
$activities = UnitActivities::find()->joinWith(['activity'])->where("unit_id=$unitId")->all();
if (count($activities) > 0) {
foreach ($activities as $item) {
$activityList[] = [
'key' => self::TYPE_ACTIVITY . $item->id,
'id' => $item->id,
'title' => $item->activity->title,
'type' => self::TYPE_ACTIVITY,
'item_order' => $item->activity_order,
];
}
}
$breaks = UnitBreaks::find()->where("unit_id=$unitId")->all();
if (count($breaks) > 0) {
foreach ($breaks as $item) {
$breakList[] = [
'key' => self::TYPE_BREAK . $item->id,
'id' => $item->id,
'title' => $item->title,
'type' => self::TYPE_BREAK,
'item_order' => $item->unit_order,
];
}
}
$finalList = array_merge($storiesList, $activityList, $breakList);
$dataProvider = new ArrayDataProvider([
'allModels' => $finalList, 'key' => 'key',
'sort' => [
'attributes' => ['item_order'],
],
]);
return $dataProvider;
}
Any solution will be very good even sort array by pure PHP I guess will fix the problem .
You can use usort()
usort($finalList, function ($a, $b) {
return $a['item_order'] < $b['item_order'];
});
Add your condition in callback >, <, <= etc

Array Operations to add / remove entries from 1 to another

I have 2 sets of array:
Data:
$data = [
[
'company_code' => 'ABC',
'supplier_codes' => [
'S-2',
'S-3',
'S-5',
],
],
];
Source (from database):
$database = [
'company_code' => 'ABC',
'suppliers' => [
[
'code' => 'S-1',
],
[
'code' => 'S-2',
'reference' => '12345'
],
[
'code' => 'S-3',
],
[
'code' => 'S-4',
'reference' => 'some string',
]
],
];
What I need to achieve:
If a supplier code is missing in $data but exists in $database,
remove it from $database.
If a supplier code exists in $data but missing in $database, add it into $database
The output of the example here should be as follows:
$output = [
'company_code' => 'ABC',
'suppliers' => [
[
'code' => 'S-2',
'reference' => '12345'
],
[
'code' => 'S-3',
],
[
'code' => 'S-5',
]
],
];
I was thinking of removing the suppliers subarray, then reconstruct the structure based on the data from supplier_codes. But the problem is some of the entries in suppliers may have an optional field called reference.
Try this
<?php
$data = [
[
'company_code' => 'ABC',
'supplier_codes' => ['S-2','S-3','S-5'],
],
];
$database = [
'company_code' => 'ABC',
'suppliers' => [
[
'code' => 'S-1',
],
[
'code' => 'S-2',
'reference' => '12345'
],
[
'code' => 'S-3',
],
[
'code' => 'S-4',
'reference' => 'some string',
]
],
];
foreach($database['suppliers'] as $k=>$v){
foreach($data as $kd=>$vd){
$valueremove = false;
$removeIndex = '';
foreach($vd['supplier_codes'] as $key=>$val){
if($val == $v['code']){
$valueremove = false;
$removeIndex = '';
break;
} else {
$valueremove = true;
$removeIndex = $k;
}
}
if($valueremove == true){
unset($database['suppliers'][$removeIndex]);
} else {
$valueinsert = false;
foreach($data as $kd=>$vd){
foreach($vd['supplier_codes'] as $key=>$val){
foreach($database['suppliers'] as $kc=>$vc){
if($val == $vc['code']){
$valueinsert = false;
$insertIndex = '';
$insertVal = '';
break;
} else {
$valueinsert = true;
$insertIndex = count($database['suppliers'])+1;
$insertVal = $val;
}
}
if($valueinsert == true){
$database['suppliers'][$insertIndex] = array('code'=>$insertVal);
}
}
}
}
}
}
echo "<PRE>"; print_r($database);
I end up solving my problem this way:
$result = $database;
$result['suppliers'] = [];
foreach($data as $tag) {
foreach($tag['supplier_codes'] as $code) {
$found = false;
foreach($database['suppliers'] as $supplier) {
if($supplier['code'] === $code) {
$result['suppliers'][] = $supplier;
$found = true;
}
}
if(!$found) {
$result['suppliers'][] = ['code' => $code];
}
}
}
Output of print_r($result);:
Array
(
[company_code] => ABC
[suppliers] => Array
(
[0] => Array
(
[code] => S-2
[reference] => 12345
)
[1] => Array
(
[code] => S-3
)
[2] => Array
(
[code] => S-5
)
)
)

PHP - search in array and create new one

I want to avoid if it is possible foreach combined with if. I want to search the array, take out the matches and create new one base on result.
In this example I want to create separate arrays for each os -
$os1 = $array;
$os2 = $array...
Array looks like this:
$array = [
0 => [
'id' => 1,
'name' => 'name',
'os' => 1
],
1 => [
'id' => 2,
'name' => 'name',
'os' => 1
],
2 => [
'id' => 3,
'name' => 'name',
'os' => 2
],
3 => [
'id' => 3,
'name' => 'name',
'os' => 2
]
];
Use array_filter to reduce the input array to the expected result
$os = 1;
$data = array_filter($array, function($item) use ($os) {
return $item['os'] == $os;
});
The short one
$os1 = [];
$os2 = [];
$os3 = [];
foreach ($array as $item) {
${'os' . $item['os']}[] = array('id' => $item['id'], 'name' => $item[$name];
}
The better one
$os1 = [];
$os2 = [];
$os3 = [];
foreach ($array as $item) {
switch($item['os']) {
case 1:
$os1[] = array('id' => $item['id'], 'name' => $item[$name]);
break;
case 2:
$os2[] = array('id' => $item['id'], 'name' => $item[$name]);
break;
case 3:
$os3[] = array('id' => $item['id'], 'name' => $item[$name]);
break;
default:
throw new Exception('Unknown Os');
}
}
Also you maybe want to assign array($item['id'] => $item[$name]); instead of array('id' => $item['id'], 'name' => $item[$name]);
$os1 = [];
$os2 = [];
$os3 = [];
foreach ($array as $item) {
${'os' . $item['os']}[] = array($item['id'] => $item[$name]);
}

Categories