Currently working with Coldfusion 10 and cfsearch.
After many hours of trial and error, I have managed to get cfindex to collect all my custom field data so that it is available to me as fields for the output on my search results page.
My only issue now, is that the search will be able to search for things like true / false strings and it will return in the search results.
I could run a QoQ to strip those out, im just wondering if anyone has any suggestions for adding fields to an index but not having them searchable.
Any ideas greatly appreciated
my current code is below
<cftry>
<!-- create new searchable collection -->
<!--- cfcollection action= "create" collection="testsearch" path= "#expandPath('/assets/scripts/server/solr/')#" ---->
<cfcollection action= "list" name="collectionlist">
<cfdump var="#collectionlist#">
<cfquery name="MyQuery" datasource="#request.DSN#" maxrows="10">
SELECT *
FROM Store_products
</cfquery>
<cfdump var="#myQuery#">
<cfset myAttr = structNew()>
<cfset variables.columns = "COST,CREATEDDATE,CUSTOM_MESSAGE,CUSTOM_MESSAGE_LENGTH,DISPLAYNAME,DONTINCLUDEINSTOCKUPDATE,FEATUREDPRODUCT,FINALDAYS,FREEDELIVERY,HEIGHT,HTMLMETADESCRIPTION,HTMLMETAKEYWORDS,IMAGE1,IMAGE10,IMAGE2,IMAGE3,IMAGE4,IMAGE5,IMAGE6,IMAGE7,IMAGE8,IMAGE9,ISBUNDLE,ISNEWPRODUCT,ISONLINE,ISONSALE,ISSILENT,LONGDESCRIPTION,MANUFACTURER,NOVOUCHERS,ONLINEEXCLUSIVE,PARTNUMBER,PRICE,PRICELEVEL1,PRICELEVEL10,PRICELEVEL11,PRICELEVEL12,PRICELEVEL13,PRICELEVEL14,PRICELEVEL15,PRICELEVEL2,PRICELEVEL3,PRICELEVEL4,PRICELEVEL5,PRICELEVEL6,PRICELEVEL7,PRICELEVEL8,PRICELEVEL9,PRODUCTCATEGORY,PRODUCTCOLOR,PRODUCTMATERIAL,PRODUCTNAME,PRODUCTSIZE,PRODUCTSTYLE,PRODUCTTITLE,PRODUCTVIEWS,RRP,SALEEND,SALEPRICE,SALESTART,SHORTDESCRIPTION,SOLDOUT,STOCKQUANTITY,STORESORTORDER,TAXEXEMPT,VOLUME,WEIGHT,WIDTH">
<cfloop from="1" to="#ListLen(variables.columns,',')#" index="idx">
<cfset myAttr[listGetAt(variables.columns,idx,',') & "_s"] = listGetAt(variables.columns,idx,',') >
</cfloop>
<cfindex attributecollection="#myAttr#" action="update" collection="testsearch" type="custom" body="DISPLAYNAME,HTMLMETADESCRIPTION,HTMLMETAKEYWORDS,LONGDESCRIPTION,MANUFACTURER,PARTNUMBER,PRODUCTNAME,PRODUCTTITLE,RRP,SHORTDESCRIPTION" query="MyQuery" key= "productname">
<cfsearch name="searchResults" collection="testsearch" criteria="false" >
<cfdump var="#searchResults#">
<cfcatch type="any">
<cfdump var="#cfcatch#">
</cfcatch>
</cftry>
Related
I am downloading data from an API from one of our vendors. The data is an array but some of the fields are empty and come over as undefined. I am able to get most of the information out with a loop but when I add the field "notes" it fails with the error of:
"Element notes is undefined in a CFML structure referenced as part of an expression. The specific sequence of files included or processed is:
C:\websites\Fire\Reports\xml_parse\Crewsense_payroll_loop.cfm, line:
21 "
When I look at the dump I see that the field shows as "undefined". I've run out of ideas. Any help would be greatly appreciated. I've included the entire code and a link to the dump showing the array.
<cfhttp url="https://api.crewsense.com/v1/payroll? access_token=as;lkdfj;alskdfj;laksdfj&token_type=bearer&start=2019-01-05%2019:00:00&end=2019-01-06%2007:59:00" method="GET" resolveurl="YES" result="result">
</cfhttp>
<cfoutput>
<cfset ApiData = deserializeJSON(result.filecontent)>
<cfset API_ArrayLength = arraylen(ApiData)>
<cfloop index="i" from="1" to=#API_ArrayLength#>
#i# #ApiData[i]["name"]#
#ApiData[i]["employee_id"]#
#ApiData[i]["start"]#
#ApiData[i]["end"]#
#ApiData[i]["total_hours"]#
#ApiData[i]["work_type"]#
#ApiData[i]["work_code"]#
#ApiData[i]["user_id"]#
#ApiData[i]["notes"]# <---Fails here when added--->
<cfset i = i+1>
<br>
</cfloop>
<cfdump var="#ApiData#">
</cfoutput>
Dump
When dealing with data structures that have optional elements you will need to check for their existence before trying to access them. Otherwise you will get that error. I have added a snippet with an if condition utilizing the structKeyExists() function to your code as an example.
<cfhttp url="https://api.crewsense.com/v1/payroll? access_token=as;lkdfj;alskdfj;laksdfj&token_type=bearer&start=2019-01-05%2019:00:00&end=2019-01-06%2007:59:00" method="GET" resolveurl="YES" result="result">
</cfhttp>
<cfoutput>
<cfset ApiData = deserializeJSON(result.filecontent)>
<cfset API_ArrayLength = arraylen(ApiData)>
<cfloop index="i" from="1" to=#API_ArrayLength#>
#i# #ApiData[i]["name"]#
#ApiData[i]["employee_id"]#
#ApiData[i]["start"]#
#ApiData[i]["end"]#
#ApiData[i]["total_hours"]#
#ApiData[i]["work_type"]#
#ApiData[i]["work_code"]#
#ApiData[i]["user_id"]#
<cfif structKeyExists(ApiData[i],"notes")>
#ApiData[i]["notes"]# <!--- Show 'notes' if it exists --->
<cfelse>
'notes' is not available <!--- Do something here (or not) --->
</cfif>
<cfset i = i+1>
<br>
</cfloop>
<cfdump var="#ApiData#">
</cfoutput>
Let's say I have a string that is as follows:
position":1,"type":"row","answer_id":"9541943203"},{"text":"Creating a report or view","visible":true,"position":2,"type":"row","answer_id":"9541943204"},{"text":"Editing a report or view","visible":true,"position":3,"type":"row","answer_id":"9541943205"},{"text":"Saving a report or view","visible":true,"position":4,"type":"row","answer_id":"9541943206"},
How can I get the values of every answer_id?
I know the value I want is always preceded by "answer_id":" and it's always followed by "},.
How do I compile a list of those values?
e.g. 9541943203, 9541943204, 9541943205, 9541943206
Dump of deserialized JSON:
You can work with JSON in ColdFusion (almost) the same way you do in Javascript.
<!--- your JSON string here --->
<cfset sourceString = '{ "data": { ... } }'>
<!--- we will add all answer_id to this array --->
<cfset arrayOfAnswerIDs = []>
<!--- in case there went something wrong, we will store the reason in this variable --->
<cfset errorMessage = "">
<cftry>
<!--- deserialize the JSON to work with for ColdFusion --->
<cfset sourceJSON = deserializeJSON(sourceString)>
<!--- validate the structure of the JSON (expected keys, expected types) --->
<cfif (
structKeyExists(sourceJSON, "data") and
isStruct(sourceJSON["data"]) and
structKeyExists(sourceJSON["data"], "pages") and
isArray(sourceJSON["data"]["pages"])
)>
<!--- iterate pages --->
<cfloop array="#sourceJSON["data"]["pages"]#" index="page">
<!--- skip pages that do not contain questions --->
<cfif (
(not isStruct(page)) or
(not structKeyExists(page, "questions")) or
(not isArray(page["questions"]))
)>
<cfcontinue>
</cfif>
<!--- iterate questions --->
<cfloop array="#page["questions"]#" index="question">
<!--- skip questions that do not have answers --->
<cfif (
(not isStruct(question)) or
(not structKeyExists(question, "answers")) or
(not isArray(question["answers"]))
)>
<cfcontinue>
</cfif>
<!--- iterate answers --->
<cfloop array="#question["answers"]#" index="answer">
<!--- skip invalid answer objects --->
<cfif not isStruct(answer)>
<cfcontinue>
</cfif>
<!--- fetch the answer_id --->
<cfif (
structKeyExists(answer, "answer_id") and
isSimpleValue(answer["answer_id"])
)>
<!--- add the answer_id to the array --->
<cfset arrayOfAnswerIDs.add(
answer["answer_id"]
)>
</cfif>
</cfloop>
</cfloop>
</cfloop>
<cfelse>
<cfset errorMessage = "Pages missing or invalid in JSON.">
</cfif>
<cfcatch type="Application">
<cfset errorMessage = "Failed to deserialize JSON.">
</cfcatch>
</cftry>
<!--- show result in HTML --->
<cfoutput>
<!--- display error if any occured --->
<cfif len(errorMessage)>
<p>
#errorMessage#
</p>
</cfif>
<p>
Found #arrayLen(arrayOfAnswerIDs)# answers with an ID.
</p>
<ol>
<cfloop array="#arrayOfAnswerIDs#" index="answer_id">
<li>
#encodeForHtml(answer_id)#
</li>
</cfloop>
</ol>
</cfoutput>
You might want to track all unexpected skips during the processing, so consider having an array of errors instead of a single string.
If you want the answer_id in a list, use
arrayToList(arrayOfAnswerIDs, ",")
I am using CFLDAP to have users get authenticated using active directory. I am trying to write an if statement in case the users information does not come back as authenticated. I thought I could check by using <cfif AuthenticateUser.RecordCount gt 0> which is working as long as the information is correct but if the wrong information is entered and nothing is authenticated it is not running the else statement. Any help with this would be greatly appreciated!
<cfldap action="query"
name="AuthenticateUser"
attributes="dn,mail,givenname,sn,samaccountname,memberof"
start="DC=domain,DC=net"
filter="(&(objectclass=user)(samAccountName=#trim(form.user_name)#))"
server="servername"
Port="389"
username="tc\#trim(form.user_name)#"
password="#trim(form.user_pass)#">
<cfoutput>#AuthenticateUser.RecordCount#</cfoutput>
<!--- Get all records from the database that match this users credentials --->
<cfquery name="userVerify" datasource="test">
SELECT *
FROM dbo.Users
WHERE user_name = <cfqueryparam value="#AuthenticateUser.samaccountname#" cfsqltype="cf_sql_varchar" />
</cfquery>
<cfif AuthenticateUser.RecordCount gt 0>
<!--- This user has logged in correctly, change the value of the session.allowin value --->
<cfset session.allowin = "True" />
<cfset session.employee_number = userVerify.employee_number />
<!--- Now welcome user and redirect to "index.html" --->
<script>
self.location="../dashboard/dashboard.cfm";
</script>
<cfelse>
<!--- this user did not log in correctly, alert and redirect to the login page --->
<script>
alert("Your credentials could not be verified, please try again!");
self.location="Javascript:history.go(-1)";
</script>
</cfif>
I have also tried: <cfif len(AuthenticateUser)>
This is how I do it. I try to run a query against our domain using the supplied username and password. If the supplied username and password are not valid, an error is generated.
<cftry>
<cfldap action="Query"
name="ADResult"
attributes="dn"
start="DC=domain,DC=net"
filter="sAMAccountName=administrator"
server="servername"
scope = "subtree"
username="#arguments.username#"
password="#arguments.password#" />
<cfset isAuthenticated = true />
<cfcatch type="any">
<cfset isAuthenticated = false />
</cfcatch>
</cftry>
<cfreturn isAuthenticated />
I wrap this up in a function called "authenticate" and expose it via a web service that I call from my apps. If I then need additional details about the user (mail, givenName, etc), I have another function in the same web service that I will call after I am sure the user has been authenticated. Note that in this other function I'm using my administrator username and password to run the query.
<cfldap action="Query"
name="ADResult"
attributes="mail,givenName"
start="DC=domain,DC=net"
filter="sAMAccountName=#arguments.username#"
server="servername"
scope = "subtree"
username="administrator"
password="myAdminPassword" />
I take the results of this, populate a query object or a structure, and return that to the calling function.
So the entire process sort of looks like this:
<cfset objAD = createobject("webservice", "http://mywebservice.com") />
<cfset isAuthenticated = objAD.authenticate(form.username, form.password) />
<cfif isAuthenticated>
<cfset userDetails = objAD.getUserDetails(form.username)>
</cfif>
Hope this helps.
This is a formatted comment. You are trying to do too much at once. Go one step at a time. Start with this:
<cfdump var="before cfldap tag<br />">
<cfldap action="query"
name="AuthenticateUser"
etc
>
<cfdump var="after cfldap tag<br />">
<cfdump var = "#AuthenticateUser#">
<cfdump var="after cfdump<br />">
Run this code with both valid and not valid credentials. Look at what you get. React accordingly.
I think it throws an error when the query fails. Try this:
<cftry>
<cfldap action="query"
name="AuthenticateUser"
attributes="dn,mail,givenname,sn,samaccountname,memberof"
start="DC=domain,DC=net"
filter="(&(objectclass=user)(samAccountName=#trim(form.user_name)#))"
server="servername"
Port="389"
username="tc\#trim(form.user_name)#"
password="#trim(form.user_pass)#">
<cfset LoginStatus = "Success">
<cfcatch type="any">
<cfset LoginStatus = "Failed">
</cfcatch>
</cftry>
Then your cfif would be something like this:
<cfif LoginStatus eq "Success">
<!--- This user has logged in correctly, change the value of the session.allowin value --->
<cfset session.allowin = "True" />
<cfset session.employee_number = userVerify.employee_number />
<!--- Now welcome user and redirect to "index.html" --->
<script>
self.location="../dashboard/dashboard.cfm";
</script>
<cfelse>
<!--- this user did not log in correctly, alert and redirect to the login page --->
<script>
alert("Your credentials could not be verified, please try again!");
self.location="Javascript:history.go(-1)";
</script>
</cfif>
I think this works on CF9.
I have a CFC object and a function which gets me the data which I want. Now I want to use that data and provide it to an already defined custom tag attribute. When I dump the #iEngine.listScore()# I get some parameters. But my problem is how should I provide those to an attribute?
<cfdump var="#iEngine.listScores()#" label="Swapnil Test - Function ListScore">
<cfset filename="ACE_DataExtract_#DateFormat(now(),'dd.mmm.yyyy')#.xls" />
<!--- Calling Custom tags to create/output xls files --->
<cfmodule template="#request.library.customtags.virtualpath#excel.cfm" file="#filename#" sheetname="ACE Report">
<cfmodule template="#request.library.customtags.virtualpath#exceldata.cfm"
query="#iEngine.listScores()#"
action="AddWorksheet"
sheetname="ACE Report"
colorscheme="blue"
useheaders="true"
contentformat="#{bold=true}#"
customheaders="#ListScore#">
<cfoutput>Excel Extract - ACE Report - #DateFormat(Now(),"d-mmm-yyyy")#</cfoutput>
</cfmodule>
</cfmodule>
Here I want to provide the data of iEngine.listScore() to the "Query" attribute in "exceldata" custom tag.
Below is the dump of iEngine.listScore()
I would write a transform Data function to change your array-struct to a query object, then pass that on....
<cffunction name="transformData" result="query">
<cfargument name="inArray" type="array">
<cfset local.qryReturn = queryNew("actiondate,actionId,closedate")>
<!--- You may look up queryNew and also set your dataTypes --->
<cfloop array="#arguments.inArray#" index="i">
<cfset QueryAddRow(local.qryReturn)>
<cfset querySetCell(local.qryReturn,"actionDate",i["actiondate"])>
<cfset querySetCell(local.qryReturn,"actionid",i["actionid"])>
<cfset querySetCell(local.qryReturn,"closedate",i["closedate"])>
</cfloop>
<cfreturn local.qryReturn>
</cffunction>
<cfset test = [
{actiondate='1/1/2015',actionid=134,closedate=''},
{actiondate='1/2/2015',actionid=135,closedate=''},
{actiondate='1/3/2015',actionid=136,closedate=''}
]>
<cfdump var="#test#">
<cfset resultQry = transformData(test)>
<cfif NOT isquery(resultQry)>
Exit invalid Data.
<cfelse>
<cfdump var="#resultQry#">
</cfif>
I have a form where I can upload logos a plenty. I'm validating files (empty form fields, wrong extension, ...) inside a cftry/cfcatch statement.
When I find an error in the cftry, I do this:
<cfthrow type="FileNotFound" message="#tx_settings_app_error_create_first#" />
and inside my 'cfcatch'
<cfcatch>
<cfoutput><script type="text/javascript">window.onload = function(){alert("#cfcatch.message#");window.location.href="hs_apps.cfm"; } </script></cfoutput>
</cfcatch>
This works fine, catches all errors and alerts the user what is wrong.
Now I wanted to use the same handler on a database call where I'm checking for duplicate username. Still the same:
<cfquery datasource="#Session.datasource#" name="duplicates">
SELECT a.app_alias
FROM apps AS a
WHERE a.iln = <cfqueryparam value = "#Session.loginID#" cfsqltype="cf_sql_varchar" maxlength="13">
AND a.app_alias = <cfqueryparam value = "#form.app_basic_alias#" cfsqltype="cf_sql_varchar" maxlength="50">
</cfquery>
<cfif duplicates.recordcount GT 0>
<cfthrow type="FileNotFound" message="#tx_settings_apps_error_dup#" />
</cfif>
The cfcatch is also the same.
However. This now procudes a server error page and I'm thrown out of the application.
Question:
Any idea, why I'm struggling to get cftry/cfcatch to work here? I'm clueless.
Thanks!
EDIT:
Here is the full code
<cfif isDefined("send_basic")>
<cfset variables.timestamp = now()>
<cfset variables.orderview = "1">
<cfif form.send_basic_type EQ "new">
<cftry>
<cfif module_check.recordcount GT 0>
<cfloop query="module_check">
<cfif module_check.module_name EQ "preorder">
<cfset variables.module_name = module_check.module_name>
<cfset variables.b2b_preord_ok = "true">
</cfif>
</cfloop>
<cfif form.app_basic_orderview EQ "preo">
<cfset variables.orderview = "0">
</cfif>
</cfif>
<!--- PROBLEM HERE: DUPLICATES --->
<cfquery datasource="#Session.datasource#" name="duplicates">
SELECT a.app_alias
FROM apps AS a
WHERE a.iln = <cfqueryparam value = "#Session.loginID#" cfsqltype="cf_sql_varchar" maxlength="13">
AND a.app_alias = <cfqueryparam value = "#form.app_basic_alias#" cfsqltype="cf_sql_varchar" maxlength="50">
</cfquery>
<cfif duplicates.recordcount GT 0>
<cfthrow type="FileNotFound" message="#tx_settings_apps_error_dup#" />
</cfif>
<!--- IF PASS, CREATE/UPDATE --->
<cfquery datasource="#Session.datasource#">
INSERT INTO apps ( ... )
VALUES( ... )
</cfquery>
<cfset variables.app_action = "Applikation erstellt">
<!--- success --->
<cfoutput><script type="text/javascript">window.onload = function(){alert("#tx_settings_app_cfm_create#");}</script></cfoutput>
<cfcatch>
<cfoutput><script type="text/javascript">window.onload = function(){alert("#tx_settings_app_err_create#");}</script></cfoutput>
</cfcatch>
</cftry>
<cfelse>
<cftry>
<!--- UPDATE --->
<cfquery datasource="#Session.datasource#">
UPDATE apps
SET ... = ...
</cfquery>
<cfset variables.app_action = "Applikation aktualisiert">
<!--- success --->
<cfoutput><script type="text/javascript">window.onload = function(){alert("#tx_settings_app_cfm_update#");}</script></cfoutput>
<cfcatch>
<cfoutput><script type="text/javascript">window.onload = function(){alert("#tx_settings_app_err_update#");}</script></cfoutput>
</cfcatch>
</cftry>
</cfif>
</cfif>
The error message I'm getting it the message I specify =
<cfthrow type="FileNotFound" message="#tx_settings_apps_error_dup#" />
Which if caught should alert the text behind tx_settings_apps_error_dup. If I dump the cfcatch, cfcatch.message is my specified text, so the error gets caught allright, only I get a server error page vs. an alert. I'm using exactly the same handler for fileuploads and form submits. I don't get why it's not working here?
Thanks for helping out!
WORKAROUD:
Note nice, but suffice(s):
<cfif dups.recordcount NEQ 0>
<cfoutput><script type="text/javascript">window.onload = function(){alert("#tx_settings_apps_error_dup#"); location.href = "hs_apps_detail.cfm?create=newApp&id=none";}</script
</cfoutput>
<cfabort>
</cfif>
So when a duplicate is found I alert the user, reload the exact same page and cfabort to prevent the old page from processing further. Patch that is.
(moved this down from being just a comment)
OK, so the catch is definitely catching the exception if you're able to dump it, so it's not that the try/catch ain't working, it's something else. Bear in mind that processing will continue until the end of the request after your catch block, and only then will the output buffer be flushed, and your alert() sent to the browser. It sounds to me like after your output the alert, and processing continues, some OTHER error is occurring which is causing the server's error page to display. I recommend getting rid of the error page temporarily and eyeballing the actual error CF is raising.
NB: if you want processing to stop immediately in the catch block after you output the alert(), you're going to need to tell CF that, ie: with a <cfabort>. Otherwise, as per above, it'll just keep going.
I think exceptions that are caught by the server error page are still logged in the exception log, but I could be wrong. You could always put an onError() handler in your Application.cfc, log whatever error occurred, then rethrow the error so the error page still deals with it. That way you get the info on the error, and the punter still sees the nice error page.