how to added dynamic query params using string in Angular 7? - java

Currently I have multiple dropdown field in screen. when selected dropdown value pass in the query param so I want to create dynamic query param added. my code is below
// this is one of the dropdown value
if (this.SearchText) {
query += 'q:' + SearchText + ',';
}
// this is the second one of dropdown value
if (this.MakeId) {
makename = this.SpaceToDash(this.MakesList.find(x => x.Id === +this.MakeId).Name);
navigateUrl += '/' + makename;
query += 'merk:' + this.MakeId + ',merkname:' + makename + ',';
}
this.router.navigate([ navigateUrl ], { queryParams: { query } });
So if "MakeId" is not dropdown value then should not added in "queryParams" so how can I do it. Above solution is not working it.
Apply solution for Dynamically create query Params in Angular 2 but it is not fit in my requirement. So can you help me anyone in it?

QueryParams should take an Object not a string ,
so you can do it by this way
let query = {};
// this is one of the dropdown value
if (this.SearchText) {
query['q'] = SearchText;
}
// this is the second one of dropdown value
if (this.MakeId) {
makename = this.SpaceToDash(this.MakesList.find(x => x.Id === +this.MakeId).Name);
navigateUrl += '/' + makename;
query['merk'] = this.MakeId;
query['makename'] = makename;
}
this.router.navigate([ navigateUrl ], { queryParams: query });

Related

Show/Hide Form Fields in Squarespace

I am trying to show/hide form fields in a Squarespace form based upon the value selected in a dropdown menu. The dropdown menu has a list of values from 1-10. The intent is to display 2 form fields for each number selected from the dropdown menu. For value 1, I want the form fields titled "Serial Number" and "Confirm Serial Number" to ALWAYS be displayed. For value 2, I want to show "Serial Number 2" and "Confirm Serial Number 2". And so on for values 3-10.
Here is a screenshot of the form as it is now with everything displayed.
enter image description here
You can get the serial element with document.getElementById(`serial-input-${index}`)
You can get the serial confirm element with document.getElementById(`serial-input-confirm-${index}`)
<p>Number of products</p>
<select id="select" onChange="create.input()"></select>
<div id="input"></div>
const create = {
select: () => {
let select = document.getElementById('select')
// Create 1-10 number of products
new Array(10).fill(0).forEach((x, i) => {
let option = document.createElement('option')
option.innerHTML = (i+1)
option.value = (i+1)
select.appendChild(option)
})
},
input: () => {
let input = document.getElementById('input')
let select = document.getElementById('select')
console.log(select.value)
// Remove all child
input.innerHTML = ''
// Create the same number of input has you select in select ...
const size = parseInt(select.value, 10)
new Array(size).fill(0).forEach((x, i) => {
console.log(i)
let p_input = create.p_input(i)
p_input.forEach(x => input.appendChild(x))
})
},
p_input: index => {
let name = `erial number` + (index > 0 ? ' ' + (index+1) : '')
let serial_p = document.createElement('p')
serial_p.innerHTML = 'S' + name
serial_p.id = 'p-serial-' + index
serial_p.class = 'p-serial'
let serial_p_confirm = document.createElement('p')
serial_p_confirm.innerHTML = 'Confirm s' + name
serial_p_confirm.id = 'pc-serial-' + index
serial_p_confirm.class = 'pc-serial'
let serial_input = document.createElement('input')
serial_input.type = "text"
serial_input.id = "serial-input-" + index
serial_input.class = 'serial-input'
let serial_input_confirm = document.createElement('input')
serial_input_confirm.type = "text"
serial_input_confirm.id = "serial-input-confirm-" + index
serial_input_confirm.class = 'serial-input'
return [serial_p, serial_input, serial_p_confirm, serial_input_confirm]
}
}
create.select()
create.input()
for exemple here its what i get when i click on 5.

Return substring of analyzed, non-stored text field in elasticsearch java api

