Update Query in Prestashop 1.7 - prestashop-1.7

I customized an update profile page; how do I update the user details in the backend?
I tried doing this query, but its not working
update($table, $data, $where = '', $limit = 0, $null_values = false, $use_cache = true, $add_prefix = true)

Related

Only one page of product got with rest admin api

I have so many pages of products on my development store.But when I try to use products.json to get all of my products, it only take 50 listings(one page).Could anybody solve my doubt?
<?php
$url = 'https://myshopifystore/admin/api/2019-07/products.json';
$result = file_get_contents($url);
$data = json_decode($result, true);
dd($data);
my result like this picture:
The limit property on the request has a default of 50 up to 250. In case you want more use a loop to search though every page until the end.
GET /admin/api/2019-07/products.json?limit=250?page=1
Use
GET /admin/api/2019-07/products/count.json
to get the total product you want to search.
More info about paginated page here
EDIT 1 : The paginated ?page= is now deprecated. It will be remove in version 2020-07. You should use cursor-based pagination.
Below function can help to fetch resources with cursor based pagination in new shopify API
public function request($method,$url,$param = []){
$client = new \GuzzleHttp\Client();
$url = 'https://'.$this->username.':'.$this->password.'#'.$this->domain.'/admin/api/2019-10/'.$url;
$parameters = [
'headers' => [
'Content-Type' => 'application/json',
'Accept' => 'application/json'
]
];
if(!empty($param)){ $parameters['json'] = $param;}
$response = $client->request($method, $url,$parameters);
$responseHeaders = $response->getHeaders();
$tokenType = 'next';
if(array_key_exists('Link',$responseHeaders)){
$link = $responseHeaders['Link'][0];
$tokenType = strpos($link,'rel="next') !== false ? "next" : "previous";
$tobeReplace = ["<",">",'rel="next"',";",'rel="previous"'];
$tobeReplaceWith = ["","","",""];
parse_str(parse_url(str_replace($tobeReplace,$tobeReplaceWith,$link),PHP_URL_QUERY),$op);
$pageToken = trim($op['page_info']);
}
$rateLimit = explode('/', $responseHeaders["X-Shopify-Shop-Api-Call-Limit"][0]);
$usedLimitPercentage = (100*$rateLimit[0])/$rateLimit[1];
if($usedLimitPercentage > 95){sleep(5);}
$responseBody = json_decode($response->getBody(),true);
$r['resource'] = (is_array($responseBody) && count($responseBody) > 0) ? array_shift($responseBody) : $responseBody;
$r[$tokenType]['page_token'] = isset($pageToken) ? $pageToken : null;
return $r;
}
using above function in controller
$ids = [];
$nextPageToken = null;
do{
$response = $shop->request('get','products.json?limit=250&page_info='.$nextPageToken.'&rel=next');
foreach($response['resource'] as $product){
array_push($ids, $product['id']);
}
$nextPageToken = $response['next']['page_token'] ?? null;
}while($nextPageToken != null);

Magento2 product import pragmatically i want skip images if not present on csv?

I am trying to upload product pragmatically through CSV all script run well but i have only 1 issue i have 3 column of images in my CSV 1st images are available but in 2nd and 3rd column some images are missing name are present but images are not found in directory but when i run script only one images are save rest of present images are not saved
My Code is
<?php
use Magento\Framework\App\Bootstrap;
include('app/bootstrap.php');
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$objectManager1 = Magento\Framework\App\ObjectManager::getInstance();
$directoryList = $objectManager1->get('\Magento\Framework\App\Filesystem\DirectoryList');
$path = $directoryList->getPath('media');
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
$myarray = glob("test.csv");
usort($myarray, create_function('$a,$b', 'return filemtime($a) - filemtime($b);'));
if(count($myarray)){
$csv_map = array_map('str_getcsv', file($myarray[count($myarray)-1]));
array_walk($csv_map, function(&$a) use ($csv_map) {
$a = array_combine($csv_map[0], $a);
});
array_shift($csv_map);
$message = '';
$count = 1;
foreach($csv_map as $data){
//echo '<pre>';print_r($data);exit;
$product = $objectManager->create('Magento\Catalog\Model\Product');
$product->setName(trim($data['NAME']));
$product->setTypeId('simple');
$product->setAttributeSetId(4);
$product->setSku(trim($data['MODEL NUMBER']));
$product->setUrlPath(trim($data['url']).trim($data['MODEL NUMBER']).('zenith'));
$product->setWebsiteIds(array(1));
$product->setVisibility(4);
$product->setBrand(trim($data['BRAND']));
$product->setFunctions(trim($data['FUNCTIONS']));
$product->setPowerReserve(trim($data['POWER RESERVE']));
$product->setStrapType(trim($data['STRAP TYPE']));
$product->setWarranty(trim($data['WARRANTY']));
$product->setFamily(trim($data['FAMILY']));
$product->setWaterResistance(trim($data['WATER RESISTANCE']));
$product->setCreatedAt(strtotime('now'));
$product->setPrice(trim($data['PRICE']));
$product->setcaseSize(trim($data['CASE SIZE']));
//$product->setColor(trim($data['dial_colour']));
$product->setMovement(trim($data['MOVEMENT']));
$product->setCaseShape(trim($data['CASE SHAPE']));
//$product->setGender(trim($data['gender']));
$product->setCaseMaterial(trim($data['CASE MATERIAL']));
//$_product->setShortDescription(trim($data['Short Description'])); // add text attribute
//$_product->setDescription(trim($data['Long Description'])); // add text attribute
$img_url = trim($data['IMAGE1']);
$img_url1=trim($data['IMAGE2']);
$img_url2=trim($data['IMAGE3']);
$dir = $directoryList->getPath('media').'/big/';
$imgpath = $dir.$img_url;
$imgpath1 = $dir.$img_url1;
$imgpath2 = $dir.$img_url2;
$product->addImageToMediaGallery($imgpath, array('image'), false, false);
if (file_exists($dir.$img_url1)) {
$product->addImageToMediaGallery($imgpath1, array('thumbnail'), false, false);
}
if (file_exists($dir.$img_url2)) {
$product->addImageToMediaGallery($imgpath2, array('small_image'), false, false);
}
$product->setStockData(array(
'use_config_manage_stock' => 0, //'Use config settings' checkbox
'manage_stock' => 1, //manage stock
'min_sale_qty' => 1, //Minimum Qty Allowed in Shopping Cart
'max_sale_qty' => 2, //Maximum Qty Allowed in Shopping Cart
'is_in_stock' => 1, //Stock Availability
'qty' => 100 //qty
)
);
$product->save();
}
echo'sucess';
}
?>
please suggest what i am doing wrong in image section
Check the image existence By
#exif_imagetype($image_path).
Thank you

