Retrieving the Line Item of an Old Record - javascript

I have a User Event Script that is deployed to Sales Orders. It uses the field values of line items to determine the quantity left. However, if I remove a line item it doesn't update the quantities of the removed item. I need the the item to be updated afterSubmit.
Is it possible to edit the quantities of the removed line item using nlapiGetOldRecord() or something of that sort?
Here's what the code looks like:
function afterSubmit(){
var curRec = nlapiGetRecordId();
var item = nlapiLoadRecord('item', curRec);
var sold = item.getFieldValue('cust_sold');
var quantity = item.getFieldValue('cust_quantity');
var leftToSell = quantity - sold;
item.setFieldValue('cust_lefttosell', leftToSell);
var finalValue = item.getFieldValue('cust_lefttosell');
var old = nlapiGetOldRecord(); // only retrieves salesorder record
nlapiSubmitRecord(item);
}
EDIT: So it turns out I can target the line items with a simple old.getLineItemValue('item', 'item', linenum).
As Adolfo pointed out below, I can target the line item of the old record. For some reason I thought the only way to target it was by using nlapiGetLineItemField(type, fldnm, linenum). The getLineItemValue version of the function was exactly what I was looking for.
This is what the code would look like:
var old = nlapiGetOldRecord();
var id = old.getLineItemValue('item', 'item', linenum);
var rec = nlapiLoadRecord('type', id);

Why not make cust_lefttosell a formula field so the value is always calculated on the fly from cust_quantity - cust_sold?
Anyways, if you want to use an afterSubmit then you have to iterate through all the line items in the old record, find out which ones were removed and then update the quantity on those.

Related

How to update sequentially in order in different rows and insert a new one?