I work on a project that has a string field (the name is urlOrContent) and it can be small (less than 50 character) or very long (more than 50 character), and I just want to return the first 50 characters every time based on a specific query. My database is elasticsearch and my problem is raised in this link and the questioner’s response seems to be correct (urlOrContent field is analyzed and non stored text field). It uses following script:
{
"script_fields": {
"substring": {
"script": {
"lang": "painless",
"inline": "params._source.text.substring(0, 100)"
}
}
}
}
But my main problem is that I can not find the equivalent of elasticsearch java api code. In fact, what should be added to the code below, which only returns the first 50 characters of the urlOrContent field? Note that this field may not even have 50 characters in some cases, and then the entire string should be returned.
String queryString =
EnumLinkFields.CREATE_TIME.getFieldName() + ":(>=" + dateFrom + " AND <=" + dateTo + ")";
QueryBuilder query = QueryBuilders.queryStringQuery(queryString);
SearchResponse response = TRANSPORT_CLIENT.prepareSearch(MY_INDEX)
.setTypes(MY_TYPE)
.setSearchType(SEARCH_TYPE)
.setQuery(query)
.setFetchSource(null, new String[]{EnumLinkFields.USER_ID.getFieldName()})
.setFrom(offset)
.setSize(count)
.addSort(orderByField, sortOrder)
.execute().actionGet();
I found the best answer.
String queryString =
EnumLinkFields.CREATE_TIME.getFieldName() + ":(>=" + dateFrom + " AND <=" + dateTo + ")";
QueryBuilder query = QueryBuilders.queryStringQuery(queryString);
String codeUrlOrContent = "if (" + EnumElasticScriptField.URL_OR_CONTENT.getFieldName() + ".length() > 50) {" +
"return " + EnumElasticScriptField.URL_OR_CONTENT.getFieldName() + ".substring(0, 50);" +
"} else { " +
"return " + EnumElasticScriptField.URL_OR_CONTENT.getFieldName() + "; }";
Script scriptUrlOrContent = new Script(ScriptType.INLINE, "painless",
codeUrlOrContent, Collections.emptyMap());
Script scriptIsUrl = new Script(ScriptType.INLINE, "painless",
EnumElasticScriptField.IS_URL.getFieldName(), Collections.emptyMap());
SearchResponse response = TRANSPORT_CLIENT.prepareSearch(MY_INDEX)
.setTypes(MY_TYPE)
.setSearchType(SEARCH_TYPE)
.setQuery(query)
.addScriptField(EnumLinkFields.URL_OR_CONTENT.getFieldName(),
scriptUrlOrContent)
.addScriptField(EnumLinkFields.IS_URL.getFieldName(), scriptIsUrl)
.setFrom(offset)
.setSize(count)
.addSort(orderByField, sortOrder)
.execute().actionGet();
Note that the call to the setFetchSource function must be removed and all returned fields must be returned through the script.
You can put your script_fields query in the query object, i.e. in setQuery(query).
Your query object should be looking like this right now.
"query" : {
"term" : { "user" : "kimchy" }
}
After you add the script_fields in the object, it should become:
"query" : {
"term" : { "user" : "kimchy" }
},
"script_fields": {
"urlOrContent": {
"script": {
"lang": "painless",
"inline": "if(params._source.urlOrContent.length() > 50){
params._source.urlOrContent.substring(0, 50)
}
else {
params._source.urlOrContent
}"
}
}
}
The resulting hits will have a fields array with the substring you required.
You have to enable scripting by changing the elasticsearch.yml file like so and restart the elasticsearch:
script.engine.painless.inline.aggs: on
script.engine.painless.inline.update: on
script.inline: on
script.indexed: on

How to access duplicate values in simple combo box in ExtJs

