If-Else condition not getting detected in Google Apps Script - if-statement

I am looping over the list "res_1" and when the Id is "400" then need to multiply "Total_Weight" with variable "cost_400"; else if the id is "400W", then need to multiply "Total_Weight"
with variable "cost_400W". In the end, "result" array should contain "Vendor" and correspoding number ("Total_Weight" * "cost_400").
In the code below, I loop over "res_1", but for some reason, the if condition is not getting detected and it does not go inside the corresponding if or else if condition.
Any suggestions would be appreciated.
Expected result:
result = [['ABC',42341820 ],['DEF',91734000]]
Input:
res_1:
[ { Id: '400 ', Vendor: 'ABC', Total_Weight: 32322 },
{ Id: '400W ', Vendor: 'DEF', Total_Weight: 61156 } ]
var cost_400 = 1310
var cost_400W = 1500
res_1.forEach((r2,i2)=>{
if (r2['Id'] == "400" ) {
Logger.log(r2['Total_Weight']*cost_400)
}
else if (r2['Id'] == "400W" ) {
Logger.log(r2['Total_Weight']*cost_400W)
}
});

Issue:
Extra space on the res_1. if (r2['Id'] == "400" ) and if (r2['Id'] == "400W" ) will always get false because '400 ' is not equal to '400' and '400W ' is not equal to '400W'.
Solution:
If you cannot manipulate the output of res, you can use String.match() and reverse the if else statement. The reason for reversal is that String.match(400) can catch both 400 and 400W and if we start with String.match('400W') we can prevent the method from catching 400.
Your code should look like this:
function myFunction() {
var res_1=
[ { Id: '400 ', Vendor: 'ABC', Total_Weight: 32322 },
{ Id: '400W ', Vendor: 'DEF', Total_Weight: 61156 } ]
var cost_400 = 1310
var cost_400W = 1500
res_1.forEach((r2,i2)=>{
if (r2['Id'].match("400W")) {
Logger.log(r2['Total_Weight']*cost_400W)
}
else if (r2['Id'].match("400")) {
Logger.log(r2['Total_Weight']*cost_400)
}
});
}
Output:
Reference:
String.match()

Related

Unit Test to find a keyword in a response array

good day everyone, i am new here,
I have a response data looking like this
[
{
"Outlet": "Outlet1",
"Inventory": 12
},
{
"Outlet": "Outlet2",
"Inventory": 0
},
{
"Outlet": "Outlet3",
"Inventory": 3
},
{
"Outlet": "Outlet4",
"Inventory": 0
}
}
I need to verify if the outlet 1 inventory is exact 12, and every other data EXCEPT outlet1 inventory is 0. do i need to loop the test?
I’ve already tried:
pm.test("Inventory.OnHand Outlet1 == 12", () => {
let Outlet1Result = jsonData.find(a => a.Outlet === "Outlet1")
pm.expect(Outlet1Result.Outlet).to.eql("Outlet1")
pm.expect(Outlet1Result.Inventory).to.eql(12)
});
pm.test("Inventory.OnHand not Outlet1 == 0", () => {
if (jsonData.Outlet !== "Outlet1") {
jsonData.forEach(function() {
let result2 = jsonData.find(a => a.Outlet !== "Outlet1")
pm.expect(result2.Inventory).to.eql(0)
}) ;
}
});
I have tried using this 2 test, the first test worked just fine, but i think the second test is wrong because it’s passed, it should not be passed since outlet 3 inventory is 3, the text expect it to be 0
Other way would be :
pm.test("Validate inventory values", () => {
jsonData.forEach(function (item) {
if (item.Outlet !== "Outlet1") {
pm.expect(item.Inventory,
`Expected inventory value of ${item.Outlet} to be 0`).
to.
eql(0)
} else {
pm.expect(item.Inventory,
`Expected inventory value of ${item.Outlet} to be 12`).
to.
eql(12)
}
})
});
why can't you just compare the object as it is than individual fields ? as you are comparing exact values.
let expected = [
{
"Outlet": "Outlet1",
"Inventory": 12
},
{
"Outlet": "Outlet2",
"Inventory": 0
},
{
"Outlet": "Outlet3",
"Inventory": 3
},
{
"Outlet": "Outlet4",
"Inventory": 0
}
]
pm.expect(JSONdata).to.be.deep.eq(expected1, `Expected ${JSON.stringify(JSONdata,null,2)} to be equal to ${JSON.stringify(expected,null,2)}`)

