call php function from smarty .tpl prestashop - 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

Related

How to create select box in ajax generated update table with values form sql table using pdo

I have the following script that i use to update multiple rows from the SQL table ''account''.
In the table ''account'' I have column named category, the cat_ID form table ''categories'' is inserted as value in the table ''accounts'' in the column category.
I now have those values hard coded and i want them to be selectable as dropdown list from the table categories, cat_ID as value and cat_name as name of the category. I have tried a lot, googled a lot, but i cant get this to work.
All i want is to have the options fetched from the SQL table categories and use them as dropdown select option in the update option of the script, which are now hard coded now and is working fine.
The hard coded part:
html += '<td class=\"footer\"><select name="category[]" id="category_'+$(this).attr('id')+'" class="editbox"><option value="4">Moet gerankt worden</option><option value="6">Wordt gerankt</option><option value="5">Current BF Holder</option><option value="7">Main Account</option><option value="8">Money Private</option><option value="11">CB/Suc</option><option value="13">Casino Holder</option><option value="15">Wordt Gestockt</option><option value="10">Dont use, ask first!</option><option value="14">Stockgeld</option><option value="0"></option></select></td>';
The SQL select call:
$query = "SELECT a.*, c.cat_color, c.cat_name, c.cat_txt FROM account a LEFT JOIN categories c ON c.cat_ID = a.category WHERE `betaald` = 'Yes' AND `secret` = 'No'";
$statement = $connect->prepare($query);
if($statement->execute())
{
while($row = $statement->fetch(PDO::FETCH_ASSOC))
{
$data[] = $row;
}
echo json_encode($data);
}
The whole script.
<script>
$(document).ready(function(){
$(document).on('click', '.loginBtn', function(e) {
e.preventDefault();
var row = $(this).closest('tr');
var tds = row.find('td');
var name = ''
var cnt = 0;
$.each(tds, function() {
if(cnt == 1) {
name = $(this).text();
return false;
}
cnt++;
});
$.ajax({
url:"select_login_update.php",
method:"POST",
data: {name: name},
dataType: 'JSON',
success:function(data)
{
if(data !== '') {
var email = data[0].email;
var pword = data[0].password
var frm = document.createElement('form');
frm.setAttribute('action', 'http://login.php');
frm.setAttribute('method', 'post');
frm.setAttribute('target', 'view');
var frmEmail = document.createElement('input');
frmEmail.setAttribute('type', 'hidden');
frmEmail.setAttribute('name', 'email');
frmEmail.setAttribute('value', email);
var frmPass = document.createElement('input');
frmPass.setAttribute('type', 'hidden');
frmPass.setAttribute('name', 'password');
frmPass.setAttribute('value', pword);
frm.appendChild(frmEmail)
frm.appendChild(frmPass)
document.body.appendChild(frm);
window.open('', 'view');
frm.submit();
} else {
console.log('empty data');
}
},
error:function(xhr, status, err)
{
console.log('select_login_update.php error ' + err);
}
});
});
function fetch_data()
{
$.ajax({
url:"select_update_all.php",
method:"POST",
dataType:"json",
success:function(data)
{
var html = '';
for(var count = 0; count < data.length; count++)
{var purpose = data[count].purpose;
if(purpose == "BFH") purpose = "Holders";
else if(purpose == "CAS") purpose = "Ranking";
else if(purpose == "PWA") purpose = "Money Rankers";
else if(purpose == "Crew") purpose = "PW Accounts";
else if(purpose == "Crew2") purpose = "The Colombo Family";
else if(purpose == "Crew3") purpose = "Hassinions";
else if(purpose == "aa") purpose = "Admin Account";
else if(purpose == "slist") purpose = "Stocklist";
else if(purpose == "Eragon") purpose = "Eragon";
else if(purpose == "NP") purpose = "Non Paying";
else if(purpose == "DA") purpose = "Deadly Alliance";
html += '<tr >';
html += '<td class=\"footer\"><input type="checkbox" id="'+data[count].id+'" data-name="'+data[count].name+'" data-bullets="'+data[count].bullets+'" data-rang="'+data[count].rang+'" data-category="'+data[count].category+'" data-door="'+data[count].door+'" data-ranker="'+data[count].ranker+'" data-purpose="'+data[count].purpose+'" data-notes="'+data[count].notes+'" class="check_box" /></td>';
html += '<td style="color:'+data[count]['cat_color']+' " class=\"footer\">'+data[count].name+'</td>';
html += '<td style="color:'+data[count]['cat_color']+' " class=\"footer\">'+data[count].bullets+'</td>';
html += '<td style="color:'+data[count]['cat_color']+' " class=\"footer\">'+data[count].rang+'</td>';
html += '<td style="color:'+data[count]['cat_color']+' " class=\"footer\">'+data[count].ranker+'</td>';
html += '<td style="color:'+data[count]['cat_color']+' " class=\"footer\">'+data[count].cat_name+'</td>';
html += '<td style="color:'+data[count]['cat_color']+' " class=\"footer\">'+purpose+'</td>';
html += '<td style="color:'+data[count]['cat_color']+' " class=\"footer\">'+data[count].notes+'</td>';
html += '<td style="color:'+data[count]['cat_color']+' " class=\"footer\">'+data[count].door+'</td>';
html += '<td class=\"footer\"><button type="button" class="loginBtn" >Login</button></td></tr>';
}
$('tbody').html(html);
}
});
}
fetch_data();
$(document).on('change', '.check_box', function(){
var html = '';
if(this.checked)
{
html = '<td class=\"footer\"><input type="checkbox" id="'+$(this).attr('id')+'" data-name="'+$(this).data('name')+'" data-bullets="'+$(this).data('bullets')+'" data-rang="'+$(this).data('rang')+'" data-category="'+$(this).data('category')+'" data-door="'+$(this).data('door')+'" data-ranker="'+$(this).data('ranker')+'" data-purpose="'+$(this).data('purpose')+'" data-notes="'+$(this).data('notes')+'" class="check_box" checked /></td>';
html += '<td class=\"footer\"><input type="text" name="name[]" class="editbox" value="'+$(this).data("name")+'" /></td>';
html += '<td class=\"footer\"><input type="number" onClick="this.select()" style="width:58px !important;" name="bullets[]" class="editbox" value="'+$(this).data("bullets")+'" /></td>';
html += '<td class=\"footer\"><select name="rang[]" id="rang_'+$(this).attr('id')+'" class="editbox"><option value="Bacteria">Bacteria</option><option value="Low Life">Low Life</option><option value="Apprentice">Apprentice</option><option value="Hitman">Hitman</option><option value="Assassin">Assassin</option><option value="Local Boss">Local Boss</option><option value="Boss">Boss</option><option value="Godfather">Godfather</option></select></td>';
html += '<td class=\"footer\"><input type="text" name="ranker[]" class="editbox" value="'+$(this).data("ranker")+'" /></td>';
html += '<td class=\"footer\"><select name="category[]" id="category_'+$(this).attr('id')+'" class="editbox"><option value="4">Moet gerankt worden</option><option value="6">Wordt gerankt</option><option value="5">Current BF Holder</option><option value="7">Main Account</option><option value="8">Money Private</option><option value="11">CB/Suc</option><option value="13">Casino Holder</option><option value="15">Wordt Gestockt</option><option value="10">Dont use, ask first!</option><option value="14">Stockgeld</option><option value="0"></option></select></td>';
html += '<td class=\"footer\"><select name="purpose[]" id="purpose_'+$(this).attr('id')+'" class="editbox"><option value="">-- No Type --</option><option value="Killer">Killers</option><option value="BFH">Holders</option><option value="CAS">Ranking</option><option value="PWA">Money Rankers</option><option value="Crew">PW Accounts</option><option value="Crew2">The Colombo Family</option><option value="Deadly Alliance">Deadly Alliance</option><option value="Crew3">Hassinions</option><option value="aa">Admin Account</option><option value="NP">Non Paying</option><option value="Eragon">Eragon</option><option value="slist">Stocklist</option></select></td>';
html += '<td class=\"footer\"><input type="text" name="notes[]" class="editbox" value="'+$(this).data("notes")+'" /></td>';
html += '<td class=\"footer\"><input disabled="" style="width:50px !important;" name="door[]" class="editbox" value="'+$(this).data("door")+'" /><input type="hidden" name="hidden_id[]" value="'+$(this).attr('id')+'" /></td>';
html += '<td class=\"footer\"><input type="submit" name="multipleupdatedata2allacc" id="multipleupdatedata2allacc" class="submit" value="Update" /></td>';
}
else
{
html = '<td class=\"footer\"><input type="checkbox" id="'+$(this).attr('id')+'" data-name="'+$(this).data('name')+'" data-bullets="'+$(this).data('bullets')+'" data-rang="'+$(this).data('rang')+'" data-category="'+$(this).data('category')+'" data-door="'+$(this).data('door')+'" data-ranker="'+$(this).data('ranker')+'" data-purpose="'+$(this).data('purpose')+'" data-notes="'+$(this).data('notes')+'" class="check_box" /></td>';
html += '<td class=\"footer\">'+$(this).data('name')+'</td>';
html += '<td class=\"footer\">'+$(this).data('bullets')+'</td>';
html += '<td class=\"footer\">'+$(this).data('rang')+'</td>';
html += '<td class=\"footer\">'+$(this).data('ranker')+'</td>';
html += '<td class=\"footer\">'+$(this).data('category')+'</td>';
html += '<td class=\"footer\">'+$(this).data('purpose')+'</td>';
html += '<td class=\"footer\">'+$(this).data('notes')+'</td>';
html += '<td class=\"footer\">'+$(this).data('door')+'</td>';
html += '<td class=\"footer\"><button type="button" class="loginBtn">Login</button></td></tr>';
}
$(this).closest('tr').html(html);
$('#rang_'+$(this).attr('id')+'').val($(this).data('rang'));
$('#category_'+$(this).attr('id')+'').val($(this).data('category'));
$('#purpose_'+$(this).attr('id')+'').val($(this).data('purpose'));
});
$('#update_form').on('submit', function(event){
event.preventDefault();
if($('.check_box:checked').length > 0)
{
$.ajax({
url:"update_multiple.php",
method:"POST",
data:$(this).serialize(),
success:function()
{
alert('Data Updated');
fetch_data();
}
})
}
});
});
</script>
Well, it is somewhat easy, and believe it or not, even easier for what you need. So, based on what you have, you really only need a string of <option> tags for the <select>, which only needs to be fetched once for reference. The tougher part is usually making the new handling work with code that already exists, if possible, without having to refactor.
Try the things below, I've added another ajax to pre-fetch the category options after the document is ready: (see the two // New comment markers)
$(document).ready(function() {
var categoryOptions = ''; // New var
$.ajax({ // New ajax
url: 'get_categories.php',
method: 'GET',
dataType: 'text',
success:function(data)
{
categoryOptions = data;
},
error:function(xhr, status, err)
{
console.log('get_categories.php error ' + err);
}
});
$(document).on('click', '.loginBtn', function(e) {
Content of get_categories.php: (replace with your DB handling)
<?php
$db = new mysqli('localhost', 'root', '', 'test');
// Get the category id/name pairs
$result = $db->query("SELECT cat_ID, cat_name FROM categories");
$options = '';
// Build the options
while ($row = $result->fetch_array()) {
$options .= '<option value="' . $row['cat_ID'] . '">' . $row['cat_name'] . '</option>';
}
// The option 0 was last, keeping the same way.
$options .= '<option value="0"></option>';
echo $options;
Then change the categories html from:
html += '<td class=\"footer\"><select name="category[]" id="category_'+$(this).attr('id')+'" class="editbox"><option value="4">Moet gerankt worden</option><option value="6">Wordt gerankt</option><option value="5">Current BF Holder</option><option value="7">Main Account</option><option value="8">Money Private</option><option value="11">CB/Suc</option><option value="13">Casino Holder</option><option value="15">Wordt Gestockt</option><option value="10">Dont use, ask first!</option><option value="14">Stockgeld</option><option value="0"></option></select></td>';
...to:
html += '<td class=\"footer\"><select name="category[]" id="category_'+$(this).attr('id')+'" class="editbox">' + categoryOptions + '</select></td>';
I believe that should achieve the desired goal.

Worry in the backoffice of my module undefined index prestashop

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');
}

Remember selected checkboxes across paginated pages

I am displaying data in a table and doing some paging and sorting. I have a checkbox for everyrow.
When I move from one page to another, I will like to keep the checkboxes checked if they were checked.
I dont want the checked boxes to uncheck as I navigate from page to page. How do i achieve that?
Here is my jquery.
<script type="text/javascript">
$(document).ready(function () {
$(".header").click(function (evt) {
var sortfield = $(evt.target).data("sortfield");
if ($("#SortField").val() == sortfield)
{
if($("#SortDirection").val()=="ascending")
{
$("#SortDirection").val("descending");
}
else
{
$("#SortDirection").val("ascending");
}
}
else
{
$("#SortField").val(sortfield);
$("#SortDirection").val("ascending");
}
evt.preventDefault();
$("form").submit();
});
$(".pager").click(function (evt) {
var pageindex = $(evt.target).data("pageindex");
$("#CurrentPageIndex").val(pageindex);
evt.preventDefault();
$("form").submit();
});
});
</script>
Here is my html page
<body>
<h1>List of Customers</h1>
#{
PageSortOnlineEx.Models.SortingPagingInfo info = ViewBag.SortingPagingInfo;
}
#using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
#Html.Hidden("SortField", info.SortField)
#Html.Hidden("SortDirection", info.SortDirection)
#Html.Hidden("PageCount", info.PageCount)
#Html.Hidden("PageSize", info.PageSize)
#Html.Hidden("CurrentPageIndex", info.CurrentPageIndex)
<table border="1" cellpadding="10">
<tr>
<th>Select</th>
<th>CustomerID</th>
<th>CompanyName</th>
<th>ContactName</th>
<th>Country</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>#Html.CheckBox("select", false)</td>
<td>#item.CustomerID</td>
<td>#item.CompanyName</td>
<td>#item.ContactName</td>
<td>#item.Country</td>
</tr>
}
<tr>
<td colspan="4">
#for (var i = 0; i < info.PageCount; i++)
{
if (i == info.CurrentPageIndex)
{
<span>#(i + 1)</span>
}
else
{
#(i + 1)
}
}
</td>
</tr>
</table>
}
</body>
Here is my controller code
public ActionResult Index()
{
using (NorthwindEntities db = new NorthwindEntities())
{
SortingPagingInfo info = new SortingPagingInfo();
info.SortField = "CustomerID";
info.SortDirection = "ascending";
info.PageSize = 10;
info.PageCount = Convert.ToInt32(Math.Ceiling((double)(db.Customers.Count() / info.PageSize)));
info.CurrentPageIndex = 0;
var query = db.Customers.OrderBy(c => c.CustomerID).Take(info.PageSize);
ViewBag.SortingPagingInfo = info;
List<Customer> model = query.ToList();
return View(model);
}
}
[HttpPost]
public ActionResult Index(SortingPagingInfo info)
{
using (NorthwindEntities db = new NorthwindEntities())
{
IQueryable<Customer> query = null;
switch (info.SortField)
{
case "CustomerID":
query = (info.SortDirection == "ascending" ? db.Customers.OrderBy(c => c.CustomerID) : db.Customers.OrderByDescending(c => c.CustomerID));
break;
case "CompanyName":
query = (info.SortDirection == "ascending" ? db.Customers.OrderBy(c => c.CompanyName) : db.Customers.OrderByDescending(c => c.CompanyName));
break;
case "ContactName":
query = (info.SortDirection == "ascending" ? db.Customers.OrderBy(c => c.ContactName) : db.Customers.OrderByDescending(c => c.ContactName));
break;
case "Country":
query = (info.SortDirection == "ascending" ? db.Customers.OrderBy(c => c.Country) : db.Customers.OrderByDescending(c => c.Country));
break;
}
query = query.Skip(info.CurrentPageIndex * info.PageSize).Take(info.PageSize);
ViewBag.SortingPagingInfo = info;
List<Customer> model = query.ToList();
return View(model);
}
}