I have a SimpleComboBox in GUI which contains some duplicate items also. Assume there are 3 items which is same as "domain". When i select second "domain" or third "domain", the selected item and selected index is always pointing to first occurance of "domain". How can i correct, so that the selected index/item is right one, instead of first occurance of item?
ComboBox with duplicate values:
When i select "domain" at fourth occurence it will always pointing the first occurance of "domain".
Output:
When i select the "192.168.1.30" at last occurenece, it will point the first occurance of "192.168.1.30".
Please any one help me.
private SimpleComboBox<String> domainName = new SimpleComboBox<String>();
domainName = WidgetUtil.getStringCombo("Domain Name", 12, true, domainNameList, null);
domainName.addSelectionChangedListener(getReportSelectionListener());
domainName.setForceSelection(true);
domainName.setTriggerAction(TriggerAction.ALL);
private Button New, add, remove;
New = WidgetUtil.getButton("New", "new", "");
New.addSelectionListener(buttonAction());
thirdLayoutContainer.add(New);
add = WidgetUtil.getButton("Add", "add", "");
add.addSelectionListener(buttonAction());
add.setStyleAttribute("paddingTop", "10px");
thirdLayoutContainer.add(add, formData);
remove = WidgetUtil.getButton("Remove", "remove", "");
remove.addSelectionListener(buttonAction());
public void componentSelected(ButtonEvent ce){
String domain_name = null;
if (ce.getComponent().getId().equals("remove")){
System.err.println("Clicked remove button...");
domain_name = domainName.getRawValue();
domainNameList.remove(domain_name);
systemDetailsMap.remove(domain_name);
systemDetailsMap.remove(domain_name + "_USER_NAME");
systemDetailsMap.remove(domain_name + "_HOST_NAME");
systemDetailsMap.remove(domain_name + "_PASSWORD");
domainName.removeAll();
domainName.add(domainNameList);
userName.clear();
hostName.clear();
password.clear();
System.err.println("After remove domain name list ---> " + domainNameList);
System.err.println("After remove map ---> " + systemDetailsMap);
} else if (ce.getComponent().getId().equals("add")) {
System.err.println("Clicked add button...");
domain_name = domainName.getRawValue();
domainNameList.add(domain_name);
systemDetailsMap.put(domain_name, domain_name);
systemDetailsMap.put(domain_name + "_HOST_NAME", hostName.getValue());
systemDetailsMap.put(domain_name + "_USER_NAME", userName.getValue());
systemDetailsMap.put(domain_name + "_PASSWORD", password.getValue());
// domainName.clear();
domainName.add(domainNameList);
// domainName.reset();
System.err.println("After add domain name list ---> " + domainNameList);
System.err.println("After add map ---> " + systemDetailsMap);
} else if (ce.getComponent().getId().equals("new")) {
System.err.println("Clicked new button...");
userName.clear();
hostName.clear();
password.clear();
domainName.removeAllListeners();
domainName.removeAll();
domainName.clear();
domainName.setEmptyText("Add a new domain");
userName.setEmptyText("Add a new username");
hostName.setEmptyText("Add a new hostname");
password.setEmptyText("Add a new password");
domainName.addSelectionChangedListener(getReportSelectionListener());
}
}
};
private SelectionChangedListener<SimpleComboValue<String>> getReportSelectionListener(){
SelectionChangedListener<SimpleComboValue<String>> ReportListener = new SelectionChangedListener<SimpleComboValue<String>>() {
#Override
public void selectionChanged(SelectionChangedEvent<SimpleComboValue<String>> se) {
SimpleComboValue<String> selectedValue = se.getSelectedItem();
String value = selectedValue.getValue();
System.err.println("Selected Value ---> " + selectedValue.getValue());
if (value != null && !value.equals("---New---") ){
userName.clear();
hostName.clear();
password.clear();
userName.setValue(systemDetailsMap.get(value + "_USER_NAME").toString());
hostName.setValue(systemDetailsMap.get(value + "_HOST_NAME").toString());
password.setValue(systemDetailsMap.get(value + "_PASSWORD").toString());
}
}
};
return ReportListener;
}
Please help me. Thanks in advance.
I am not using Ext-gwt just the standard ext-js, but I think I know what you need! You should define a display and value field.
Ext.create('Ext.form.ComboBox', {
store: xyz,
queryMode: 'local',
displayField: 'name',
valueField: 'id',
renderTo: Ext.getBody()
});
You just have to make sure, that the duplicated items are getting unique id. I think that if this is possible in ext-js it should also be possible in ext-gwt!

"arg 1 could not unmarshal" during JSON-RPC call

I have the unenviable task of editing a 2000 line javascript file inorder to maintain and add some new feature to a web app written in JSP, Json-RPC, jQuery and Java. I do not possess any deeper knowledge of jQuery and Json-RPC except basic Javascript knowledge and the original developer is not there anymore.
There is a JS function which accepts a few params, and calls a Json-RPC and here I am getting the error
arg 1 could not unmarshal
Can someone please tell me what this error means?
Here is my code
function distributeQuantityNew(pReportId, pDecimalPlaces, pRun) {
try {
alert('distributeQuantityNew: ' + pReportId + ', ' + pDecimalPlaces + ', ' + pRun);
var fieldValue = $("#distribution_quantity_" + pReportId).val();
if (fieldValue.length == 0) {
showErrorDialog(resourceBundleMap["error.no.distribution.quantity"]);
return;
} else {
$("#distribution_quantity_" + pReportId).val("");
}
var affectedRowIds = [];
var rows = $("#tableBody_" + pReportId + " tr:visible").has("input[type=text]").filter(function(index) {
var voucherType = this.cells[getVoucherColumnIndex()].innerHTML;
if ((voucherType == 'TRANSFER_CS') || (voucherType == 'PAYOUT_CS') || (voucherType == 'SOURCE_BON') || (voucherType == 'PAYOUT_BON')) {
return false;
}
affectedRowIds.push(parseInt(this.id.split("_")[3]));
return true;
}
);
var affectedReportRows = $.extend(true, {}, foreignReportMap[pReportId]);
$.each(affectedReportRows.map, function(i, row) {
if ($.inArray(row.partnerReportBillNr, affectedRowIds) == -1) {
delete affectedReportRows.map["row_" + row.partnerReportBillNr];
}
});
var report = getLoadedReportByRunId(pReportId);
var productType = report.partnerProductType;
SessionManager.extend();
var resultRows = jsonrpc.foreignReportObject.distributeQuantity(affectedReportRows, fieldValue, pDecimalPlaces, pRun);
alert('back after RPC');
$.each(resultRows.map, function(i, row) {
foreignReportMap[pReportId].map["row_" + row.partnerReportBillNr] = row;
updateForeignReportRow(row, true, productType);
});
updateSummaryRow(pReportId);
toggleApproveAllLink(pReportId);
sortForeignReportTable(pReportId, true);
} catch (e) {
handleError("Failed to distribute quantity: ", e);
}
}
I have peppered it with alerts so that I know whether RPC call was succesful, but I get the error arg 1 could not unmarshal before that from the catch block. Thanks for any hints
OK, got it solved. The first parameter to the remote function is expecting a list of Map<String, SomeBO>. SomeBO is a bean with several BigDecimals. I had another JS function which had set the values passed into the Map. This function was setting a BigNumber where I had a setter of String only. I wish the error I had gotten back from JSON unmarshaller was a bit more descriptive...Below is the code where I added .toString() to solve the issue
foreignReportMap[pReportId].map["row_" + pRowId].clientQuantity = clientQuantity.toString();
foreignReportMap[pReportId].map["row_" + pRowId].totalClientQuantity = totalClientQuantity.toString();

