Prestashop webservice DELETE categories remove_associated - prestashop

In prestashop there is an option that asks you if you want to remove all the products in the category you want to remove, do you know which is the way with the API?
https://devdocs.prestashop.com/1.7/webservice/tutorials/prestashop-webservice-lib/delete-resource/
<?php
try {
$webService = new PrestaShopWebservice('http://example.com/', 'ZR92FNY5UFRERNI3O9Z5QDHWKTP3YIIT', false);
$id = 2;
$webService->delete([
'resource' => 'customers',
'id' => $id, // Here we use hard coded value but of course you could get this ID from a request parameter or anywhere else
]);
echo 'Customer with ID ' . $id . ' was successfully deleted' . PHP_EOL;
} catch (PrestaShopWebserviceException $e) {
echo 'Error:' . $e->getMessage();
}
In its web site it only shows an example to remove categories.

Iterate on products and delete. Example for 1 language shop, 10000 products catalog:
$products = Product::getProducts(1, 0, 10000, 'id_product', 'DESC', $id_category_to_remove);
$webService = new PrestaShopWebservice($yourUri, $yourKey, false);
foreach ($products as $product) {
$webService->delete([
'resource' => 'products',
'id' => $product['id_product'],
]);
}

Related

How can I change the WordPress Custom Post & Categories to New Custom Post & Categories

In my database I have 2 custom post type and their category.
Old Post Type and Category
Post Type = real-estate
Category = re-category
Mew Post Type and Category
Post Type = real_estate
Category = real_estate_category
Now I want to convert all old post type and their categories to new custom post type and their categories.
So, using this code I can get all the old post type and can change the old post type to new post type BUT how can I change the old post type's attached categories to new post type categories?
add_action( 'template_redirect', 'everstrap_do_migration' );
function everstrap_do_migration() {
// Convert their real-estate to real_estate post type
if( $_REQUEST['action'] && $_REQUEST['action'] == 'convert_re_post_type' ) {
global $wpdb;
$old_custom_post_type = 'real-estate';
$ne_custom_post_type = 'real_estate';
// A sql query to return all real-esate post
$results = $wpdb->get_results( $wpdb->prepare( "SELECT ID, post_title FROM {$wpdb->posts} WHERE post_type = %s and post_status = 'publish'", $old_custom_post_type ), ARRAY_A );
// Return null if we found no results
if ( ! $results )
return;
foreach ( $result as $key => $value) {
// Update query
$update = $wpdb->update(
$wpdb->posts,
array(
'post_type' => $new_custom_post_type,
),
array(
'post_type' => $old_custom_post_type,
),
array(
'%s',
),
array(
'%s'
)
);
if( $update ) {
echo 'Updated post id ' . $value['ID'];
} else {
echo 'can\' update';
}
}
// echo '<pre>';
// print_r( $results );
// echo '</pre>';
}
}
$new = "real_estate_category";
$old = "re-category";
$cat = get_terms( array (
'taxonomy' => $old,
'hide_empty' => false,
));
global $wpdb;
$table = $wpdb->prefix . "term_taxonomy";
foreach ($cat as $c) {
$wpdb->update($table, array("taxonomy" => $new), array("term_id" => $c->term_id), array("%s"));
}

How can i get product details at order confirmation page in prestashop?

I have created custom module to send curl request.In this i get shipping address of current user but i want to get product details as well in order confirmation page. How can i do this?
Here Is my Code:
public function hookOrderConfirmation($params)
{
**Here i want to print product details**
echo $this->context->customer->firstname ."<br/>";
echo $this->context->customer->lastname ."<br/>";
echo $this->context->customer->email ."<br/>";
die("GET ALL DETAILS.");
//set POST variables
$url = 'http://localhost/wrd-folder/web-service/';
$fields = array(
'first_name' => urlencode("Testing1"),
'last_name' => urlencode("Testing2"),
'username' => urlencode("Testing1"),
'email' => urlencode("testing#gmail.com"),
'membership_id' => urlencode("676"),
'password' => urlencode("12345678"),
'password2' => urlencode("12345678")
);
//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
//Lets display our template file.
return $this->display(__FILE__, 'sentcurl.tpl');
} // End of hookOrderConfirmation
In a few lines you can acomplish this task. You have 2 options:
Get an products array and their price
$order = $params['objOrder'];
// array with products with price, quantity (with taxes and without)
$products = $order->getProducts();
Get a more detailed array with products:
$order = $params['objOrder'];
$products_with_details = $order->getProductsDetail();
You can get like:
$order = new Order($id_order);
$products = $order->getProducts();
foreach($products as $product):
..
$product has every param that you need.

Trouble passing SQL data to view in codeigniter