Autocomplete issue in Yii

I'm using this
auto-complete plugin with my new project. It's working fine. See image
But I want to populate these fields when I select the result.
Here is my code:
var as = $("#query" + x + "").autocomplete({
minChars: 1,
maxHeight: 100,
serviceUrl: 'index.php?r=purchaseorder/list',
});
IN CONTROLLER
public function actionList() {
$criteria = new CDbCriteria;
$criteria->select = array('id','description','unit','rate');
$criteria->addSearchCondition("description", $_GET['query']);
$criteria->limit = $this->limit;
$items = Item::model()->findAll($criteria);
$suggestions = array();
$data = array();
foreach ($items as $c) {
$suggestions[] = $c->description;
$data[] = $c->id;
}
header('Content-type: application/json; charset=utf-8');
echo CJSON::encode(
array(
'query' => 'q',
'suggestions' => $suggestions,
'data' => $data
)
);
exit;
}
grid jquery
jQuery("#addrow").click(function() {
jQuery(".item-row:last").after('<tr class="item-row">\n\
<td>\n\
<span id="delete' + x + '" style="cursor: pointer" class="icon-remove"></span>\n\
</td>\n\
<td class="item-code"><input autocomplete="off" name="code[]" id="code' + x + '" type="text" class="input-code"/></td>\n\
<td class="item-description"><input autocomplete="off" name="q" id="query' + x + '" type="text" class="input-description"/></td>\n\
<td class="item-unit"><input readonly autocomplete="off" name="unit[]" id="unit' + x + '" type="text" class="input-unit"/></td>\n\
<td class="item-qty"><input name="qty[]" autocomplete="off" value="0" id="qty' + x + '" type="text" class="input-qty"/></td>\n\
<td class="item-rate"><input readonly name="rate[]" autocomplete="off" value="125.25" id="rate' + x + '" type="text" class="input-rate"/></td>\n\
<td class="item-discount"><input name="discount[]" autocomplete="off" value="0.00" id="discount' + x + '" type="text" class="input-discount"/></td>\n\
<td class="item-total"><input name="total[]" readonly autocomplete="off" value="0.00" id="total' + x + '" type="text" class="input-amount"/></td>\n\
</tr>');
controller is already there
I have done it like this...
IN JQUERY....
var as = $("#query").autocomplete({
minChars: 1,
maxHeight: 100,
serviceUrl: 'index.php?r=purchaseorder/list',
onSelect: function(suggestion) {
var row = $(this).closest('tr');
row.find('.input-code').val(suggestion.id).attr('readonly', 'readonly');
row.find('.input-description').attr('readonly', 'readonly');
row.find('.input-unit').val(suggestion.unit).attr('readonly', 'readonly');
row.find('.input-rate').val(suggestion.rate).attr('readonly', 'readonly');
row.find('.input-qty').focus();
}
});
AND THEN IN CONTROLLER
public function actionList() {
$criteria = new CDbCriteria;
$criteria->select = array('description', 'id','unit','rate');
$criteria->addSearchCondition("description", $_GET['query']);
$criteria->limit = $this->limit;
$items = Item::model()->findAll($criteria);
$suggestions = array();
$x=0;
foreach ($items as $c) {
$suggestions[$x]['value'] = $c->description;
$suggestions[$x]['id'] = $c->id;
$suggestions[$x]['rate'] = $c->rate;
$suggestions[$x]['unit'] = $c->unit;
$x++;
}
header('Content-type: application/json; charset=utf-8');
echo CJSON::encode(
array(
'suggestions' => $suggestions,
)
);
exit;
}
thats it...!
Sample code as shown below
$('#yourautoCompleteId').change(function(){
var selecteddata=$(this).val();
$.ajax({
url: "'.$this->createUrl('Controller/yourMethod').'",
data: {
//special:specialisation,
data :selecteddata,
},
type:"GET",//you can also use POST method
dataType:"html",//you can also specify for the result for json or xml
success:function(response){
//write the logic to get the response data as u need and set it to the fields
$("#dataId").val("SetHere");
$('#quantityId').val("setHere");
},
error:function(){
//TODO: Display in the poll tr ifself on error
alert("Failed request data from ajax page");
}
});
})
get the data in the controller using post and query with this data and send the result as u need and set to the fields as shown in the sample

Banking API queried by Javascript

I am finalising a college project and I am stuck.
I have created an API in netbeans and it is working fine.
Returing e.g.
<?xml version="1.0" encoding="UTF-8"?>
<accountholder>
<accountnumber>45672</accountnumber>
<address>234 THE BANK, DUBLIN 1</address>
<balance>763.32</balance>
<email>JOHANN#SMITH.COM</email>
<firstname>JOHANN</firstname>
<id>1</id>
<lastname>SMITH</lastname>
<pinnumber>1234</pinnumber>
</accountholder>
Now I am trying to create a javascript to return data when searching by Id.
<script language="javascript" type="text/javascript">
var request = null;
function createRequest() {
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject("MsXML2.XMLHTTP");
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = null;
}
}
}
if (request == null)
alert("Error creating request object!");
}
function getMessage()
{
createRequest();
var accountholderid = document.getElementById("Id").value;
id=eval(accountholderid);
var url = "http://localhost:8080/BankProjectApi/webresources/bankprojectapi.accountholder/"+id;
request.onreadystatechange = handleResponse;
request.open("GET", url, true);
request.send(null);
}
function handleResponse() {
if (request.readyState==4 && request.status==200)
{
var xmlDocument=request.responseXML;
var firstname = xmlDocument.getElementsByTagName("firstname");
var lastname = xmlDocument.getElementsByTagName("lastname");
var accountnumber = xmlDocument.getElementsByTagName("accountnumber");
for(var i=0; i<firstname.length; i++) {
var firstname = firstname[i].childNodes[0].nodeValue;
var lastname = lastname[i].childNodes[0].nodeValue;
var accountnumber= accountnumber[i].childNodes[0].nodeValue;
document.getElementById('lastname').value=firstname;
document.getElementById('firstname').value=lastname;
document.getElementById('accountnumber').value=accountnumber;
}
}
}
</script>
In the body I have an input textfield with a button with an on click:
<td>Enter Account holder ID : </td>
<td><input type="text" id="playerid" size="10"/>
<input type="button" value="Get Details" onclick="getMessage()"/>
</tr>
<tr>
<td>Account holder Last Name : </td>
<td> <input type="text" id="lastname" size="10"/> </td>
</tr>
<tr>
<td>Account holder First Name : </td>
<td> <input type="text" id="firstname" size="10"/> </td>
</tr>
<tr>
<td>Account number : </td>
<td> <input type="text" id="accountnumber" size="10"/> </td>
</tr>
What am I missing as it is not returning anything :(
I believe your id value for the 'accountholderid' was looking for 'Id' instead of 'playerid'.
May I ask why you are calling 'eval' on the value? Do you need parseInt?
(function () {
var request = null;
function createRequest() {
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject('MsXML2.XMLHTTP');
} catch (othermicrosoft) {
try {
request = new ActiveXObject('Microsoft.XMLHTTP');
} catch (failed) {
request = null;
}
}
}
if (request === null) {
alert('Error creating request object!');
}
}
function getMessage() {
createRequest();
var accountholderid = document.getElementById('playerid').value,
id = eval(accountholderid),
url = 'http://localhost:8080/BankProjectApi/webresources/bankprojectapi.accountholder/' + id;
request.onreadystatechange = handleResponse;
request.open("GET", url, true);
request.send(null);
}
function handleResponse() {
if (request.readyState === 4 && request.status === 200) {
var xmlDocument = request.responseXML,
firstname = xmlDocument.getElementsByTagName('firstname'),
lastname = xmlDocument.getElementsByTagName('lastname'),
accountnumber = xmlDocument.getElementsByTagName('accountnumber');
for(var i = 0, max = firstname.length; i < max; i += 1) {
var firstname = firstname[i].childNodes[0].nodeValue,
lastname = lastname[i].childNodes[0].nodeValue,
accountnumber = accountnumber[i].childNodes[0].nodeValue;
document.getElementById('lastname').value = firstname;
document.getElementById('firstname').value = lastname;
document.getElementById('accountnumber').value = accountnumber;
}
}
}
}());
Also, I did a quick refactoring of your code to aid in my assessing the issue, adhere to more community conventions as well as avoid common JS pitfalls. (ex. closure, missing var declarations, ===, curlys everywhere, single variable pattern, and some others).