AWS RDS Data API executeStatement not return column names

I'm playing with the New Data API for Amazon Aurora Serverless
Is it possible to get the table column names in the response?
If for example I run the following query in a user table with the columns id, first_name, last_name, email, phone:
const sqlStatement = `
SELECT *
FROM user
WHERE id = :id
`;
const params = {
secretArn: <mySecretArn>,
resourceArn: <myResourceArn>,
database: <myDatabase>,
sql: sqlStatement,
parameters: [
{
name: "id",
value: {
"stringValue": 1
}
}
]
};
let res = await this.RDS.executeStatement(params)
console.log(res);
I'm getting a response like this one, So I need to guess which column corresponds with each value:
{
"numberOfRecordsUpdated": 0,
"records": [
[
{
"longValue": 1
},
{
"stringValue": "Nicolas"
},
{
"stringValue": "Perez"
},
{
"stringValue": "example#example.com"
},
{
"isNull": true
}
]
]
}
I would like to have a response like this one:
{
id: 1,
first_name: "Nicolas",
last_name: "Perez",
email: "example#example.com",
phone: null
}
update1
I have found an npm module that wrap Aurora Serverless Data API and simplify the development
We decided to take the current approach because we were trying to cut down on the response size and including column information with each record was redundant.
You can explicitly choose to include column metadata in the result. See the parameter: "includeResultMetadata".
https://docs.aws.amazon.com/rdsdataservice/latest/APIReference/API_ExecuteStatement.html#API_ExecuteStatement_RequestSyntax
Agree with the consensus here that there should be an out of the box way to do this from the data service API. Because there is not, here's a JavaScript function that will parse the response.
const parseDataServiceResponse = res => {
let columns = res.columnMetadata.map(c => c.name);
let data = res.records.map(r => {
let obj = {};
r.map((v, i) => {
obj[columns[i]] = Object.values(v)[0]
});
return obj
})
return data
}
I understand the pain but it looks like this is reasonable based on the fact that select statement can join multiple tables and duplicated column names may exist.
Similar to the answer above from #C.Slack but I used a combination of map and reduce to parse response from Aurora Postgres.
// declarative column names in array
const columns = ['a.id', 'u.id', 'u.username', 'g.id', 'g.name'];
// execute sql statement
const params = {
database: AWS_PROVIDER_STAGE,
resourceArn: AWS_DATABASE_CLUSTER,
secretArn: AWS_SECRET_STORE_ARN,
// includeResultMetadata: true,
sql: `
SELECT ${columns.join()} FROM accounts a
FULL OUTER JOIN users u ON u.id = a.user_id
FULL OUTER JOIN groups g ON g.id = a.group_id
WHERE u.username=:username;
`,
parameters: [
{
name: 'username',
value: {
stringValue: 'rick.cha',
},
},
],
};
const rds = new AWS.RDSDataService();
const response = await rds.executeStatement(params).promise();
// parse response into json array
const data = response.records.map((record) => {
return record.reduce((prev, val, index) => {
return { ...prev, [columns[index]]: Object.values(val)[0] };
}, {});
});
Hope this code snippet helps someone.
And here is the response
[
{
'a.id': '8bfc547c-3c42-4203-aa2a-d0ee35996e60',
'u.id': '01129aaf-736a-4e86-93a9-0ab3e08b3d11',
'u.username': 'rick.cha',
'g.id': 'ff6ebd78-a1cf-452c-91e0-ed5d0aaaa624',
'g.name': 'valentree',
},
{
'a.id': '983f2919-1b52-4544-9f58-c3de61925647',
'u.id': '01129aaf-736a-4e86-93a9-0ab3e08b3d11',
'u.username': 'rick.cha',
'g.id': '2f1858b4-1468-447f-ba94-330de76de5d1',
'g.name': 'ensightful',
},
]
Similar to the other answers, but if you are using Python/Boto3:
def parse_data_service_response(res):
columns = [column['name'] for column in res['columnMetadata']]
parsed_records = []
for record in res['records']:
parsed_record = {}
for i, cell in enumerate(record):
key = columns[i]
value = list(cell.values())[0]
parsed_record[key] = value
parsed_records.append(parsed_record)
return parsed_records
I've added to the great answer already provided by C. Slack to deal with AWS handling empty nullable character fields by giving the response { "isNull": true } in the JSON.
Here's my function to handle this by returning an empty string value - this is what I would expect anyway.
const parseRDSdata = (input) => {
let columns = input.columnMetadata.map(c => { return { name: c.name, typeName: c.typeName}; });
let parsedData = input.records.map(row => {
let response = {};
row.map((v, i) => {
//test the typeName in the column metadata, and also the keyName in the values - we need to cater for a return value of { "isNull": true } - pflangan
if ((columns[i].typeName == 'VARCHAR' || columns[i].typeName == 'CHAR') && Object.keys(v)[0] == 'isNull' && Object.values(v)[0] == true)
response[columns[i].name] = '';
else
response[columns[i].name] = Object.values(v)[0];
}
);
return response;
}
);
return parsedData;
}