I have a form that I am using to allow people to input data and then upload a preset picture. I want to label that picture as the form_id. I am able to run a LAST_INSERT_ID() query and display it after I insert the form in my view but I can't seem to echo that information out anywhere else. I need the query to select_last_id to run after my $update query or the ID number will be off. Could anyone assist in helping me pass just the value of the row to my view? Here is the code from my controller.
function inspection() {
if($this->input->post('submit')) {
$array = array(
'trlr_num' => $this->input->post('trlr_num'),
'seal' => $this->input->post('seal'),
'damaged' => $this->input->post('damaged'),
'truck_num' => $this->input->post('truck_num'),
'driver_name' => $this->input->post('driver_name'),
'car_code' => $this->input->post('car_code'),
'origin' => $this->input->post('origin'),
'lic_plate' => $this->input->post('lic_plate'),
'del_note' => $this->input->post('del_note'),
'live_drop' => $this->input->post('live_drop'),
'temp' => $this->input->post('temp'),
'level' => $this->input->post('level'),
'ship_num' => $this->input->post('ship_num'),
'trlr_stat' => $this->input->post('trlr_stat'),
'comment' => $this->input->post('comment')
);
$update = $this->trailer_model->insert_form($array);
$query = $this->trailer_model->select_last_id();
$result =& $query->result_array();
$this->table->set_heading('ID');
$data['table'] = $this->table->generate_table($result);
unset($query,$result);
}
$level = $this->trailer_model->select_fuel_level();
$result = $level->result_array();
$data['options'] = array();
foreach($result as $key => $row) {
$data['options'][$row['level']] = $row['level'];
}
unset($query,$result,$key,$row);
$data['label_display'] = 'Fuel Level';
$data['field_name'] = 'level';
$status = $this->trailer_model->select_trailer_type();
$result = $status->result_array();
$data['options1'] = array();
foreach($result as $key => $row) {
$data['options1'][$row['trlr_stat']] = $row['trlr_stat'];
}
unset($query,$result,$key,$row);
$data['label_display1'] = 'Trailer Status';
$data['field_name1'] = 'trlr_stat';
$data['page_title'] = 'Trailer Inspection';
$data['main_content'] = 'dlx/inspection/trailer_inspection_view';
return $this->load->view('includes/template',$data);
}
}
Anything you want to display on a view, you must pass to it.
When you're setting $data, you missed adding $query to it.
Controller:
I understand that $query = $this->trailer_model->select_last_id(); is returning just an ID, so:
$data['last_id'] = $query;
But if $query = $this->trailer_model->select_last_id(); does not return just an ID, but an array or something else, you shall include to return the ID in your model method. Actually, it'd be crucial to know what $this->trailer_model->select_last_id(); is returning.
View:
echo $last_id; -> must echo the last ID, if select_last_id() method from your model returns what it has to return.

Why I cannot post image through twitter api?

this is my code, i am trying to post tweet with image, but only text get posted?I really really want to post image as well. I am pulling my hair out for that, HELP!!?
<?php
error_reporting(E_ALL);
require_once('TwitterAPIExchange.php');
//echo 'start';
/** Set access tokens here - see: https://dev.twitter.com/apps/ **/
require_once('connect.php');
$recid=$_GET['recid'];
//echo $recid;
$dsn='mysql:host='.$hostname.';dbname=twitter_db';
try{
$dbh=new PDO($dsn,$username,$password);
$dbh->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$stmt=$dbh->prepare("SELECT * FROM gr_twitter WHERE recid=:recid");
$stmt->execute(array(
'recid'=>$recid
));
$foundResult=$stmt->fetchAll();
$tweetmsg=$foundResult[0]['tweet'];
$tweetImage=$foundResult[0]['tweetImageName'];
$timestamp=$foundResult[0]['sentTimestamp'];
print_r($foundResult);
$stmt2=$dbh->prepare("UPDATE gr_twitter SET sent=1 WHERE recid=:recid");
$stmt2->execute(array(
'recid'=>$recid
));
}
catch(PDOException $e){}
// Perform a GET request and echo the response **/
/** Note: Set the GET field BEFORE calling buildOauth(); **/
$url = 'https://api.twitter.com/1.1/statuses/update.json';
$requestMethod='POST';
////images is stored in D:\Databases\RC_Data_FMS\images\Files\images\tweetImage folder
$tweetImage='D:\Databases\RC_Data_FMS\images\Files\images\tweetImage/images.jpg';
$postfields = array(
'status' => $tweetmsg,
'media' => "#{$tweetImage}"
);
/** POST fields required by the URL above. See relevant docs as above **/
//print_r($postfields).'<br />';
$twitter = new TwitterAPIExchange($Yh_settings);
$response= $twitter->buildOauth($url, $requestMethod)
->setPostfields($postfields)
->performRequest();
echo "Success, you just tweeted!<br />";
var_dump(json_decode($response));
//////////////////////////////////////////////////////////////////////////
function objectToArray($d)
{
if (is_object($d)) {
// Gets the properties of the given object
// with get_object_vars function
$d = get_object_vars($d);
}
if (is_array($d)) {
/*
* Return array converted to object
* Using __FUNCTION__ (Magic constant)
* for recursive call
*/
// return array_map(__FUNCTION__, $d);
} else {
// Return array
// return $d;
}
}
?>
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
I recommend you to use tmhOAuth library if you want to post images that are located in your server.
Here you have an example:
<?php
require_once('./tmhOAuth.php');
$tmhOAuth = new tmhOAuth(array(
'consumer_key' => CONSUMER_KEY,
'consumer_secret' => CONSUMER_SECRET,
'user_token' => OAUTH_TOKEN,
'user_secret' => OAUTH_TOKEN_SECRET
));
$tweetText = 'Your text here';
$imageName = 'picture.png';
$imagePath = dirname(__FILE__) . DIRECTORY_SEPARATOR . $imageName;
$code = $tmhOAuth->request(
'POST',
$tmhOAuth->url('1.1/statuses/update_with_media'),
array(
'media[]' => "#{$imagePath};type=image/png;filename={$imageName}",
'status' => $tweetText
),
true, // use auth
true // multipart
);
?>
Hope this helps!