Getting the metadata of columns from SOQL Query

I have a simple SOQL query in java for extracting Salesforce standard object as follows -
String soqlQuery = "SELECT FirstName, LastName FROM Contact";
QueryResult qr = connection.query(soqlQuery);
I want to get the datatype of the object fields.
I have written a small function below which will provide the list of Phone fields and its label present in a Custom or Standard Object of your Salesforce ORG. I hope this might help you in writing the business logic for your code.
public list<String> getFieldsForSelectedObject(){
selectedPhoneNumber = ''; //to reset home number field
list<String> fieldsName = new list<String>();
selectedObject = 'Object Name' // This should have the object name for which we want to get the fields type
schemaMap = Schema.getGlobalDescribe(); //Populating the schema map
try{
if(selectedObject != null || selectedObject != '' || selectedObject != '--Select Object--'){
Map<String, Schema.SObjectField> fieldMap = schemaMap.get(selectedObject).getDescribe().fields.getMap();
for(Schema.SObjectField sfield : fieldMap.Values()){
schema.describefieldresult dfield = sfield.getDescribe();
schema.Displaytype disfield= dfield.getType();
system.debug('#######' + dfield );
if(dfield.getType() == Schema.displayType.Phone){// Over here I am trying to findout all the PHONE Type fields in the object(Both Custom/Standard)
fieldsName.add('Name:'+dfield.getName() +' Label:'+ dfield.getLabel ());
}
}
}
}catch(Exception ex){
apexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'There is no Phone or Fax Field Exist for selected Object!'));
}
return fieldsName;
}
Sample OUTPUT List of String::
Name: Home_Phone__c Label: Home Phone
Name: Office_Phone__c Label: Office Phone
Say that we have the below soql.
select FirstName,LastName from Contact limit 2
The query result in the QueryResult object looks like below.
{
[2]XmlObject
{
name={urn:partner.soap.sforce.com}records, value=null, children=
[
XmlObject{name={urn:sobject.partner.soap.sforce.com}type, value=Contact, children=[]},
XmlObject{name={urn:sobject.partner.soap.sforce.com}Id, value=null, children=[]},
XmlObject{name={urn:sobject.partner.soap.sforce.com}FirstName, value=Bill, children=[]},
XmlObject{name={urn:sobject.partner.soap.sforce.com}LastName, value=Gates, children=[]}
]
},
XmlObject
{
name={urn:partner.soap.sforce.com}records, value=null, children=
[
XmlObject{name={urn:sobject.partner.soap.sforce.com}type, value=Contact, children=[]},
XmlObject{name={urn:sobject.partner.soap.sforce.com}Id, value=null, children=[]},
XmlObject{name={urn:sobject.partner.soap.sforce.com}FirstName, value=Alan, children=[]},
XmlObject{name={urn:sobject.partner.soap.sforce.com}LastName, value=Donald, children=[]}
]
},
}
In order to parse the QueryResult and to take column names, I have implemented the below method that will return the column names in comma separated String. I have mentioned the logic inside the code.
public String getColumnNames(QueryResult soqlResponse)
{
String columns = ""
try
{
// We are looping inorder to pick the 1st record from the QueryResult
for (SObject record : soqlResponse.getRecords())
{
Iterator<XmlObject> xmlList = record.getChildren();
int counterXml = 0;
while(xmlList.hasNext())
{
XmlObject xObj = xmlList.next();
// Since the 1st 2 nodes contains metadata of some other information, we are starting from the 3rd node only
if(counterXml > 1)
{
columns += xObj.getName().getLocalPart() + ",";
}
counterXml++;
}
// Since we can get the column names from the 1st record, we are breaking the loop after the data of 1st record is read
break;
}
// We are removing the last comma in the string
columns = columns.substring(0, columns.length() - 1);
}
catch(Exception ex)
{
}
return columns;
}

Categories

Resources