Swift Storing Appending multiple Dictionary into array

I want to store multiple dictionary into an array so that the final results looks like so
(
{
id: 12,
task : completed
},
{
id: 15,
task : error
},
{
id: 17,
task : pending
},
)
I tried with code below but it does not give me what I want Please can someone help me out. Thanks
var FinalTaskData = [[String:AnyObject]]()
for i in 0..<taskObj.count{
let dict = ["id":taskObj[i].id!,"task":taskObj[i].task!] as [String : AnyObject]
FinalTaskData.append(dict)
}
And this gives me the output of
(
{
id = 190;
},
{
task = "Task To Be Edited";
},
{
id = 191;
},
{
task = "Also To Be Edited";
}
)
Which is not what I want. Thanks

Smartclient ListGrid RestDataSource not Populating

Code:
isc.RestDataSource.create({
ID: "restDS",
dataFormat: "xml",
fetchDataURL: "http://192.168.1.21:8282/uom/username=vikash%7C214057357158656/password=gbadmin/ModifiedOn=0",
fields: [
{name:"UOMId"},
{name:"UOMCode"},
{name:"UOMName"}
,
{name:"UOMType"},
{name:"UOMNoOfDecimals"},
{name:"UOMStatus"}
]
});
isc.ListGrid.create({
ID: "restList",
width:800, height:224, alternateRecordStyles:true,
dataSource: restDS,
fields:[
{name:"UOMId"},
{name:"UOMCode"},
{name:"UOMName"}
,
{name:"UOMType"},
{name:"UOMNoOfDecimals"},
{name:"UOMStatus"}
],
autoFetchData:true,
autoDraw: true
});
This Error I'm getting in browser
XML Parsing Error: no element found Location: moz-nullprincipal:{bc0868f9-b8df-4acd-b155-e58c50373d1b} Line Number 1, Column 1:
WebService Content
<ResponseJSON><Body><Datalist><UOMId>-1499999999</UOMId><UOMCode>MPM</UOMCode><UOMName>Meters Per Minute</UOMName><UOMType>2</UOMType><UOMNoOfDecimals>4</UOMNoOfDecimals><UOMStatus>1</UOMStatus></Datalist><Datalist><UOMId>-1499999997</UOMId><UOMCode>MM</UOMCode><UOMName>Milli Metres</UOMName><UOMType>0</UOMType><UOMNoOfDecimals>4</UOMNoOfDecimals><UOMStatus>1</UOMStatus></Datalist><Datalist><UOMId>-1499999996</UOMId><UOMCode>GSM</UOMCode><UOMName>Grammes per Square Metre</UOMName><UOMType>6</UOMType><UOMNoOfDecimals>4</UOMNoOfDecimals><UOMStatus>1</UOMStatus></Datalist><Datalist><UOMId>-1499999994</UOMId><UOMCode>LPM</UOMCode><UOMName>Litres Per Minute</UOMName><UOMType>2</UOMType><UOMNoOfDecimals>4</UOMNoOfDecimals><UOMStatus>1</UOMStatus></Datalist><Datalist><UOMId>-1499999993</UOMId><UOMCode>GRADE</UOMCode><UOMName>Grade</UOMName><UOMType>6</UOMType><UOMNoOfDecimals>4</UOMNoOfDecimals><UOMStatus>1</UOMStatus></Datalist><Datalist><UOMId>-1499999992</UOMId><UOMCode>GRAM</UOMCode><UOMName>Gram</UOMName><UOMType>1</UOMType><UOMNoOfDecimals>4</UOMNoOfDecimals><UOMStatus>1</UOMStatus></Datalist><Datalist><UOMId>-1499999991</UOMId><UOMCode>Degree</UOMCode><UOMName>Degree</UOMName><UOMType>6</UOMType><UOMNoOfDecimals>4</UOMNoOfDecimals><UOMStatus>1</UOMStatus></Datalist><Datalist><UOMId>-1499999990</UOMId><UOMCode>SET</UOMCode><UOMName>Set</UOMName><UOMType>6</UOMType><UOMNoOfDecimals>4</UOMNoOfDecimals><UOMStatus>1</UOMStatus></Datalist><Datalist><UOMId>-1499999989</UOMId><UOMCode>VOLT</UOMCode><UOMName>Volts</UOMName><UOMType>6</UOMType><UOMNoOfDecimals>4</UOMNoOfDecimals><UOMStatus>1</UOMStatus></Datalist><Datalist><UOMId>-1499999988</UOMId><UOMCode>AMPERE</UOMCode><UOMName>Ampere</UOMName><UOMType>6</UOMType><UOMNoOfDecimals>4</UOMNoOfDecimals><UOMStatus>1</UOMStatus></Datalist><Datalist><UOMId>-1499999987</UOMId><UOMCode>CELSIUS</UOMCode><UOMName>Celsius</UOMName><UOMType>6</UOMType><UOMNoOfDecimals>4</UOMNoOfDecimals><UOMStatus>1</UOMStatus></Datalist><Datalist><UOMId>-1499999986</UOMId><UOMCode>HZ</UOMCode><UOMName>Hertz</UOMName><UOMType>6</UOMType><UOMNoOfDecimals>4</UOMNoOfDecimals><UOMStatus>1</UOMStatus></Datalist><Datalist><UOMId>-1499999985</UOMId><UOMCode>HRS</UOMCode><UOMName>Hours</UOMName><UOMType>6</UOMType><UOMNoOfDecimals>4</UOMNoOfDecimals><UOMStatus>1</UOMStatus></Datalist><Datalist><UOMId>-1499999984</UOMId><UOMCode>LITERS</UOMCode><UOMName>Liters</UOMName><UOMType>6</UOMType><UOMNoOfDecimals>4</UOMNoOfDecimals><UOMStatus>1</UOMStatus></Datalist><Datalist><UOMId>-1499999983</UOMId><UOMCode>KWh</UOMCode><UOMName>KiloWatt Per Hour</UOMName><UOMType>6</UOMType><UOMNoOfDecimals>4</UOMNoOfDecimals><UOMStatus>1</UOMStatus></Datalist><Datalist><UOMId>-1499999982</UOMId><UOMCode>GRAVITY</UOMCode><UOMName>Gravity</UOMName><UOMType>6</UOMType><UOMNoOfDecimals>4</UOMNoOfDecimals><UOMStatus>1</UOMStatus></Datalist><Datalist><UOMId>-1499999981</UOMId><UOMCode>PRSR</UOMCode><UOMName>Pressure</UOMName><UOMType>6</UOMType><UOMNoOfDecimals>4</UOMNoOfDecimals><UOMStatus>1</UOMStatus></Datalist><Datalist><UOMId>-1499999980</UOMId><UOMCode>KVARh</UOMCode><UOMName>KVARh</UOMName><UOMType>6</UOMType><UOMNoOfDecimals>4</UOMNoOfDecimals><UOMStatus>1</UOMStatus></Datalist><Datalist><UOMId>-1499999979</UOMId><UOMCode>KVAh</UOMCode><UOMName>KVAh</UOMName><UOMType>6</UOMType><UOMNoOfDecimals>4</UOMNoOfDecimals><UOMStatus>1</UOMStatus></Datalist><Datalist><UOMId>-1499999978</UOMId><UOMCode>kVA</UOMCode><UOMName>kVA</UOMName><UOMType>6</UOMType><UOMNoOfDecimals>4</UOMNoOfDecimals><UOMStatus>1</UOMStatus></Datalist><Datalist><UOMId>-1499999977</UOMId><UOMCode>KW</UOMCode><UOMName>Kilo Watt</UOMName><UOMType>6</UOMType><UOMNoOfDecimals>4</UOMNoOfDecimals><UOMStatus>1</UOMStatus></Datalist><Datalist><UOMId>-1499999976</UOMId><UOMCode>VL</UOMCode><UOMName>V Line</UOMName><UOMType>6</UOMType><UOMNoOfDecimals>4</UOMNoOfDecimals><UOMStatus>1</UOMStatus></Datalist><Datalist><UOMId>-1499999975</UOMId><UOMCode>IL</UOMCode><UOMName>I Line</UOMName><UOMType>6</UOMType><UOMNoOfDecimals>4</UOMNoOfDecimals><UOMStatus>1</UOMStatus></Datalist><Datalist><UOMId>-1499999974</UOMId><UOMCode>TR</UOMCode><UOMName>TR</UOMName><UOMType>6</UOMType><UOMNoOfDecimals>4</UOMNoOfDecimals><UOMStatus>1</UOMStatus></Datalist><Datalist><UOMId>-1499999973</UOMId><UOMCode>PSIG</UOMCode><UOMName>PSIG</UOMName><UOMType>6</UOMType><UOMNoOfDecimals>4</UOMNoOfDecimals><UOMStatus>1</UOMStatus></Datalist><Datalist><UOMId>-1499999972</UOMId><UOMCode>FH</UOMCode><UOMName>Fahrenheit</UOMName><UOMType>6</UOMType><UOMNoOfDecimals>4</UOMNoOfDecimals><UOMStatus>1</UOMStatus></Datalist><Datalist><UOMId>-1499999971</UOMId><UOMCode>Y/N</UOMCode><UOMName>Y/N</UOMName><UOMType>6</UOMType><UOMNoOfDecimals>4</UOMNoOfDecimals><UOMStatus>1</UOMStatus></Datalist><Datalist><UOMId>-1499999970</UOMId><UOMCode>KL</UOMCode><UOMName>KL</UOMName><UOMType>6</UOMType><UOMNoOfDecimals>4</UOMNoOfDecimals><UOMStatus>1</UOMStatus></Datalist><Datalist><UOMId>-1499999969</UOMId><UOMCode>INR</UOMCode><UOMName>INR</UOMName><UOMType>1</UOMType><UOMNoOfDecimals>2</UOMNoOfDecimals><UOMStatus>1</UOMStatus></Datalist><Datalist><UOMId>-1499999968</UOMId><UOMCode>RKVAH</UOMCode><UOMName>RKVAH</UOMName><UOMType>1</UOMType><UOMNoOfDecimals>2</UOMNoOfDecimals><UOMStatus>1</UOMStatus></Datalist><Datalist><UOMId>-1499999967</UOMId><UOMCode>UNITS</UOMCode><UOMName>UNITS</UOMName><UOMType>1</UOMType><UOMNoOfDecimals>2</UOMNoOfDecimals><UOMStatus>1</UOMStatus></Datalist><Datalist><UOMId>-1499999966</UOMId><UOMCode>SQFT</UOMCode><UOMName>SQFT</UOMName><UOMType>1</UOMType><UOMNoOfDecimals>2</UOMNoOfDecimals><UOMStatus>1</UOMStatus></Datalist><Datalist><UOMId>-1499999965</UOMId><UOMCode>MTS</UOMCode><UOMName>Minutes</UOMName><UOMType>1</UOMType><UOMNoOfDecimals>2</UOMNoOfDecimals><UOMStatus>1</UOMStatus></Datalist><Datalist><UOMId>269758049027601</UOMId><UOMCode>rt</UOMCode><UOMName>rt12</UOMName><UOMType>2</UOMType><UOMNoOfDecimals>1</UOMNoOfDecimals><UOMStatus>1</UOMStatus></Datalist><Datalist><UOMId>-1500000000</UOMId><UOMCode>NOS</UOMCode><UOMName>Numbers</UOMName><UOMType>6</UOMType><UOMNoOfDecimals>3</UOMNoOfDecimals><UOMStatus>1</UOMStatus></Datalist><Datalist><UOMId>-1499999998</UOMId><UOMCode>PPM</UOMCode><UOMName>Parts Per Million</UOMName><UOMType>3</UOMType><UOMNoOfDecimals>4</UOMNoOfDecimals><UOMStatus>1</UOMStatus></Datalist><Datalist><UOMId>-1499999995</UOMId><UOMCode>%</UOMCode><UOMName>Percentage</UOMName><UOMType>3</UOMType><UOMNoOfDecimals>4</UOMNoOfDecimals><UOMStatus>1</UOMStatus></Datalist><Datalist><UOMId>301246830151381</UOMId><UOMCode>cccc</UOMCode><UOMName>cccc</UOMName><UOMType>0</UOMType><UOMNoOfDecimals>1</UOMNoOfDecimals><UOMStatus>1</UOMStatus></Datalist><Datalist><UOMId>306495824922361</UOMId><UOMCode>sd</UOMCode><UOMName>sd</UOMName><UOMType>1</UOMType><UOMNoOfDecimals>4</UOMNoOfDecimals><UOMStatus>1</UOMStatus></Datalist><Datalist><UOMId>301243241629396</UOMId><UOMCode>asdf</UOMCode><UOMName>aaaa</UOMName><UOMType>0</UOMType><UOMNoOfDecimals>2</UOMNoOfDecimals><UOMStatus>1</UOMStatus></Datalist><Datalist><UOMId>545196525553078</UOMId><UOMCode>YTY</UOMCode><UOMName>QYRDY</UOMName><UOMType>1</UOMType><UOMNoOfDecimals>3</UOMNoOfDecimals><UOMStatus>1</UOMStatus></Datalist></Body><Status>200</Status><Total>41.0</Total></ResponseJSON>
plz help
Thank You
Your webservice returns incorrect response for RestDataSource. Example of expected response you can see in documentation here: RestDataSource
Another option that you have is to override response parsing. In your case it will be something like this:
isc.RestDataSource.create({
ID: "restDS",
dataFormat: "xml",
fetchDataURL: "http://192.168.1.21:8282/uom/username=vikash%7C214057357158656/password=gbadmin/ModifiedOn=0",
xmlRecordXPath:"/ResponseJSON/Body/*",
fields: [
{name:"UOMId"},
{name:"UOMCode"},
{name:"UOMName"},
{name:"UOMType"},
{name:"UOMNoOfDecimals"},
{name:"UOMStatus"}
] ,
transformResponse : function (dsResponse, dsRequest, data) {
var totalRows = data.selectNumber("//Total");
if (totalRows != null) dsResponse.totalRows = totalRows;
var startRow = data.selectNumber("//startRow");
if (startRow != null) dsResponse.startRow = startRow;
var endRow = data.selectNumber("//endRow");
if (endRow != null) dsResponse.endRow = endRow;
return dsResponse;
}
});
Note that I overwritten xmlRecordPath property and transformResponse method.