$this -> cart->insert(); not working on live while working on localhost

Hi i am having problem on my live server when i am checking the add to cart builtin function of CI. But its working fine on my localhost.
Here is my Model code where i am saving the cart
$id = $this->input->post('product_id'); // Assign posted product_id to $id
$qty = 1;// Assign posted quantity to $cty
$this->db->from($this->table_name);
$this->db->join($this->desc_table_name, "$this->desc_table_name.products_id = $this->table_name.id");
$this -> db -> where('id', $id); // Select where id matches the posted id$this->db->from($this->table_name);
$this -> db -> limit(1);
$query = $this->db->get(); // Select the products where a match is found and limit the query by 1
// Check if a row has been found
if($query->num_rows > 0){
foreach ($query->result() as $row)
{
$data = array(
'id' => $id,
'qty' => $qty,
'price' => $row->price,
'name' => "$row->title",
'options' => array('description' => $row->description,'short_desc'=> $row->short_desc,'image'=>$row->image,),
);
//print_r($data);
$res = $this -> cart -> insert($data);
return TRUE;
}
// Nothing found! Return FALSE!
}else{
return FALSE;
}`
and my ajax function is like this
var link = window.location.protocol + "//" + window.location.host + "/youth_fashion/";
$(".add_item").click(function() {
// Get the product ID and the quantity
var id = $(this).attr('id');
$.post(link + "front/cart_controller/add_cart_item1", { product_id: id, ajax: '1' },
function(data){
if(data == 'true'){
$.get(link + "front/cart_controller/show_cart", function(cart){
$("#cart_content").html(cart);
var x = location.href;
window.location.href= x;
});
}else{
alert("Product does not exist");
}
});
return false;
});`
I am using CI 2.0. Thank you in advance
The issue is resolved.
The issue is in session file (config.php). I am using the library of cart but it is not storing the data into table.
$config['sess_use_database'] = TRUE; i turned true and its storing and working for me

Magento Changing Default Payment Method

I have a function that runs raw SQL queries to our database in Magento. What the function does is changes the customer's default credit card to a value passed to the function. My question is how would I rewrite the function utilizing Magento models. The current function works, but we'd rather have it not be directly interfacing with SQL.
Here is the function:
public function setDefaultPayment($value)
{
$customerId = $this->_getSession()->getCustomer()->getId();
$write = Mage::getSingleton('core/resource')->getConnection('core_write');
$read = $write->query("SELECT entity_type_id FROM eav_entity_type WHERE entity_type_code='customer'");
$row = $read->fetch();
$entity_type_id = $row['entity_type_id'];
$read = $write->query("SELECT attribute_id FROM eav_attribute WHERE attribute_code='default_payment' AND entity_type_id = $entity_type_id");
$row = $read->fetch();
$attribute_id = $row['attribute_id'];
$read = $write->query("SELECT * FROM customer_entity_int WHERE entity_type_id='$entity_type_id' AND attribute_id='$attribute_id' AND entity_id='$customerId'");
if ($row = $read->fetch()) {
$write->update(
'customer_entity_int',
array('value' => $value),
"entity_type_id='$entity_type_id' AND attribute_id='$attribute_id' AND entity_id='$customerId'"
);
} else {
$write->insert(
'customer_entity_int',
array(
'entity_type_id' => $entity_type_id,
'attribute_id' => $attribute_id,
'entity_id' => $customerId,
'value' => $value
)
);
}
}
If I read you code right, you want to update the customer attribute default_payment with a value given.
For that you need to:
Load the customer by id
Set the new value for the customer attribute default_payment
Save the customer
public function setDefaultPayment($value)
{
$customerId = $this->_getSession()->getCustomer()->getId();
$write = Mage::getSingleton('core/resource')->getConnection('core_write');
$customer = Mage::getModel('customer/customer')->load($customerId);
$oldValue = $customer->getDefaultPayment(); // optional, just for checking
$customer->setDefaultPayment($value);
$customer->save();
}

