Get all entries for a given name in firefox form history - firefox

Is there a way I can find out all elements of a given name in teh form history. In my firefox addon, I am adding some elements in the form-history under a specific name - lest say "search-description".
I now want to get all the elements I added under this name. I see that I can get a history object :
this.Ci = Components.interfaces;
this.Cc = Components.classes;
var historyObj = this.Cc["#mozilla.org/satchel/form-history;1"].getService(this.Ci.nsIFormHistory2 || this.Ci.nsIFormHistory);
But the nsIFormHistory or nsIFormHistory2 interfaces do not have any function like:
getAllEntries(name)
Anyone can help me out in this?

Usually, nsIFormHistory2.DBConnection property is used for querying, you access the SQLite table directly. Something like this (untested):
var completionListener =
{
handleCompletion: function(reason) {},
handleError: function(error) {},
handleResult: function(result)
{
var values = [];
while (true)
{
var row = result.getNextRow();
if (!row)
break;
values.push(row.getResultByName("value"));
}
alert("Autocomplete values: " + values);
}
};
var query = "SELECT value " +
"FROM moz_formhistory " +
"WHERE fieldname='search-description'";
var statement = historyObj.DBConnection.createAsyncStatement(query);
historyObj.DBConnection.executeAsync([statement], 1, completionListener);
Note that using async API is recommended here, querying the database might take time.

Related

Why Parse server is creating new object instead of updating?