jqgrid: How to define filter presets / templates inside a combo-box?

I have a jqgrid containing some data to filter. I'd like to define a combo box with some pre-defined filter sets / templates.
If a user selects an item of the combobox, the grid should automatically apply combined filters. Preferably, the combo box should be integrated into a toolbar or jqGrid's pager, but also in the html page would be fine.
For example:
COMBO BOX
Item templates filter parameters
___________
|Expired | << Timeout = true
|Last Week | << OpenDate between 02/13/2012 and 02/16/2012
|Last Month | << OpenDate between 01/01/2012 and 02/16/2012
|......... | ......
Thanks in advance for your help
jqGrid supports Searching Templates in the Advance Searching (see "Searching"/ "Search Templates" in the official jqGrid demo), but there are currently no searching templates support in the Toolbar Filtering.
I find your question very interesting. In the old question I described how one can use generic external filters to send additional information to the server. The way can be good in case of remote data, but it can't be used directly in the local grid or in the grid with the loadonce: true option.
So I created the demo which shows how the filter templates can be implemented in Toolbar Filtering and how to integrated the template in the jqGrid. I used toolbar: [true, "top"] to have additional empty toolbar above the column headers:
In the implementation I used the refreshSerchingToolbar function which I suggested originally here. It's important to understand, that the refreshSerchingToolbar function fill in the filter toolbar only the information which can be exactly represented by the filter. For example the filter for "Closed" rows can be represented in the filter toolbar (see the picture above), but the interval of dates "Last Week" and "Last Month" con't. In the cases the data in the grid will be filtered, but the corresponding fields of the filter toolbar stay empty.
The most important part of the code of the demo you can find below
var $grid = $("#list"),
initDate = function (elem) {
$(elem).datepicker({
dateFormat: 'dd-M-yy',
autoSize: true,
changeYear: true,
changeMonth: true,
showButtonPanel: true,
showWeek: true
});
},
numberTemplate = {formatter: 'number', align: 'right', sorttype: 'number', editable: true/*,
searchoptions: { sopt: ['eq', 'ne', 'lt', 'le', 'gt', 'ge', 'nu', 'nn', 'in', 'ni'] }*/},
dateTemplate = {width: 80, align: 'center', sorttype: 'date',
formatter: 'date', formatoptions: { newformat: 'd-M-Y' }, editable: true, datefmt: 'd-M-Y',
editoptions: { dataInit: initDate },
searchoptions: { sopt: ['eq', 'ne', 'lt', 'le', 'gt', 'ge'], dataInit: initDate }},
yesNoTemplate = {align: 'center', editable: true, formatter: 'checkbox',
edittype: 'checkbox', editoptions: {value: 'Yes:No', defaultValue: 'No'},
stype: 'select', searchoptions: { sopt: ['eq', 'ne'], value: ':Any;true:Yes;false:No' }},
myDefaultSearch = 'cn',
getColumnIndex = function (columnIndex) {
var cm = this.jqGrid('getGridParam', 'colModel'), i, l = cm.length;
for (i = 0; i < l; i++) {
if ((cm[i].index || cm[i].name) === columnIndex) {
return i; // return the colModel index
}
}
return -1;
},
refreshSerchingToolbar = function (myDefaultSearch) {
var filters, i, l, rules, rule, iCol, cmi, control, tagName,
$this = $(this),
postData = $this.jqGrid('getGridParam', 'postData'),
cm = $this.jqGrid('getGridParam', 'colModel');
for (i = 0, l = cm.length; i < l; i++) {
control = $("#gs_" + $.jgrid.jqID(cm[i].name));
if (control.length > 0) {
tagName = control[0].tagName.toUpperCase();
if (tagName === "SELECT") { // && cmi.stype === "select"
control.find("option[value='']")
.attr('selected', 'selected');
} else if (tagName === "INPUT") {
control.val('');
}
}
}
if (typeof (postData.filters) === "string" &&
typeof (this.ftoolbar) === "boolean" && this.ftoolbar) {
filters = $.parseJSON(postData.filters);
if (filters && filters.groupOp === "AND" && typeof (filters.groups) === "undefined") {
// only in case of advance searching without grouping we import filters in the
// searching toolbar
rules = filters.rules;
for (i = 0, l = rules.length; i < l; i++) {
rule = rules[i];
iCol = getColumnIndex.call($this, rule.field);
if (iCol >= 0) {
cmi = cm[iCol];
control = $("#gs_" + $.jgrid.jqID(cmi.name));
if (control.length > 0 &&
(((typeof (cmi.searchoptions) === "undefined" ||
typeof (cmi.searchoptions.sopt) === "undefined")
&& rule.op === myDefaultSearch) ||
(typeof (cmi.searchoptions) === "object" &&
$.isArray(cmi.searchoptions.sopt) &&
cmi.searchoptions.sopt.length > 0 &&
cmi.searchoptions.sopt[0] === rule.op))) {
tagName = control[0].tagName.toUpperCase();
if (tagName === "SELECT") { // && cmi.stype === "select"
control.find("option[value='" + $.jgrid.jqID(rule.data) + "']")
.attr('selected', 'selected');
} else if (tagName === "INPUT") {
control.val(rule.data);
}
}
}
}
}
}
},
templateClosed = {
groupOp: "AND",
rules: [
{ field: "closed", op: "eq", data: "true" }
]
},
templateLastWeek = {
groupOp: "AND",
rules: [
{ field: "invdate", op: "ge", "data": "13-Feb-2012" },
{ field: "invdate", op: "le", "data": "16-Feb-2012"}
]
},
templateLastMonth = {
groupOp: "AND",
rules: [
{ field: "invdate", op: "ge", "data": "16-Jan-2012" },
{ field: "invdate", op: "le", "data": "16-Feb-2012"}
]
},
myFilterTemplateLabel = 'Filter by Template: ',
myFilterTemplateNames = ['Closed', 'Last Week', 'Last Month'],
myFilterTemplates = [templateClosed, templateLastWeek, templateLastMonth],
iTemplate,
cTemplates = myFilterTemplateNames.length,
templateOptions = '',
reloadWithNewFilterTemplate = function () {
var iTemplate = parseInt($('#filterTemplates').val(), 10),
postData = $grid.jqGrid('getGridParam', 'postData');
if (isNaN(iTemplate)) {
$grid.jqGrid('setGridParam', {search: false});
} else if (iTemplate >= 0) {
$.extend(postData, {
filters: JSON.stringify(myFilterTemplates[iTemplate])
});
$grid.jqGrid('setGridParam', {search: true});
}
$grid.trigger('reloadGrid', [{current: true, page: 1}]);
};
$grid.jqGrid({
...
toolbar: [true, "top"],
loadComplete: function () {
var $this = $(this);
if (typeof (this.ftoolbar) !== "boolean") {
// create toolbar if needed
$this.jqGrid('filterToolbar',
{stringResult: true, searchOnEnter: true, defaultSearch: myDefaultSearch});
}
refreshSerchingToolbar.call(this, myDefaultSearch);
}
});
$.extend($.jgrid.search, {
multipleSearch: true,
multipleGroup: true,
recreateFilter: true,
closeOnEscape: true,
closeAfterSearch: true,
overlay: 0,
tmplLabel: myFilterTemplateLabel,
tmplNames: myFilterTemplateNames,
tmplFilters: myFilterTemplates
});
$grid.jqGrid('navGrid', '#pager', {edit: false, add: false, del: false});
for (iTemplate = 0; iTemplate < cTemplates; iTemplate++) {
templateOptions += '<option value="' + iTemplate + '">' +
myFilterTemplateNames[iTemplate] + '</option>';
}
$('#t_' + $.jgrid.jqID($grid[0].id)).append('<label for="filterTemplates">'+
myFilterTemplateLabel + '</label>' +
'<select id="filterTemplates"><option value="">Not filtered</option>' +
templateOptions + '</select>');
$('#filterTemplates').change(reloadWithNewFilterTemplate).keyup(function (e) {
// some web browsers like Google Chrome don't fire "change" event
// if the select will be "scrolled" by keybord. Moreover some browsers
// like Internet Explorer don't change the select option on pressing
// of LEFT or RIGHT key. Another web browsers like Google Chrome do this.
// We make refrech of the grid in any from the cases. If needed one
// could modify the code to reduce unnneded reloading of the grid,
// but for the demo with a few local rows it's such optimization
// isn't really needed
var keyCode = e.keyCode || e.which;
if (keyCode === $.ui.keyCode.PAGE_UP || keyCode === $.ui.keyCode.PAGE_DOWN ||
keyCode === $.ui.keyCode.END || keyCode === $.ui.keyCode.HOME ||
keyCode === $.ui.keyCode.UP || keyCode === $.ui.keyCode.DOWN ||
keyCode === $.ui.keyCode.LEFT || keyCode === $.ui.keyCode.RIGHT) {
reloadWithNewFilterTemplate();
}
});