Worry in the backoffice of my module undefined index prestashop - module

I developed a prestashop module, when I am in the backoffice of my module, I have many with errors:
Notice à la ligne 30 du fichier
C:\xampp2\htdocs\projet_presta\app\cache\dev\smarty\compile\86\1c\1c\861c1cb1906b13002a1460e54203e8a370598366.file.displayContent.tpl.php
[8] Undefined index: avisnote Notice à la ligne 30 du fichier
C:\xampp2\htdocs\projet_presta\app\cache\dev\smarty\compile\86\1c\1c\861c1cb1906b13002a1460e54203e8a370598366.file.displayContent.tpl.php
[8] Trying to get property of non-object
in my module avisnote.php file:
public function displayContent()
{
$avisnote = Db::getInstance()->executeS('SELECT * FROM `'._DB_PREFIX_.'avisnote` LIMIT 1');
print_r($avisnote);
foreach ($avisnote as $row)
{
$file = $row['url'];
$state = $row['etat'];
}
if(isset($fileContent) && !empty($fileContent))
{
$fileContent = file_get_contents($file, NULL, NULL);
$var_sep = explode(";", $fileContent);
$nb_avis = $var_sep[0];
$note = $var_sep[1];
$this->context->$smarty->assign('avisnote',
array('nb_avis' => $nb_avis,
'note'=>$note,
'etat'=>$state));
}
return $this->display(__FILE__,'views/templates/hook/displayContent.tpl');
}
the paths of my files:
avisnote.php : Modules/avisnote/
displayContent.tpl : Modules/avisnote/views/templates/hook/
displayContent.tpl:
<p></p>
<div itemprop="itemreviewed" itemscope="" itemtype="http://data-vocabulary.org/Review-aggregate">
<span itemprop="itemreviewed">Mywebsite</span> <span itemprop="rating" itemscope="" itemtype="http://data-vocabulary.org/Rating"> <span itemprop="average">{$avisnote.note}</span> sur <span itemprop="best">5</span> </span>
<br />basé sur <span itemprop="votes">{$avisnote.nb_avis}</span> avis Avis Vérifiés</div>
</div>

You have at least 2 errors in your code.
First you check if isset($fileContent) then use the variable $file. Second, you have $this->context->$smarty ... Your code fixed should be more like:
public function displayContent()
{
$avisnote = Db::getInstance()->executeS('SELECT * FROM `'._DB_PREFIX_.'avisnote` LIMIT 1');
print_r($avisnote);
foreach ($avisnote as $row)
{
$file = $row['url'];
$state = $row['etat'];
}
$nb_avis = $note = $state = '';
if(isset($file) && !empty($file))
{
$fileContent = file_get_contents($file, NULL, NULL);
$var_sep = explode(";", $fileContent);
$nb_avis = $var_sep[0];
$note = $var_sep[1];
}
$this->context->smarty->assign('avisnote',
array('nb_avis' => $nb_avis,
'note'=>$note,
'etat'=>$state));
return $this->display(__FILE__,'views/templates/hook/displayContent.tpl');
}

Related

Is there a way to update an HTML page with input from each prompt while continually prompting for multiple inputs?