Creating Configurable product on import csv

When a new simple product is added (via CSV or manually) we need to check if the appropriate configurable product has been added (where SKU = "item_number-item_colour_code" e.g. BLEA2606B-BK001). If the configurable product exists then associate the simple product. If the configurable product does not exist then create using the data in the simple product AND then associate the simple product.
I found some help from HERE but don't know how check if configurable product already exists, and if not how to create one.
Here is the script file that I downloaded. Can anybody advice if this will work with my scenario?
EDITED
I have scraped the idea of creating configurable product in import. I am doing it by capturing the catalog_product_save_after event now. Hopefully that will get me somewhere.
EDITED 2
OK, Finally, I have it working. I'm doing it in the observer. I know it slows down the product save process but couldn't think of any other way. Thats what I'm doing:
public function productSave($observer)
{
$p = $observer->getProduct();
$pr = Mage::getModel('catalog/product')->load($p->getId());
$attributeValue = Mage::getResourceModel('catalog/product')->getAttributeRawValue($pr->getId(), 'size'); //loads attribute option value
$qtyStock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($pr)->getQty();
Mage::log('Qty: '.$qtyStock.$pr->getId(), null, 'test.txt');
if ($pr->getTaxClassId() == '0' || !isset($pr->getTaxClassId)) {
$taxClass = 'None';
} elseif ($pr->getTaxClassId() == '2') {
$taxClass = 'Taxable Goods';
} elseif ($pr->getTaxClassId() == '4') {
$taxClass = 'Shipping (not used by AvaTax)';
} elseif ($pr->getTaxClassId() == '5') {
$taxClass = 'General';
}
$_configSku = $pr->getItemNumber().'-'.$pr->getItemColourCode();
$category = array();
$categoryCollection = $pr->getCategoryCollection();
foreach ($categoryCollection as $cat) {
$category[] = $cat->getId();
}
$_configExist = Mage::getModel('catalog/product')->loadByAttribute('sku',$_configSku);
if($_configExist && $_configSku != '-') {
//Mage::log($_configExist, null, 'test.txt');
//Mage::log($_configSku, null, 'test.txt');
$new_ids = array();
$current_ids = $_configExist->getTypeInstance()->getUsedProductIds();
foreach($current_ids as $temp_id)
{
$new_ids[] = $temp_id;
}
}
if(!$_configExist && $_configSku != '-') {
$att_size = Mage::getModel('eav/entity_attribute')->loadByCode('catalog_product','size');
$att_sizes = $this->__getAttList('size');
$confProduct = Mage::getModel('catalog/product');
$confProduct->setAttributeSetId('10');
$confProduct->setSku($_configSku);
$confProduct->setTypeId('configurable');
$confProduct->setName($pr->getName());
$confProduct->setDescription($pr->getDescription());
$confProduct->setShortDescription($pr->getShortDescription());
$confProduct->setCreatedAt(strtotime('now'));
$confProduct->setPrice($pr->getPrice());
$confProduct->setStatus(1);
$confProduct->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH);
$confProduct->setWebsiteIDs(array(1));
$confProduct->setStockData(array(
'is_in_stock' => 1,
'qty' => 9999
));
$confProduct->setTaxClassId( $taxClass );
$confProduct->setCategoryIds( $category );
/* Set Configurable Attributes */
$confProduct->setConfigurableAttributesData($tmp = array(
array_merge($att_size->getData(), array('label' => '', 'values' => $size_values))
));
$simpleProducts = array(
$pr->getId()=>array( 'attribute_id'=>'145', 'label'=>'size', 'value_index'=>$attributeValue, 'is_percent'=>0, 'pricing_value'=>'' )
);
/* Set Associated Products */
$confProduct->setConfigurableProductsData( $simpleProducts );
//print_r( get_class_methods( $confProduct ) );
$confProduct->save();
}
elseif ($_configExist && !in_array($pr->getId(), $new_ids)) {
$new_ids = array();
$current_ids = $_configExist->getTypeInstance()->getUsedProductIds();
$current_ids[] = $pr->getId();
$current_ids = array_unique($current_ids);
foreach($current_ids as $temp_id)
{
parse_str("position=", $new_ids[$temp_id]);
}
Mage::log('inside', null, 'test.txt');
Mage::log($current_ids, null, 'test.txt');
$_configExist->setConfigurableProductsData($new_ids)->save();
}
All works fine with manual product save/update and import csv (it is slow but works). The only thing is, in configurable product, the Attribute Name field is empty. How to set attribute name there?
with magmi you can easily create configurable products, and more awesome stuff
I have found the way. See EDITED 2 section in the question for the solution.

Resources