Questions regarding update of table on Prestashop - prestashop

I'm trying to update ps_stock_available when I modify the product on Prestashop. But it's unsuccessfull. Could you help me please ?
public function hookActionUpdateQuantity(array $params)
{
$id_product = $params['id_product'];
$product = new Product((int)$id_product);
$id_category = $product->id_category_default;
$db = \Db::getInstance();
$request_loc='SELECT location FROM `'._DB_PREFIX_.'category_location` WHERE `id_category` = '.(int)$id_category;
$location = $db->getValue($request_loc);
$request_id_stock='SELECT id_stock_available FROM `'._DB_PREFIX_.'stock_available` WHERE `id_product` = '.(int)$id_product;
$id_stock_available = $db->getValue($request_id_stock);
$result = $db->update('stock_available', array('location' => $location), '`id_stock_available` = '.(int)$id_stock_available);
}
I have written this code but it doesn't seem to work.

in order to accomplish this task I would rely to the native StockAvailable class metehods getStockAvailableIdByProductId() and setLocation() (check the classes/stock/StockAvailable.php file).
Anyway your code seems to be correct, so I would definitely check for undefined variables and/or something not working in the $db->update statement.
In case, you can change it to :
$db->execute('UPDATE '._DB_PREFIX_.'stock_available SET `location` = "'.pSQL($location).'" WHERE id_stock_available = '.(int)$id_stock_available;

Related

Codeigniter 4 - WHERE clause in Model

It's me again, Van.
Hi everyone,
I hope you're doing well!
I am doing a tutorial on a chat application using Codeigniter 4 with Ajax.
Everything worked fine until I applied the following code in the Model below
public function load_chat_data($sender_id,$receiver_id) {
// $where = ['sender_id' => $sender_id, 'receiver_id' => $receiver_id];
$where1 = "sender_id = $sender_id OR sender_id = $receiver_id";
$where2 = "receiver_id = $receiver_id OR receiver_id = $sender_id";
$builder = $this->db->table('chat_messages');
// $builder->where($where);
$builder->where($where1);
$builder->where($where2);
$builder->orderBy('chat_messages_id','ASC');
$results = $builder->get();
$rows = $results->getResultArray();
if($rows > 0)
{
return $rows;
}
else
{
return false;
}
}
The lines that I commented worked well before they were commented but it was not enough data I wanted to get so I tried to get both data of sender and receiver to display on the view by adding more code. However, when I tried $where1 and $where2 for the WHERE clauses, it didn't work. I think it must be the syntax error. Please correct my codes or any ideas on how the codes work with the same meaning supposed.
Thank you so much!!!
I tried as below, but it still didn't work.
$where1 = "sender_id={$sender_id} OR sender_id={$receiver_id}";
$where2 = "receiver_id={$receiver_id} OR receiver_id={$sender_id}";
Also, I tried:
$where1 = "'sender_id'=$sender_id OR 'sender_id'=$receiver_id";
$where2 = "'receiver_id'=$receiver_id OR 'receiver_id'=$sender_id";
I think you are trying to receive the messages of the conversation between two people. Can you try the following code for this?
$builder->groupStart(); // or $builder->orGroupStart();
$builder->where('sender_id', $sender_id);
$builder->where('receiver_id', $receiver_id);
$builder->groupEnd();
$builder->orGroupStart();
$builder->where('sender_id', $receiver_id);
$builder->where('receiver_id', $sender_id);
$builder->groupEnd();

Kreait : verifySessionCookie() not found

I try to verify a session cookie from the $sessionCookieString = $auth->createSessionCookie($idToken, $oneWeek); which work normally.
But report say that the function is not found.
"Call to undefined method Kreait\Firebase\Auth::verifySessionCookie()"
Didn't understand why.
i have the latest version install.
--- Portion of code below ---
use Kreait\Firebase\Factory;
use Kreait\Firebase\Contract\Auth;
use Kreait\Firebase\Auth\UserQuery;
use Google\Cloud\Firestore\FirestoreClient;
use Kreait\Firebase\Auth\CreateSessionCookie\FailedToCreateSessionCookie;
public function doLogin() {
$factory = (new Factory)->withServiceAccount($this->ekonysJson );
$auth = $factory->createAuth();
$this->auth = $auth;
//print_r($auth);
$signInResult = $auth->signInWithEmailAndPassword("email#dot", "password");
$idToken = $signInResult->idToken();
`print_r($signInResult->refreshToken());`
$oneWeek = new \DateInterval('P7D');
$sessionCookieString = $auth->createSessionCookie($idToken, $oneWeek);
$verifiedSessionCookie = $auth->verifySessionCookie($sessionCookieString)
}
refer to doc https://firebase-php.readthedocs.io/en/stable/authentication.html#session-cookies
if you have any idea.... thanks
Solution for this problem

How to duplicate an existing order (core, php) with Prestashop 1.6.x in FrontPage from client Account - My Orders?

if i use a function in classes\duplicateOrder, found on a previous answer, everytime i refresh the page order-history, all orders from my account->orders are duplicated
the function seems to be ok, so where is the problem?
public function duplicateOrder($id_order)
{
$order = new Order($id_order);
$duplicatedOrder = $order->duplicateObject();
$orderDetailList = $order->getOrderDetailList();
foreach ($orderDetailList as $detail) {
$orderDetail = new orderDetail($detail['id_order_detail']);
$duplicatedOrderDetail = $orderDetail->duplicateObject();
$duplicatedOrderDetail->id_order = $duplicatedOrder->id;
$duplicatedOrderDetail->save();
}
$orderHistoryList = $order->getHistory(Configuration::get('PS_LANG_DEFAULT'));
foreach ($orderHistoryList as $history) {
$orderHistory = new OrderHistory($history['id_order']);
$duplicatedOrderHistory = $orderHistory->duplicateObject();
$duplicatedOrderHistory->id_order = $duplicatedOrder->id;
//$duplicatedOrderHistory->save();
}
}
Where is your call? I think you call it in a foreach that lists the commands.
Regards
in history.tpl I inserted the folowing li option after Reorder button; whenever I press the refresh (F5) the orders are multiplicated (2, 4, 8, 16 and so on)
{l s='Duplicate Order'}
the function was saved in classes\Order\Order.php

Google Sheet API - How to get all sheets name in spreadsheet file?

I use Google Sheet API Version 4.
And i want to get all sheets name what available in that spreadsheet file?
So if you have any way to do it, tell me please. Thanks
public function GoogleServiceSheets(){
$client = new \Google_Client();
$client->setApplicationName('Sheets');
$client->setScopes([\Google_Service_Sheets::SPREADSHEETS]);
$client->setAccessType('offline');
$client->setAuthConfig(GOOGLE_CREDENTIALS);
$service = new Google_Service_Sheets($client);
return $service;
}
public function getSheetID_SheetName($spreadsheetID){
$service = $this->GoogleServiceSheets();
$sheetNumberCounter = 1;
$spreadSheetArr = [];
$worksheetSheets = $service->spreadsheets->get($spreadsheetID)->sheets;
foreach($worksheetSheets as $sheet){
$id = $sheet->properties['sheetId'];
$name = $sheet->properties['title'];
$singleSheetArr = array(
'id'=>$id,
'name'=>$name
);
$spreadSheetArr[$sheetNumberCounter] = $singleSheetArr;
$sheetNumberCounter = $sheetNumberCounter + 1;
}
return $spreadSheetArr;
}
We can call spreadsheet object to get all information of spreadsheet.
$service = new Google_Service_Sheets($client);
$spreadsheetId = 'your spredsheetid';
$sheetInfo = $service->spreadsheets->get($spreadsheetId);
$allsheet_info = $sheetInfo['sheets'];
$idCats = array_column($allsheet_info, 'properties');
Thanks
Google api lets do it.
You need to do api call:
https://spreadsheets.google.com/feeds/worksheets/key/public/basic?alt=json
Where the "key" is your spreadsheet.
Good luck!

TYPO3 6.2 - how to create FileReference in frontend (FE)?

I have the hypothetical Zoo extension in which I've Animal model with photo field and FrontEnd (FE) plugin with typical CRUD actions. photo field is typical FAL's FileReference and it works perfectly in backend (BE) with common TCA IRRE config.
I'm able to successful upload the file to the storage, it's visible in the Filelist module, and I can use it in BE during my Animal editing, anyway I can't create FileReference within my FE plugin.
My current approach looks like this:
/**
* #param \Zoo\Zoo\Domain\Model\Animal $animal
*/
public function updateAction(\Zoo\Zoo\Domain\Model\Animal $animal) {
// It reads proper uploaded `photo` from form's $_FILES
$file = $this->getFromFILES('tx_zoo_animal', 'photo');
if ($file && is_array($file) && $file['error'] == 0) {
/** #type $storageRepository \TYPO3\CMS\Core\Resource\StorageRepository */
$storageRepository = GeneralUtility::makeInstance('\TYPO3\CMS\Core\Resource\StorageRepository');
$storage = $storageRepository->findByUid(5); // TODO: make target storage configurable
// This adds uploaded file to the storage perfectly
$fileObject = $storage->addFile($file['tmp_name'], $storage->getRootLevelFolder(), $file['name']);
// Here I stuck... below line doesn't work (throws Exception no. 1 :/)
// It's 'cause $fileObject is type of FileInterface and FileReference is required
$animal->addPhoto($fileObject);
}
$this->animalRepository->update($animal);
$this->redirect('list');
}
anyway attempt to create reference by this line throws exception:
$animal->addPhoto($fileObject);
How can I resolve this?
Checked: DataHandler approach (link) won't work also, as it's unavailable for FE users.
TL;DR
How to add FileReference to Animal model from existing (just created) FAL record?
You need to do several things. This issue on forge is where I got the info, and some stuff is taken out of Helmut Hummels frontend upload example (and the accompanying blogpost) which #derhansen already commented.
I'm not entirely sure if this is everything you need, so feel free to add things. This does not use a TypeConverter, which you should probably do. That would open further possibilities, for example it would be easily possible to implement deletion and replacement of file references.
You need to:
Create a FAL file reference object from the File object. This can be done using FALs resource factory.
Wrap it in a \TYPO3\CMS\Extbase\Domain\Model\FileReference (method ->setOriginalResource)
EDIT: This step is unnecessary as of TYPO3 6.2.11 and 7.2, you can directly use the class \TYPO3\CMS\Extbase\Domain\Model\FileReference.
But, because the extbase model misses a field ($uidLocal) in 6.2.10rc1, that won't work. You need to inherit from the extbase model, add that field, and fill it. Don't forget to add a mapping in TypoScript to map your own model to sys_file_reference.
config.tx_extbase.persistence.classes.Zoo\Zoo\Domain\Model\FileReference.mapping.tableName = sys_file_reference
The class would look like this (taken from the forge issue):
class FileReference extends \TYPO3\CMS\Extbase\Domain\Model\FileReference {
/**
* We need this property so that the Extbase persistence can properly persist the object
*
* #var integer
*/
protected $uidLocal;
/**
* #param \TYPO3\CMS\Core\Resource\ResourceInterface $originalResource
*/
public function setOriginalResource(\TYPO3\CMS\Core\Resource\ResourceInterface $originalResource) {
$this->originalResource = $originalResource;
$this->uidLocal = (int)$originalResource->getUid();
}
}
Add this to the TCA of the image field, in the config-section (adapt to your table and field names of course):
'foreign_match_fields' => array(
'fieldname' => 'photo',
'tablenames' => 'tx_zoo_domain_model_animal',
'table_local' => 'sys_file',
),
EDIT: Use \TYPO3\CMS\Extbase\Domain\Model\FileReference in this step if on TYPO3 6.2.11 or 7.2 or above.
So at the end add the created $fileRef instead of $fileObject
$fileRef = GeneralUtility::makeInstance('\Zoo\Zoo\Domain\Model\FileReference');
$fileRef->setOriginalResource($fileObject);
$animal->addPhoto($fileRef);
Don't tell anyone what you have done.
Here is the complete function to upload file in TYPO3 using FAL and create filereference
/**
* Function to upload file and create file reference
*
* #var array $fileData
* #var mixed $obj foreing model object
*
* #return void
*/
private function uploadAndCreateFileReference($fileData, $obj) {
$storageUid = 2;
$resourceFactory = \TYPO3\CMS\Core\Resource\ResourceFactory::getInstance();
//Adding file to storage
$storage = $resourceFactory->getStorageObject($storageUid);
if (!is_object($storage)) {
$storage = $resourceFactory->getDefaultStorage();
}
$file = $storage->addFile(
$fileData['tmp_name'],
$storage->getRootLevelFolder(),
$fileData['name']
);
//Creating file reference
$newId = uniqid('NEW_');
$data = [];
$data['sys_file_reference'][$newId] = [
'table_local' => 'sys_file',
'uid_local' => $file->getUid(),
'tablenames' => 'tx_imageupload_domain_model_upload', //foreign table name
'uid_foreign' => $obj->getUid(),
'fieldname' => 'image', //field name of foreign table
'pid' => $obj->getPid(),
];
$data['tx_imageupload_domain_model_upload'][$obj->getUid()] = [
'image' => $newId,
];
$dataHandler = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(
'TYPO3\CMS\Core\DataHandling\DataHandler'
);
$dataHandler->start($data, []);
}
where $filedata =
$this->request->getArgument('file_input_field_name');
And
$obj = //Object of your model for which you are creating file
reference
This example does not deserve a beauty prize but it might help you. It works in 7.6.x
private function uploadLogo(){
$file['name'] = $_FILES['logo']['name'];
$file['type'] = $_FILES['logo']['type'];
$file['tmp_name'] = $_FILES['logo']['tmp_name'];
$file['size'] = $_FILES['logo']['size'];
// Store the image
$resourceFactory = \TYPO3\CMS\Core\Resource\ResourceFactory::getInstance();
$storage = $resourceFactory->getDefaultStorage();
$saveFolder = $storage->getFolder('logo-companies/');
$newFile = $storage->addFile(
$file['tmp_name'],
$saveFolder,
$file['name']
);
// remove earlier refereces
$GLOBALS['TYPO3_DB']->exec_DELETEquery('sys_file_reference', 'uid_foreign = '. $this->getCurrentUserCompanyID());
$addressRecord = $this->getUserCompanyAddressRecord();
// Create new reference
$data = array(
'table_local' => 'sys_file',
'uid_local' => $newFile->getUid(),
'tablenames' => 'tt_address',
'uid_foreign' => $addressRecord['uid'],
'fieldname' => 'image',
'pid' => $addressRecord['pid']
);
$GLOBALS['TYPO3_DB']->exec_INSERTquery('sys_file_reference', $data);
$newId = $GLOBALS['TYPO3_DB']->sql_insert_id();
$where = "tt_address.uid = ".$addressRecord['uid'];
$GLOBALS['TYPO3_DB']->exec_UPDATEquery('tt_address', $where, array('image' => $newId ));
}