I am running parse server in NodeJS environment with express.
Generally, Parse automatically figures out which data has changed so only “dirty” fields will be sent to the Parse Cloud. So, I don’t need to worry about squashing data that I didn’t intend to update.
But why this following code is saving new data every time instead of updating the existing document data with name "Some Name".
// Parse code
Parse.initialize(keys.parseAppID);
Parse.serverURL = keys.parseServerURL;
var GameScore = Parse.Object.extend("GameScore");
var gameScore = new GameScore();
let data = {
playerName: "Some Name",
score: 2918,
cheatMode: true
};
gameScore.save(data, {
success: (gameScore) => {
// let q = new Parse.Query("GameScore");
// q.get(gameScore.id)
console.log("ID: " + gameScore.id)
},
error: function (gameScore, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and message.
alert('Failed to create new object, with error code: ' + error.message);
}
});
// End of Parse code
The problem is that you're executing the query to find which object you want to update, but then you're not using the results when you go to save data.
query.first({ // This will result in just one object returned
success: (result) => {
// Check to make sure a result exists
if (result) {
result.save(data, {
// Rest of code
Note: You're treating playerName as a unique key. If multiple users can have the same playerName attribute, then there will be bugs. You can use id instead which is guaranteed to be unique. If you use id instead, you can utilize Parse.Query.get
Edit:
Since you want to update an existing object, you must specify its id.
var GameScore = Parse.Object.extend("GameScore");
var gameScore = new GameScore();
gameScore.id = "ID"; // This id should be the id of the object you want to update

sys_id arrays to is one of not displaying records on my report

I am not able to display records on my report.
Report Source: Group Approval(sysapproval_group) table
Condition:Sys Id - is one of - javascript: new GetMyGroupApprovals().getSysIds();
Script Include : MyGroupApproval
Note : Active is checked, Accesible is all application score & Client callable unchecked
var GetMyGroupApprovals = Class.create();
GetMyGroupApprovals.prototype = {
initialize: function() {
},
getSysIds : function getMyGroupMembers(){
var ga = new GlideRecord('sysapproval_group');
ga.addQuery('parent.sys_class_name', '=', 'change_request');
ga.query();
gs.log("TotalRecords1 Before:: " + ga.getRowCount());
var sysIdArray = [];
while(ga.next()){
sysIdArray.push(ga.sys_id);
}
return sysIdArray;
},
type: 'GetMyGroupApprovals'
};
Kindly note that I have to achieve with script approach. I am not able to get records on my report.
This line is probably causing unexpected behavior:
sysIdArray.push(ga.sys_id);
ga.sys_id returns a GlideElement object, which changes for each of the iterations in the GlideRecord, so the contents of sysIdArray will just be an instance of the same object for each row in the result set, but the value will just be the last row in the set.
You need to make sure you push a string to the array by using one of the following methods:
sysIdArray.push(ga.sys_id+''); // implicitly call toString
sysIdArray.push(ga.getValue('sys_id')); // return string value
Quick suggestion, you can use the following to get sys_ids as well:
sysIdArray.push(ga.getUniqueValue());

Django AJAX call: Referencing Table in JS

Is there a way I can reference a list containing data from my database (item_list = inventory.objects.order_by('name')) in my jquery AJAX call?
This is my code:
/models.py:
class phonebook(models.Model):
name = models.Charfield(max_length=200)
phone_number = models.CharField(max_length=100)
/views.py:
def phonebook_home(request):
global phonebook
phonebook = phonebook.objects.order_by('name')
def get_next_3_contacts(request):
returnedContacts = phonebook[contactIndex:contactIndex+3]
return HttpResponse(phonebook)
/main.js:
var = ajax_call {
type: 'GET'
url: DEFINED_URL
data: {
index: contactIndex
},
dataType: 'html'
success: function (returned, textStatus_ignored, jqXHR_ignored) {
var contactIndex = 0
function phonebook_list(name, phone_number) {
"<li>" + name + " : " + phone_number + "</li>"
}
for(var index=0; index < 3; index++) {
var name = phonebook[index].name
var phone_number = phonebook[index].phone_number
$("ul").append(phonebook_list(name, phone_number))
}
contactIndex += 3
}
The phonebook[index].name / .phone_number returns "undefined" on my page. I want to keep my js file separate from my template file as it will be easier for me to debug, but unfortunately, this problem has stumped me. I also inputted an alert to test out if any data was being returned from the data base, which only returns a string containing the names of the contacts with no spacing in between contact names. Ex: "JaredSarahJohn".
All help and any bit of advice is appreciated!
A couple of things need to be cleaned up in order for this solution to work:
Your idea that global phonebook will be available from within get_next_3_contacts() is incorrect. When you make the AJAX call that will ultimately invoke get_next_3_contacts() the variable phonebook is no longer available. It went out of scope when the call to phonebook_home() completed.
What's the solution? Change phonebook_home() to accept an offset and count parameters. Have it hit the database and return the requested quantities. This is called pagination and is something you should get familiar with!
def phonebook_home(request, offset, count):
phonebook = phonebook.objects.all()[offset:offset+count]
But how do we get those results down to your AJAX handler? You can't just "return" a list of objects to the HTTPResponse() function - it's looking for text to render, not Model objects.
import json
from django.http import JsonResponse
def phonebook_home(request, offset, count):
status = "OK"
return_data = ""
try:
phonebook = phonebook.objects.all()[offset:offset+count]
return_data = json.dumps(phonebook)
exception:
status = "UH OH"
return JsonResponse({'data': return_data, 'status': status)

jqGrid drag and drop headings for grouping .... Group Name

I have setup drag and drop headings to group by the relevant column from jQgrid Grouping Drag and Drop
It works great however I am trying to display the column name before the value i.e.
Client : Test data data
Client : Test2 data data
I've been going around in circles if any one could help.
if i take the same code used for the dynamic group by which should be the (column Name)
I end up with The Column data not the column name.
$('#' + gridId).jqGrid('groupingGroupBy', getheader());
function getheader() {
var header = $('#groups ol li:not(.placeholder)').map(function () {
return $(this).attr('data-column');
}).get();
return header;
}
if i use the same function in group text I get data not the column name.
I've come from C# and I am very new to jQuery.
If any one could help it would be greatly appreciated.
Kind Regards,
Ryan
First of all the updated demo provides the solution of your problem:
Another demo contains simplified demo which demonstrates just how one could display the grouping header in the form Column Header: Column data in the grouping header instead of Column data used as default.
The main idea of the solution is the usage of formatDisplayField property of groupingView which I suggested originally in the answer. The current version of jqGrid support the option. If one would use for example the options
grouping: true,
groupingView: {
groupField: ["name", "invdate"],
groupColumnShow: [false, false],
formatDisplayField: [
customFormatDisplayField,
customFormatDisplayField
]
}
where customFormatDisplayField callback function are defined as
var customFormatDisplayField = function (displayValue, value, colModel) {
return colModel.name + ": " + displayValue;
}
will display almost the results which you need, but it will uses name property of colModel instead of the corresponding name from colNames. To makes the final solution one use another implementation of customFormatDisplayField:
var getColumnHeaderByName = function (colName) {
var $self = $(this),
colNames = $self.jqGrid("getGridParam", "colNames"),
colModel = $self.jqGrid("getGridParam", "colModel"),
cColumns = colModel.length,
iCol;
for (iCol = 0; iCol < cColumns; iCol++) {
if (colModel[iCol].name === colName) {
return colNames[iCol];
}
}
},
customFormatDisplayField = function (displayValue, value, colModel, index, grp) {
return getColumnHeaderByName.call(this, colModel.name) + ": " + displayValue;
};

How to use a confirmation button in Google Apps Script spreadsheet embedded scripts?

I have this Google Apps Script to send an email with a request to people I choose in a spreadsheet:
function sendRequestEmail() {
var data = SpreadsheetApp.openById(SPREADSHEET);
if(!employee_ID) {
employee_ID = getCurrentRow();
if (employee_ID == 1) {
var employee_ID = Browser.inputBox("Você precisa selecionar um assistido?", "Choose a row or type its number here:", Browser.Buttons.OK_CANCEL);
}
}
// Fetch variable names
// they are column names in the spreadsheet
var sheet = data.getSheets()[0];
var columns = getRowAsArray(sheet, 1);
Logger.log("Processing columns =" + columns);
var employeeData = getRowAsArray(sheet, employee_ID);
Logger.log("Processing employeeData = " + employeeData);
// Assume first column holds the name of the person
var email2Send = "pythonist#example.com";
var title = "Request by email";
var name = employeeData[0];
var mother_name = employeeData[1];
var message = "Hi, I have a request for you, " + name + ", this is... example";
// HERE THE
// CONFIRMATION BUTTON!!!
MailApp.sendEmail(email2Send, title, message);
}
And, before sending the email, I want a confirmation button, something like this:
function showConfirmation(name, email2Send) {
var app = UiApp.createApplication().setHeight(150).setWidth(250);
var msg = "Do you confirm the request to " + email2Send + " about " + name + "?";
app.setTitle("Confirmation of request");
app.add(app.createVerticalPanel().add(app.createLabel(msg)));
var doc = SpreadsheetApp.getActive();
doc.show(app);
}
So, if user press OK, the app will execute the line MailApp.sendEmail(email2Send, title, message); and send an e-mail.
I have to admit my ignorance. I'm reading chapter 4 of the book "Google Apps Script" (Oreilly, by James Ferreira) on handlers. I've tried using an example provided in the documentation from Google (already deleted the code!). But I came across an error that I could not understand.
The code used were this sample:
var ui = DocumentApp.getUi();
var response = ui.prompt('Getting to know you', 'May I know your name?', ui.ButtonSet.YES_NO);
// Process the user's response.
if (response.getSelectedButton() == ui.Button.YES) ... DO THIS
I have some urgency in this simple project, so forgive-me for asking this question before research more for the answer (I'm searching for it while wating for the answer). So, how can I use a confirmation/cancellation button in this code?
The code snippet you showed is for document embedded UI, the equivalent (well... almost) class for spreadsheet context is Browser.MsgBox(prompt,buttons), see doc here, it will be simpler than create a Ui + a handler function... even if the layout and appearance are fairly basic it's easy and efficient.
In your code it becomes :
...
var confirm = Browser.msgBox('send confirmation','Are you sure you want to send this mail ?', Browser.Buttons.OK_CANCEL);
if(confirm=='ok'){ MailApp.sendEmail(email2Send, title, message)};
...

Resources