I am creating a JavaScript hangman game and am having trouble figuring out how I would prompt the user to guess the letters of the hangman puzzle, and then update the page with .innerHTML the guessed letter in place of the dashes I have on the screen.
I have a while loop set up to prompt for the guesses and do the work of placing the letters that are guessed in the length of the word, but it will prompt continually until more than 10 guesses are made and than print the dashes to screen.
This is the code that I am currently using.
function myGame()
{
var player_name = document.getElementById("player");
document.getElementById("user_name").innerHTML = "Welcome " + player_name.value + " to Wheel of Fortune";
var count = 0;
var phrase = "parseint";
var lgth = phrase.length; var checkWin = false; var correct_guess = false; var guess;
var numCols = lgth; new_word = ""; var crazyWord = ""; var new_word = ""; crzLgth = crazyWord.length;
for (var cols = 0; cols < numCols; cols++)
document.getElementById('wheel_game' + cols).innerHTML = ("/ ");
document.getElementById('hWord').innerHTML = "The word was " + (phrase);
while (checkWin === false && count < 10)
{
correct_guess = false;
guess = prompt("Guess a letter");
for (var j = 0; j < lgth; j++)
{
if (guess === phrase.charAt(j))
{
correct_guess = true;
count = count + 1;
document.getElementById('wheel_game' + j).innerHTML = guess;
for (var nw = 0; nw < lgth; nw++)
crazyWord = crazyWord + (document.getElementById('wheel_game' + nw).innerHTML);
}
new_word = crazyWord.substr((crzLgth - lgth), lgth);
checkWin = checkWord(phrase, new_word);
}
if (checkWin === true)
{
document.getElementById("result").innerHTML = ("You win!");
}
else if (checkWin === false)
{
document.getElementById("result").innerHTML = ("You Lose");
if (correct_guess === false)
count = count + 1;
if (count === 10)
{
guess = prompt("One last chance to guess the word");
}
if(guess.length !== 1 && guess !== "parseint") {
break;
}
else if(guess === 'parseint' && guess.length === 8) {
checkWin = true;
document.getElementById("result").innerHTML = ("You win!");
}
}
}
function checkWord(phrase, otherWord)
{
var cleanWord;
cleanWord = otherWord;
if (phrase === cleanWord)
return true;
else
return false;
}
}
Here is my HTML
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<meta name="description" content="Hangman">
<title>Hangman</title>
</head>
<body>
<h1>Welcome player</h1>
<p> Please Enter your name. </p>
<input type="text" id="player" onchange="myGame();" />
<p id="user_name"> </p> <br>
<div id="wheel_game0"></div> <br>
<div id="wheel_game1"></div> <br>
<div id="wheel_game2"></div> <br>
<div id="wheel_game3"></div> <br>
<div id="wheel_game4"></div> <br>
<div id="wheel_game5"></div> <br>
<div id="wheel_game6"></div> <br>
<div id="wheel_game7"></div> <br>
<div id="wheel_game8"></div> <br>
<div id="wheel_game9"></div> <br>
<div id="hWord"><p></p></div>
<div id="result"><p></p></div>
<script src="myScript_2.js"></script>
</body>
</html>
I tried using a continue statement because I thought that it would skip the iteration of the loop which would keep guessing but unfortunately that did not work. I essentially need the program to prompt the user to guess a letter and than display the letter in place of a dash but for every guess.
Any help would be appreciated.

Upload image to server using Ionic 5