Magento API - Get Product Names from specific Category

I'm working on the Magento API and I got some questions...
I try to get all Product Names from a specific category at Magento.
here's my code for that:
<?php
$host = "www.host.tld/index.php";
$client = new SoapClient("http://".$host."/api/soap/?wsdl");
$apiuser= "user"; //webservice user login
$apikey = "pass"; //webservice user pass
try {
// Login
$sess_id= $client->login($apiuser, $apikey);
// Getting all products from category
$filters = array( 'category_ids' => array('107') );
$productList = $client->call($sess_id, 'catalog_category.assignedProducts', $filters);
//iterate and get all the product_id's and put it into one array
foreach($productList as $products => $values){
if (isset($values['product_id']) || array_key_exists('product_id', $values)) {
$product_ids[] = $values['sku'];
}
}
//Get product details from product_id
foreach($product_ids as $key => $values) {
$details = $client->call( $sess_id, 'product.info', array($values));
#echo $details['name'];
}
}
catch (Exception $e) { //while an error has occured
echo "==> Error: ".$e->getMessage();
exit();
}
?>
The main problem I have is, that the performance I get is not the best. For each "product name" I make one api-call for getting all products. Every time for each product. That's probably not so clever.
What can I optimize. Am I missing something?
I can imagine, that if I want to get the details from more than one category, my server will crash ;). We have about 1000 products in our shop.
Thanks for the help.
Try
$proxy = new SoapClient('http://magentohost/api/soap/?wsdl');
$sessionId = $proxy->login('apiUser', 'apiKey');
$filters = array(
'id' => array('in' => array(<product_id_1>, <product_id_2>, ...))
);
$products = $proxy->call($sessionId, 'product.list', array($filters));
If you need some extended info about product - you should alter magento code, see this my answer on the similar questionL Magento API v1- List prices for all products in one call
You can use to catalog_category.assignedProducts
Retrieve the list of products assigned to a required category.
try this if you are using SOAP V1:
$client = new SoapClient('http://magentohost/api/soap/?wsdl');
// If somestuff requires api authentification,
// then get a session token
$session = $client->login('apiUser', 'apiKey');
$result = $client->call($session, 'catalog_category.assignedProducts', '4');
var_dump($result);
// If you don't need the session anymore
//$client->endSession($session);
if you are using SOAP V2:
$proxy = new SoapClient('http://magentohost/api/v2_soap/?wsdl'); // TODO : change url
$sessionId = $proxy->login('apiUser', 'apiKey'); // TODO : change login and pwd if necessary
$result = $proxy->catalogCategoryAssignedProducts($sessionId, '4');
var_dump($result);
and the respond would be like this:
array
0 =>
array
'product_id' => string '1' (length=1)
'type' => string 'simple' (length=6)
'set' => string '4' (length=1)
'sku' => string 'n2610' (length=5)
'position' => string '1' (length=1)
1 =>
array
'product_id' => string '2' (length=1)
'type' => string 'simple' (length=6)
'set' => string '4' (length=1)
'sku' => string 'b8100' (length=5)
'position' => string '1' (length=1)