I don't really know how to approach this, thing is, I'm developing a web application and in a section I need to assign projects to other developers, every assignment/project will have a priority of how important it is. Priority 1 is the highest (more important), and priority 5 is lowest (less important).
What the system has to do is, when I add a new priority 1 (or any other priority), if there are other priorities and a priority 1, move the others down (P1 = P2, P2 = P3, P3 = P4) and add the new one as P1.
I made a little piece of code (making everything manually that will only work once but is just for you to see what I want)
//PHP CODE
//prioridad = "P1" from a button
$prioridad = validacion::limpiar_cadena($_POST['prioridad']);
$estado = "";
$pes = array();
//I get all the priorities from my user and save them in this array
//Saving an array of the user's priorities
while ($row = $resultado->fetch_assoc()){
$pes[] = $row["prioridad"];
}
//Replace current priorities with their new one (just once)
if (in_array($prioridad, $pes)){
if (in_array("P5", $pes)){
$estado = "lleno";
}
//Make priority 4 = priority 5 and same for all
//This user just had the first 3 priorities,so this one did nothing but the others updated succesfully just for this example
if (in_array("P4", $pes)){
$upd= $conexion->prepare("UPDATE asignarproyectousuario SET prioridad = 'P5' WHERE idUsuario = 1 AND idProyecto = 32");
$upd->execute();
}
if (in_array("P3", $pes)){
$upd= $conexion->prepare("UPDATE asignarproyectousuario SET prioridad = 'P4' WHERE idUsuario = 1 AND idProyecto = 2");
$upd->execute();
}
if (in_array("P2", $pes)){
$upd = $conexion->prepare("UPDATE asignarproyectousuario SET prioridad = 'P3' WHERE idUsuario = 1 AND idProyecto = 1");
$upd->execute();
}
if (in_array("P1", $pes)){
$upd= $conexion->prepare("UPDATE asignarproyectousuario SET prioridad = 'P2' WHERE idUsuario = 1 AND idProyecto = 3");
$upd->execute();
}
$insert = $conexion->prepare("INSERT asignarproyectousuario(idProyecto, idUsuario, prioridad) VALUES(4, 1, ?)");
$insert->bind_param("s", $prioridad);
$insert->execute();
}
I tried using arrays and adding a value of one to the current priority but I don't know how to make it work, separate the array and assign every value to a row in the database.
I also found queues that make exactly that "movement" of adding one priority and move the others in order, but I haven't found much documentation about it.
This is the example I saw:
$queue = new SplQueue();
$queue->enqueue('prioridad1');
$queue->enqueue('Prioridad2');
$queue->enqueue('Prioridad3');
$queue->unshift('prioridad1');
$queue->rewind(); // always rewind the queue/stack, so PHP can start from the beginning.
while($queue->valid()){
echo $queue->current()."\n"; // Show the first one
$queue->next(); // move the cursor to the next element
}
echo "\n"."\n"."\n";
var_dump($queue);
If you could give me an idea of how to do it or a different example would be very helpful.
Thanks in advance and if my english is not good enough I can try to explain it better.
technique is simple >
you need to know how JSON works
add an Extra column (text) in mysql Table >
store JSON array in that column Like >
[{"TaskName":"XYX","AssignDate":"AnyDate","Priority":"High","PriorityCount":"50"}]
add extra array in JSON / Update array whenever require
itarate the array that finds ("Priority":"High" AND "PriorityCount": "" // highest)
this might help > Getting max value(s) in JSON array

Populating table with textbox value from previous HTML page

I have some JS that stores the name and value of selected checkboxes on one page and then, on a button click, adds this data to a table on page 2.
This works, but now I am looking to do the same for a textbox containing a number. Specifically, I'm looking to take the value entered by the user and add this to a cell in the table. What would be the best way to approach this? Add to the existing function or create a separate on button click function specifically for the textbox value?
I have added a screenshot of the HTML table on page 2 along with where I would like the textbox value to go (highlighted with a red rectangle).
Here's what I have so far:
HTML for textbox (page 1):
<div class="selecttier">
<h1>5. Number of Clicks</h1>
<input id="numberofclickstextbox" name="numberofclicks" type="text" value="0" data-total="0" oninput="calculatetier()" />
</div>
JS on page 1:
$('#sales_order_form_button').click(function() {
let table_info = [];
$('input[type=checkbox]').each(
function(index, value) {
if($(this).is(':checked')) {
table_info.push(
{
name: $(this).attr('name'),
value: $(this).attr('value'),
}
);
}
});
let base64str=btoa(JSON.stringify(table_info));
window.location = "page2.html?table_data=" + base64str;
});
JS on page 2:
// Helper function
function getUrlParameter(name) {
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
var results = regex.exec(location.href);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};
// actual code
let table_data = getUrlParameter('table_data');
let data_from_page_1 = JSON.parse(atob(table_data));
for(let i = 0; i < data_from_page_1.length; i++){
let row = $("<tr></tr>");
let recordName = $("<td></td>").text(data_from_page_1[i].name);
let recordValue = $("<td></td>").text(data_from_page_1[i].value);
row.append(recordName, recordValue);
$('#output_table').append(row);
}
// code to sum CPC column
var sum1 = 0;
$("#output_table tr > td:nth-child(2)").each(
(_,el) => sum1 += Number($(el).text()) || 0
);
$("#sum1").text(sum1);
//datetime stamp
var dt = new Date();
document.getElementById("datetime").innerHTML = dt.toLocaleString();
Output HTML table (page 2):
<table id="output_table">
<tr>
<th>Name</th>
<th>Value</th>
<th>Number of Clicks</th>
</tr>
<tfoot>
<tr>
<th id="total" colspan="1">Total CPC:</th>
<td id="sum1"></td>
</tr>
</tfoot>
</table>
As stated in the #Manu Varghese comment, the way to go would be using sessionStorage or localStorage.
First, let's differentiate both. According to the Stack Overflow question "HTML5 Local storage vs Session Storage", we have the following answer:
localStorage and sessionStorage both extend Storage. There is no difference between them except for the intended "non-persistence" of sessionStorage.
That is, the data stored in localStorage persists until explicitly deleted. Changes made are saved and available for all current and future visits to the site.
For sessionStorage, changes are only available per tab. Changes made are saved and available for the current page in that tab until it is closed. Once it is closed, the stored data is deleted.
Considering they are used the same way and you must to choose between what better fits your case, I will proceed using sessionStorage.
For that, in the first page you must use:
sessionStorage.setItem("key", "value")
You may set the item right when you perceives a change, like in the input 'blur' event.
and when you land in the second page (right when jQuery calls its start event), you will retrieve your data using:
sessionStorage.getItem("key")
Take in mind that localStorage/sessionStorage can support a limited amount of data. Even if that limit is way bigger than URL, most browsers will store only 2.5MB to 10MB per origin, according to the browser implementation (you may test by yourself in the link recommended in MDN (Mozilla Development Network), http://dev-test.nemikor.com/web-storage/support-test/).
Also, you may want to avoid storing sensitive data in the storages, due to some some discussions about security, which seems not to be a complaint here.
Implementation in the given case
Your code can be modified in three steps:
Change the way you save the data to use the storage
Creates a JSON of an object containing the array, instead the make the JSON using the array itself. Then you can add more fields.
Load the JSON object and its fields (the array and the number).
Step 1 - Changing to sessionStorage
Just now you have your Javascript on page 1 creating an array of data and stringifying that data to a JSON string.
If you want to use the storage rather than the URL for all the data, just change these lines of code from:
let base64str=btoa(JSON.stringify(table_info));
window.location = "page2.html?table_data=" + base64str;
to the code that will save the data into a (local/session)Storage:
let jsonStr=JSON.stringify(table_info); // converts to JSON string
sessionStorage.setItem("oldData", jsonStr); // save to storage
window.location = "page2.html"; // navigate to other page
Notice that the storage can receive any string, but only strings, then we can remove the btoa function, but we must keep the stringify.
Step 2 -- Adding more data to save
Now you have one JSON that is an array of items. But what do you want is to include one more field, parallel to this array. Of course, you can't include it in the array, as it is a different thing. So, what we must to do is to create a JSON object which has a number field AND the array field itself.
Your function to create the array is all ok, then we will use the same "table_data" as the array and include it to a new JSON object:
let table_data = []; // the array you have
$('input[type=checkbox]').each(
... rest of code ...
); // the function that creates the array (I abbreviated it here)
// Creates an object with an array and a number
let jsonObj = {
table_data: table_data,
number_of_clicks: theNumberYouHave/* your variable with the number here */
};
// This is the bit above with CHANGES into variable names
// Instead of "table_data", now we save "jsonObj"
let jsonStr=JSON.stringify(jsonObj); // converts the "jsonObj" to a JSON string
sessionStorage.setItem("oldData", jsonStr);
window.location = "page2.html";
Remember to change "theNumberYouHave" to whatever your variable with the number is called. The you will append the number as a field of the JSON object.
In other words, this simply will create an structure like that:
{
number_of_clicks: 5216,
table_data: [
{ name: "...", value: "..."},
{ name: "...", value: "..."},
{ name: "...", value: "..."},
...
]
}
See? Your table_data is still there, but with a new sibling (number_of_clicks) inside an object.
Step 3 -- Loading data from page 1
For now, you have these two lines of code in page 2 to read data from page 1:
let table_data = getUrlParameter('table_data');
let data_from_page_1 = JSON.parse(atob(table_data));
What do you need there, is to simply replace the getUrlParameter function to read from the storage, and remove the atob function to reflect the changes we made in page 1, this way:
let jsonObj = sessionStorage.getItem("oldData"); // reads the string
let data_from_page_1 = JSON.parse(jsonObj); // parse the JSON string
let table_data = data_from_page_1.table_data; // grab the table data
let number_of_clicks = data_from_page_1.number_of_clicks; // grab the number
Now you are free to use the variable "table_data" like you did, and to use the "number_of_clicks" in the way you want to use it. It is the number passed from page 1, then you may set it to your table cell.
You have it with the unique ID "sum1", the you may just:
$("#sum1").text(number_of_clicks);
And you are done!
I highly recommend localStorage and sessionStorage to be used, as per this and this
Page 1 code full source
$('#next_page_button').click(function(){
let table_info = [];
// Do for checkboxes
$('.campaignstrategy input[type=checkbox]').each(
function(index, value){
if($(this).is(':checked')){
table_info.push(
{
name: $(this).attr('name'),
value: $(this).attr('value'),
type: 'checkbox'
}
);
}
});
$('.campaignstrategy input[type=text]').each(
function(index, value){
table_info.push(
{
name: $(this).attr('name'),
value: $(this).attr('value'),
type: 'text'
}
);
});
let base64str=btoa(JSON.stringify(table_info));
window.location = "page2.html?table_data=" + base64str;
});
Page 2 Code full source
// Helper function
function getUrlParameter(name) {
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
var results = regex.exec(location.href);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};
// actual code
let table_data = getUrlParameter('table_data');
let data_from_page_1 = JSON.parse(atob(table_data));
// clear table
$('#output_table').html("");
// generator checboxes
for(let i=0;i<data_from_page_1.length;i++){
if(data_from_page_1[i].type == "checkbox"){
let row = $("<tr></tr>");
let recordName = $("<td></td>").text(data_from_page_1[i].name);
let recordValue = $("<td></td>").text(data_from_page_1[i].value);
let recordCount = $("<td></td>").text("");
row.append(recordName, recordValue, recordCount); // not used but needed
$('#output_table').append(row);
}
}
// generate textboxes
for(let i=0;i<data_from_page_1.length;i++){
if(data_from_page_1[i].type == "text"){
let row = $("<tr></tr>");
let recordName = $("<td></td>").text("");
let recordValue = $("<td></td>").text("");
let recordCount = $("<td></td>").text(data_from_page_1[i].value);
row.append(recordName, recordValue, recordCount);
$('#output_table').append(row);
}
}
ANSWER:
What would be the best way to approach this?
window.localStorage - stores data with no expiration date
window.sessionStorage - stores data for one session

Mix clickable row and unclickable row on slickgrid

For my columns definition.
var columns = [
{id: "label", name: "point", formatter:this.clickableFormatter,field: "point",width: 150},
then I add clickhander for it.
chart.addClickHandler(){
}
Also I use clickableFormatter for this.
clickableFormatter(row,cell,value,columnDef,dataContext){
return "<span style='cursor:pointer;'>" + value + "</span>";
}
From these code. my table rows are clickable and I can show the user where is clickable by changing pointer.
However now I want to make one row unclickable.
(for example total row)
Is it possible to prevent click event for one low??
And is it possible to use another formatter for one row?
I gave the data from for loop and add total seperately.
for (var k = 0 ; k < data.length ;k++){
var temp = new Array();
temp['id'] = data[k]['id'];
temp['point'] = data[k]['point'];
ret.push(temp);
}
ret.push({
'id' : "total",
"point" : pointTotal,
});
In your formatter, you have access to the value of the cell, so if value==='total', just return an empty string.
Also FYI, I don't think you need the for loop in your code (you could just leave it out entirely), unless you're using it to calculate the total, but you don't seem to be doing that.
If you think that you need it for creating the array objects, you're misunderstanding arrays in javascript, what you're actually setting is object properties, and it would be usual to initialise with var temp = { }; rather than as Array.
It may not make sense at first, but everything in javascript is an object, including arrays and functions. So you can add object properties to anything.
somevar[numericVal] = x; // set array element, somevar must be type Array
somevar['stringVal'] = x; // set object property 'stringVal'
somevar.stringVal = x; // identical to above line, different way of specifying

Creating Select Box from options stored in a variable

I want to create a select box from options stored in a variable (the values will change based on the user).
For now, I'm just trying to get it to work with this variable in my javascript file:
var resp = {"streams": [ {"sweet":"cookies"}, {"savory":"pizza"}]}
In the html file, I have a select id "selectedStream"
How do I invoke, both the select id from html and the variable from javascript to create the select box?
I've seen examples such as the one below, but I don't understand how to link the id and the variable to the box.
$("option:selected", myVar).text()
I hope this was coherent! Thanks
I think what you are trying to do is append option html nodes to an existing select element on your screen with an id of 'selectedStream'. You want to use the data from the 'resp' variable to populate the text and value of the option nodes that you are appending. If this is correct, I have implemented that functionality with this jsfiddle. The javascript is also below:
$(function(){
var resp = {"streams": [ {"sweet":"cookies", "savory":"pizza"}]};
var streamData = resp.streams[0];
var optionTemplate = "<option value=\"{0}\">{1}</option>";
for(var key in streamData){
var value = streamData[key];
var currentOptionTemplate = optionTemplate;
currentOptionTemplate = currentOptionTemplate.replace("{0}", key);
currentOptionTemplate = currentOptionTemplate.replace("{1}", value);
$("#selectedStream").append($(currentOptionTemplate));
}
});
Is that array necessary? If you're just trying to display the keys within that object I'd create a for loop:
var resp = { "streams": {"sweet": "cookies", "savory": "pizza"} }
for (property in resp.streams) {
$('#selectStream').append($('<option/>', {text: property, value: property}));
}
JSFiddle: http://jsfiddle.net/pWFNb/

Dojo: option[selected ='selected'] not working for run-time change

I am working on a multi-select box and found
var count = dojo.query("option[selected ='selected']", dojo.byId('select_id')).length;
Always returns whatever original from the page(database) but yet what user selected at run-time. I am running on Dojo 1.6. So how can I count number of selected options from multi-select box AT RUN-TIME?
I made a page that shows users and the groups they are in. Here is some of the code. I had to rip some stuff out to make it concise. The last line of code answers the question. It returns an array with the checked values.
// Programattically create the select.
var _groups = new dojox.form.CheckedMultiSelect({
multiple : true,
class : "cssThing"
}, "groups" + _userNumber);
// Fill the CheckedMultiSelect boxes with unchecked data.
var tempArray = new Array();
dojo.forEach(groupList, function(row, index) {
tempArray.push({
value : row.value,
label : row.label,
selected : false,
});
});
_groups.addOption(tempArray);
// Populate the CheckedMultiSelect with an array.
var tempArray = [];
dojo.forEach(user.groups, function(row) {
tempArray.push(String(row.groupName));
});
_groups.set('value', tempArray);
// Get the CheckedMultiSelect values as an array.
_groups.get('value');

Categories

Resources