I've been trying to upload a image to the server using Ionic 5 without any luck.
After taking a image with the camera or selecting a image from the galery, and try to upload it, it returns empty (No image selected.)
Ionic code :
createFileName() {
const d = new Date(),
n = d.getTime(),
newFileName = n + '.jpg';
return newFileName;
}
pathForImage(img: string) {
if (img === null) {
return '';
} else {
return this.file.dataDirectory + img;
}
}
async selectImage() {
let buttonLabels = ['Select from galery', 'Use camera'];
const options: ActionSheetOptions = {
title: 'Make a choice',
buttonLabels: buttonLabels,
addCancelButtonWithLabel: 'Cancel',
androidTheme: 4
}
this.actionSheet.show(options).then((buttonIndex: number) => {
if (buttonIndex == 1) {
this.takePicture(this.camera.PictureSourceType.PHOTOLIBRARY);
} else if (buttonIndex == 2) {
this.takePicture(this.camera.PictureSourceType.CAMERA);
}
});
}
copyFileToLocalDir(namePath: string, currentName: string, newFileName: string) {
this.file.copyFile(namePath, currentName, this.file.dataDirectory, newFileName).then(success => {
this.lastImage = newFileName;
}, error => {
console.log(error);
});
}
takePicture(sourceType: any) {
const options: CameraOptions = {
quality: 100,
sourceType: sourceType,
saveToPhotoAlbum: false,
correctOrientation: true,
cameraDirection: 1,
allowEdit: true,
targetHeight: 300,
targetWidth: 300
};
this.camera.getPicture(options).then(imageData => {
this.clickedImage = (<any>window).Ionic.WebView.convertFileSrc(imageData);
if (this.platform.is('android') && sourceType === this.camera.PictureSourceType.PHOTOLIBRARY) {
this.filePath.resolveNativePath(imageData).then(filePath => {
const correctPath = filePath.substr(0, filePath.lastIndexOf('/') + 1);
const currentName = imageData.substring(imageData.lastIndexOf('/') + 1, imageData.lastIndexOf('?'));
this.copyFileToLocalDir(correctPath, currentName, this.createFileName());
});
} else {
const currentName = imageData.substr(imageData.lastIndexOf('/') + 1);
const correctPath = imageData.substr(0, imageData.lastIndexOf('/') + 1);
this.copyFileToLocalDir(correctPath, currentName, this.createFileName());
}
this.uploadImageData();
});
}
uploadImageData() {
var targetPath = this.pathForImage(this.lastImage);
var filename = this.lastImage;
const fileTransfer: FileTransferObject = this.transfer.create();
let options: FileUploadOptions = {
fileKey: "file",
fileName: filename,
chunkedMode: false,
mimeType: "multipart/form-data",
params : {'fileName': filename}
}
fileTransfer.upload(targetPath, upload_url, options)
.then((data) => {
this.newdata = JSON.parse(data.response);
if (this.newdata.success) {
this.global.presentAlert("Success", this.newdata.message);
} else {
this.global.presentAlert("Error", this.newdata.message);
}
}, (err) => {
this.global.presentAlert("Error", JSON.stringify(err));
})
}
php code:
<?php
$xresponse = 0;
$xmessage = "";
$emparray = array();
if ( !empty( $_FILES ) )
{
$target_path = urldecode($_FILES["file"]["name"]);
$filename = stripslashes($target_path);
$image_name = time() . "_" . $filename;
if ( move_uploaded_file( $_FILES['file']['tmp_name'], "/uploads/profile/" . $image_name ) ) {
$success = true;
$message = "Upload success";
} else {
$success = false;
$message = $image_name;
}
} else {
$success = false;
$message = "No image selected.";
}
echo json_encode(
$emparray = array(
'success' => $success,
'message'=> $message
)
);
html code:
<ion-header class="pages">
<ion-toolbar class="bg-grad-lightblue">
<ion-title>
<span>My profile</span>
</ion-title>
</ion-toolbar>
</ion-header>
<ion-content class="bg-lightblue">
<section class="app-container">
<ion-grid class="ptop">
<ion-row>
<ion-col size="12">
<ion-avatar class="avatar_circle">
<img src="{{this.img}}" alt="" [hidden]="clickedImage">
<img [src]="clickedImage" [hidden]="!clickedImage" />
</ion-avatar>
<ion-card>
<ion-card-content>
<ion-button color="grad-btn-small bg-grad-gray" expand="block" (click)="selectImage()">
<span class="ion-text-left">Upload image</span></ion-button>
</ion-card-content>
</ion-card>
</ion-col>
</ion-row>
</ion-grid>
</section>
</ion-content>
ionic info:
Ionic:
Ionic CLI : 6.12.0 (C:\Users\User\AppData\Roaming\npm\node_modules\#ionic\cli)
Ionic Framework : #ionic/angular 5.3.1
#angular-devkit/build-angular : 0.901.12
#angular-devkit/schematics : 9.1.12
#angular/cli : 9.1.12
#ionic/angular-toolkit : 2.3.0
Cordova:
Cordova CLI : 10.0.0
Cordova Platforms : 6.0.0, android 9.0.0, browser
Cordova Plugins : cordova-plugin-ionic-keyboard 2.2.0, cordova-plugin-ionic-webview 4.2.1, (and 18 other plugins)
Utility:
cordova-res : 0.14.0
native-run : 1.2.2
System:
NodeJS : v14.4.0 (C:\Program Files\nodejs\node.exe)
npm : 6.14.5
OS : Windows 10
Can someone help me with this or point me in the right direction.
Thank you

call php function from smarty .tpl prestashop

I'm working to update a module for Prestashop. In this I use the hookDisplayAdminOrder in this way:
public function hookDisplayAdminOrder($params)
{
$orderId = Tools::getValue('id_order'); // mi prendo l'id dell'ordine per le query sui docId
$order = new Order($orderId);
$order_status = $order->getCurrentOrderState();
if(is_object($order_status)){
if($order_status->name[1] == 'Annullato')
$order_status_name = '';
else
$order_status_name = $order_status->name[1];
}else{
$order_status_name = $order_status;
}
$query = 'SELECT docId, docIdOrder, apiResponseOrder, apiResponseInvoice FROM '._DB_PREFIX_.'orders WHERE id_order=\'' . $orderId . '\';';
$docId = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow($query)['docId'];
$docIdOrder = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow($query)['docIdOrder'];
$apiResponseOrder = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow($query)['apiResponseOrder'];
$apiResponseInvoice = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow($query)['apiResponseInvoice'];
$obj_apiResponseOrder = json_decode($apiResponseOrder);
$obj_apiResponseInvoice = json_decode($apiResponseInvoice);
$orderResponseDescription = is_object($obj_apiResponseOrder)? $obj_apiResponseOrder->description : $obj_apiResponseOrder['description'];
$invoiceResponseDescription = is_object($obj_apiResponseInvoice)? $obj_apiResponseInvoice->description : $obj_apiResponseInvoice['description'];
$config_CreaOrdine = Configuration::get('PS_CREAZIONE_ORDINE');
$config_CreaFattura = Configuration::get('PS_CREAZIONE_FATTURA');
if(!$config_CreaOrdine){
$message_order = 'creazione documento disabilitata';
} else if(empty($order_status_name)){
$message_order = 'ordine annullato in Prestashop';
} else {
if(!empty($docIdOrder))
$message_order = 'documento salvato';
else
$message_order = 'documento NON salvato';
}
if(!$config_CreaFattura){
$message_invoice = 'creazione documento disabilitata';
} else if(empty($order_status_name)){
$message_invoice = 'ordine annullato in Prestashop';
} else {
if(!empty($docId))
$message_invoice = 'documento salvato';
else
$message_invoice = 'documento NON salvato';
}
// uso order_documents per incrementare il contatore
$order_documents = 0;
if(strpos($message_order, 'documento salvato') !== false)
$order_documents++;
if(strpos($message_invoice, 'documento salvato') !== false)
$order_documents++;
$this->context->smarty->assign('id_order', json_encode($order));
$this->context->smarty->assign('order_status_name', $order_status_name); //se l'ordine è annullato nascondo i pulsanti
$this->context->smarty->assign('config_CreaOrdine', $config_CreaOrdine);
$this->context->smarty->assign('config_CreaFattura', $config_CreaFattura);
$this->context->smarty->assign('order_documents', $order_documents); // contatore documenti salvati
$this->context->smarty->assign('invoice_docId', $docId); //docId per tasto fattura
$this->context->smarty->assign('invoice', $message_invoice);
$this->context->smarty->assign('order_docId', $docIdOrder); //docId per tasto ordine
$this->context->smarty->assign('order', $message_order);
return $this->display(__FILE__, 'views/templates/hook/admin_order.tpl');
}
Here below my template:
<div class="panel" id="myModule">
<div class="panel-heading">
<i class="icon-money"></i>{l s='myModule' mod='myModule'}
<span class="badge">{$order_documents}</span>
</div>
<table>
<tbody>
<thead>
<tr>
<td><strong>{l s='Stato ordine' mod='myModule'} </strong></td>
<td style="padding-left: 20px;"><strong>{l s='Stato fattura' mod='myModule'} </strong></td>
</tr>
</thead>
<tr>
<td id="f24_order">{$order}</td>
<td id="f24_invoice" style="padding-left: 20px;">{$invoice}</td>
</tr>
<tr>
<td>
{if $order_status_name neq '' && $order_docId == '' && $config_CreaOrdine eq 1}
<button type="submit" name="submit_order" id="submit_order" class="btn btn-primary">Salva Ordine</button>
{/if}
</td>
<td style="padding-left: 20px;">
{if $order_status_name neq '' && $invoice_docId == '' && $config_CreaFattura neq 0 }
<button type="submit" name="submit_invoice" id="submit_invoice" class="btn btn-primary">Salva Fattura</button>
{/if}
</td>
</tr>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
var orderbtn = document.getElementById("submit_order");
orderbtn.addEventListener('click', function (e) {
$.ajax({
type: 'POST',
data: {
ajax: true,
action: 'SmartyOrder' + {$id_order},
},
url: 'myModule',
success: function (response) {
console.log(response);
return response;
}
});
});
Eventually I created in myModule SmartyOrder function, but when I click in my button it does nothing.
Here below the method:
function ajaxProcessSmartyOrder($params){
$this->ajax = true;
$config_CreaOrdine = Configuration::get('PS_CREAZIONE_ORDINE');
$orderId = Tools::getValue('id_order'); // mi prendo l'id dell'ordine per le query sui docId
$check_order = new Order($orderId);
$order_status = $check_order->getCurrentOrderState(); // controllo lo stato dell'ordine prima di tutto
if(is_object($order_status)){
if($order_status->name[1] == 'Annullato')
$order_status_name = '';
else
$order_status_name = $order_status->name[1];
} else {
$order_status_name = $order_status;
}
$query = 'SELECT docId, docIdOrder, apiResponseOrder, apiResponseInvoice FROM '._DB_PREFIX_.'orders WHERE id_order=\'' . $orderId . '\';';
$docIdOrder = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow($query)['docIdOrder'];
$apiResponseOrder = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow($query)['apiResponseOrder'];
//$apiResponseInvoice = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow($query)['apiResponseInvoice'];
$obj_apiResponseOrder = json_decode($apiResponseOrder);
//$obj_apiResponseInvoice = json_decode($apiResponseInvoice);
$this->afterHook($check_order, false);
if(!empty($docIdOrder)){
$query = 'UPDATE ' . _DB_PREFIX_ . 'orders SET docIdOrder=\'' . $docIdOrder . '\' WHERE id_order=\'' . $orderId . '\';';
Db::getInstance()->Execute($query);
//$this->downloadDocument($docIdOrder, $orderId, true);
} else if (!empty($obj_apiResponseOrder->description)) { // con questa condizione popolo il docId anche nel caso in cui il documento è già esistente in F24
$query = 'UPDATE ' . _DB_PREFIX_ . 'orders SET docIdOrder=\'' . $obj_apiResponseOrder->description . '\' WHERE id_order=\'' . $orderId . '\';';
Db::getInstance()->Execute($query);
}
}
I want to call SmartyOrder function from template passing order data but at the moment I'm not able to do it. Any suggestion? Thanks
You can find more information about your issue in a module of Prestashop called 'CarrierComparion". You can compare your current code with the code of the module.
Post form using (Ajax): https://github.com/PrestaShop/ps_carriercomparison/blob/master/js/carriercompare.js#L84
Receiving post (PHP): https://github.com/PrestaShop/ps_carriercomparison/blob/master/controllers/front/carrier_comparison.php#L45

Including dynamic auto suggest javascript code in twig

I wanted to add an auto suggest list of students' code into input box
public function autoCodeSuggest()
{
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery("SELECT s.studentLogin FROM AppBundle:StudentLogin s ORDER BY s.studentLogin");
$code = $query->getArrayResult();
$strJavascript = '';
if (!empty($code)){
$strJavascript = '
var ArrayCode = new Array(';
for ($i=0; $i<count($code); $i++){
$strJavascript .= '"'.$code[$i]['studentLogin'].'",';
} // for ($i=0; $i<count($code); $i++)
$n = strlen($strJavascript)-1;
$strJavascript = substr_replace($strJavascript,'',$n); // remove last ,
$strJavascript .= ');';
} // if (!empty($code))
return $strJavascript;
} // end function
in my controller
public function studentSearchAction()
{
$LoginJS = $this->get('utilities_student_tools')->autoCodeSuggest();
return $this->render('student/student_search.html.twig', array(
'LoginJS' => $LoginJS,
));
}
student_search.html.twig contains
{% block body %}
<script language="javascript" type="text/javascript">
{{ LoginJS }}
</script>
{{ include('student_code.html.twig') }}
{% endblock %}
it doesn't work because when I view the source code of my page I have
<script language="javascript" type="text/javascript">
var ArrayCode = new Array("AA0951","AA1825","AA2802","AA2886","AA3418",.....
</script>
when I add a \ to the javascript code generator
$strJavascript .= '\"'.$code[$i]['studentLogin'].'\",';
the output become
var ArrayCode = new Array(\"AA0951\",\"AA1825\",\"AA2802\",\"AA2886\"
It works if the output is like
var ArrayCode = new Array("AA0951","AA1825","AA2802","AA2886",
the " is converted to " .
How can I avoid the conversion in twig?
I just find the answer.
{{ LoginJS|raw }}

How to insert in a specific column of a table?

I want to insert something in a specific column of a table:-
$this->db->insert('images.image',$data); // this query don't work
my table name in images and my column name is image. I want to insert $data in it.
I am using codeigniter.
When inserting data best use data array like so.
Disclaimer: This is just example code help you along.
Model Function Example
public function add($data) {
$data = array(
'CustomerName' => $data['CustomerName'],
'ContactName' => $data['ContactName'],
'Address' => $data['Address'],
'City' => $data['City'],
'PostalCode' => $data['PostalCode'],
'Country' => $data['Country']
);
$this->db->insert('tablename', $data);
}
Controller Function Example
<?php
public function index() {
$this->load->model('modal_name');
// Your post data can go here also.
// Example Only:
$CustomerName = $this->input->post('CustomerName');
if (isset($name)) {
$data['CustomerName'] = $CustomerName;
} else {
$data['CustomerName'] = '';
}
// On view would be <input type="text" name="CustomerName" />
$ContactName = $this->input->post('ContactName');
if (isset($ContactName)) {
$data['ContactName'] = $ContactName;
} else {
$data['ContactName'] = '';
}
// On view would be <input type="text" name="ContactName" />
$Address = $this->input->post('Address');
if (isset($Address)) {
$data['Address'] = $Address;
} else {
$data['Address'] = '';
}
// On view would be <input type="text" name="Address" />
$City = $this->input->post('City');
if (isset($City)) {
$data['City'] = $City;
} else {
$data['City'] = '';
}
// On view would be <input type="text" name="City" />
$PostalCode = $this->input->post('PostalCode');
if (isset($PostalCode)) {
$data['PostalCode'] = $PostalCode;
} else {
$data['PostalCode'] = '';
}
// On view would be <input type="text" name="PostalCode" />
$Country = $this->input->post('Country');
if (isset($Country)) {
$data['Country'] = $Country;
} else {
$data['Country'] = '';
}
// On view would be <input type="text" name="Country" />
$this->load->library('form_validation');
$this->form_validation->set_rules('CustomerName', 'Customer Name', 'required');
if ($this->form_validation->run() == FALSE ) {
$this->load->view('page', $data);
} else {
$this->model_name->add($this->input->post());
// You can use $this->input->post() this will let you get all post with in this function
/*
var_dump($this->input->post());
exit;
*/
redirect('success_page');
}
}
your controller code
$data=array('image'=>your_value);
$result = $this->your_model->insert($data);
and your model code
function insert($data){
$result = $this->db->insert('images',$data);
}