Thursday, October 31, 2013
Ajax with Double Bind
Here are the requirements I needed to fulfill:
1. Display a select box of categories
2. Based on the category selected, do an autosuggest of institutions
3. Populate a hidden field with the institutionID based on the institution selected in #2.
Ok so here is my first SELECT:
<cfselect name="categoryID"
bind="cfc:ajaxlookup.getInstitutionCategories()"
bindonload="true" />
It called the getInstitutionCategories function in the ajaxlookup CFC.
Here is the method:
<cffunction name="getInstitutionCategories" access="remote" returnType="array">
<!--- Define variables --->
<cfset var data="">
<cfset var result=ArrayNew(2)>
<cfset var i=0>
<!--- Get data --->
<cfquery name="data" datasource="#request.dsn#">
SELECT strInstitutionCategory, intInstitutionCateogryNumber
FROM tblInstitutionCategories
where intInstitutionCateogryNumber IN (2,3,1,6,7,8,9)
ORDER BY strInstitutionCategory
</cfquery>
<!--- Convert results to array --->
<cfloop index="i" from="1" to="#data.RecordCount#">
<cfset result[i][1]=data.intInstitutionCateogryNumber[i]>
<cfset result[i][2]=data.strInstitutionCategory[i]>
</cfloop>
<!--- And return it --->
<cfreturn result>
</cffunction>
When the user selects the category, I take the category ID and search for institutions in that category using a call to the getInstitutions method in ajaxlookup CFC.
<cfinput type="text" name="institution"
autosuggest="cfc:ajaxlookup.getInstitutions({cfautosuggestvalue},{categoryID})" value="#form.institution#" size="60" showAutoSuggestLoadingIcon="false">
As you can see, two values are passed to the function: the value typed, and the category ID that the user selected in the first drop down.
Here is the getInstitutions function:
<cffunction access="remote" name="getInstitutions" output="false" returntype="array">
<cfargument name="search" type="any" required="true" default="">
<cfargument name="catID" type="numeric" required="true">
<!--- Define variables --->
<cfset var result=ArrayNew(1)>
<!--- Do search --->
<cfquery datasource="#request.dsn#" name="data">
SELECT strInstitutionName
FROM tblInstitutions
WHERE intInstitutionCategoryID = #catID#
AND strInstitutionName LIKE '#search#%'
ORDER BY strInstitutionName
</cfquery>
<!--- Build result array --->
<cfloop query="data">
<cfset ArrayAppend(result, strInstitutionName)>
</cfloop>
<!--- And return it --->
<cfreturn result>
</cffunction>
And for step 3, I want to populate a hidden field with the institutionID of the institution the user selected in step 2:
<cfinput type="hidden" name="institutionID" id="institutionID" bind="cfc:ajaxlookup.getInstitutionIDs({institution})">
It simply passes the institution name to the getInstitutionIDs function with a bind.
Here is the getInstitutionIDs function:
<cffunction access="remote" name="getInstitutionIDs" output="false" returntype="array">
<cfargument name="institution" type="string" required="true">
<!--- Define variables --->
<cfset var result=ArrayNew(1)>
<!--- Do search --->
<cfquery datasource="#request.dsn#" name="data">
SELECT intInstitutionID
FROM tblInstitutions
WHERE strInstitutionName = <cfqueryparam value="#institution#" cfsqltype="CF_SQL_VARCHAR">
</cfquery>
<!--- Build result array --->
<cfloop query="data">
<cfset ArrayAppend(result, intInstitutionID)>
</cfloop>
<!--- And return it --->
<cfreturn result>
</cffunction>
Enjoy!
Bind data to an input field via autosuggest using data from another input field.
<cfinput type="text"
name="country" value="#form.country#" validateat="onSubmit" size="60" showAutoSuggestLoadingIcon="false"
autosuggest="cfc:ajaxlookup.getCountries({cfautosuggestvalue})">
This is a simple CF autosuggest. It calls the getCountries function in the ajaxlookup cfc. The CFC is in the same directory as my file. I don't know if you have to do this but it just works better for me. :)
This call will suggest countries as the person types the name of the country.
(showAutoSuggestLoadingIcon="false" means that little loading icon won't show.)
Here is the getCountries function:
<!--- Country Lookup used for auto suggest --->
<cffunction access="remote" name="getCountries" output="yes" returntype="array">
<cfargument name="search" type="any" required="false" default="">
<!--- Define variables --->
<cfset var data="">
<cfset var result=ArrayNew(1)>
<!--- Do search --->
<cfquery datasource="#request.dsn#" name="data">
SELECT strCountry
FROM tblCountries
WHERE strCountry LIKE '#arguments.search#%'
ORDER BY strCountry
</cfquery>
<!--- Build result array --->
<cfloop query="data">
<cfset ArrayAppend(result, strCountry)>
</cfloop>
<!--- And return it --->
<cfreturn result>
</cffunction>
So I want to send the country ID to the database, not the country name. So I am going to retrieve the country ID based on the country that the user selected in the above input.
Here is my 2nd input:
<cfinput type="hidden" name="countryID" id="countryID" bind="cfc:ajaxlookup.getCountryID({country})">
It uses the bind attribute to call the getCountry method while passing in the value of the country input.
Enjoy!
Wednesday, October 17, 2012
Customized CKEditor ToolBars Based on User Roles
Here's how to display a different toolbar set based on user roles.
So I have two roles within my CMS - a super editor and a basic editor. The super editor sees the advance toolbar and the basic, sees the basic.
In my config.js files, I define my toolbars:
Here is my basic tool bar (Basic Editor Access):
config.toolbar_Basic =
[
['Bold', 'Italic', '-', 'NumberedList', 'BulletedList', '-', 'Link', 'Unlink','-','About']
];
};
Here is my FULL tool bar (Super Editor Access):
config.toolbar_Full =
[
{ name: 'document', items : [ 'Source','-','Save','NewPage','DocProps','Preview','Print','-','Templates' ] },
{ name: 'clipboard', items : [ 'Cut','Copy','Paste','PasteText','PasteFromWord','-','Undo','Redo' ] },
{ name: 'editing', items : [ 'Find','Replace','-','SelectAll','-','SpellChecker', 'Scayt' ] },
//{ name: 'forms', items : [ 'Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton',
// 'HiddenField' ] },
'/',
{ name: 'basicstyles', items : [ 'Bold','Italic','Underline','Strike','Subscript','Superscript','-','RemoveFormat' ] },
{ name: 'paragraph', items : [ 'NumberedList','BulletedList','-','Outdent','Indent','-','Blockquote','CreateDiv',
'-','JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock','-','BidiLtr','BidiRtl' ] },
{ name: 'links', items : [ 'Link','Unlink','Anchor' ] },
//{ name: 'insert', items : [ 'Image','Flash','Table','HorizontalRule','Smiley','SpecialChar','PageBreak','Iframe' ] },
'/',
{ name: 'styles', items : [ 'Styles','Format','Font','FontSize' ] },
{ name: 'colors', items : [ 'TextColor','BGColor' ] },
{ name: 'tools', items : [ 'Maximize', 'ShowBlocks','-','About' ] }
];
Ok so here is my editor reference on the CFM page:
My textarea field
<textarea id="englishText" class="ckeditor" name="englishText">#englishText#</textarea>
Code to show the different toolbars:
<cfif session.user.roleID EQ 1>
<script type="text/javascript"> // <![CDATA[
CKEDITOR.replace( 'englishText', { toolbar : 'Full' });
// ]]>
</script>
<cfelse>
<script type="text/javascript"> // <![CDATA[
CKEDITOR.replace( 'englishText', { toolbar : 'Basic' });
// ]]>
</script>
</cfif>
I want to make a few notes about this code:
1. Notice I did not add the toolbar attribute to the textarea field
2. Notice I added the code UNDER the textarea field. For some reason that I don't know about and had to learn the HARD WAY (GRRRR....) the code has to go after the textarea.
Enjoy! :)
Tuesday, October 16, 2012
What to use instead of the evaluate function
Well that's fine and dandy but if you do a search on this NO ONE gives you an alternative!!! (AUGH!!)
Well I have been using one - I can't credit it because I forgot where I found it.
Here goes:
Instead of this:
<cfset response= evaluate("form.#VarName#")>
Use this:
<cfset response=form["#VarName#"]>
Enjoy!
More examples: 01.13.16
Instead of this: #Evaluate( "#session.languagePreference#SUBSECTION" )#
Use this: <cfset SUBSECTION = content["#session.languagePreference#SUBSECTION"]>
Monday, October 8, 2012
How to protect your Coldfusion tags in CkEditors
First, lets walk through the steps of installing CKEditor
Step 1: Download the files here: http://ckeditor.com/download
Step 2: Follow the installation Instructions here: http://docs.cksource.com/CKEditor_3.x/Developers_Guide/Installation
Step 3: Go to the SAMPLE files (see installation Instructions) and recreate one of the samples as your actual editing form. Make sure the following files are included on your editing form:
<script type="text/javascript" src="ckeditor/ckeditor.js"></script>
<script src="ckeditor/_samples/sample.js" type="text/javascript"></script>
<link href="ckeditor/_samples/sample.css" rel="stylesheet" type="text/css" />
AND this is how to create the actual editor:
<textarea class="ckeditor" toolbar="Basic" name="englishText"></textarea>
Step 4: Here is where the config.js file comes in. You'll want to open the config.js file (it's in the ckeditor root folder) and add the following lines:
config.protectedSource.push( /<\?[\s\S]*?\?>/g );
config.protectedSource.push(/[^<]*(<h1>([^<]+)<\/h1>)/g);
config.protectedSource.push( /<cfscript[\s\S]*?\/cfscript>/g );
config.protectedSource.push( /<br[\s\S]*?\/>/g ); // BR Tags
config.protectedSource.push( /<img[\s\S]*?\/>/g ); // IMG Tags
config.protectedSource.push( /{exp:[\s\S]*?{\/exp:[^\}]+}/g ); // Expression Engine style server side code
config.protectedSource.push( /{.*?}/g);
config.protectedSource.push( /<tex[\s\S]*?\/tex>/g);
config.protectedSource.push( /<object[\s|\S]+?<\/object>/g); // Protects <OBJECT> tags
config.protectedSource.push( /<style[\s\S]*?\/style>/g); // Protects <STYLE> tags
config.protectedSource.push( /<cfoutput[\s\S]*?\/cfoutput>/g); // Protects <CFOUTPUT> tags
config.protectedSource.push( /<pre[\s\S]*?\/pre>/g);
config.protectedSource.push( /<code[\s\S]*?\/code>/g);
config.protectedSource.push( /<cfinclude[\s\S]*?\/cfinclude>/g);
config.protectedSource.push( /<cfloop[\s\S]*?\/cfloop>/g);
config.protectedSource.push( /<cfset[\s\S]*?\/cfset/g);
config.protectedSource.push( /<cf[\s\S]*?>/gi ) ; // ColdFusion cf tags - OPEN.
config.protectedSource.push( /<\/cf[\s\S]*?>/gi ) ; // ColdFusion cf tags - CLOSE.
config.ProtectedTags = 'cfquery|cfif|cfoutput|cfloop' ;
CKEDITOR.on( 'instanceReady', function( ev )
{
ev.editor.dataProcessor.writer.setRules( 'cfoutput',
{
indent : false,
breakBeforeOpen : false,
breakAfterOpen : false,
breakBeforeClose : false,
breakAfterClose : false
});
ev.editor.dataProcessor.writer.setRules( 'cfinvoke',
{
indent : false,
breakBeforeOpen : false,
breakAfterOpen : false,
breakBeforeClose : false,
breakAfterClose : false
});
ev.editor.dataProcessor.writer.setRules( 'cfloop',
{
indent : false,
breakBeforeOpen : false,
breakAfterOpen : false,
breakBeforeClose : false,
breakAfterClose : false
});
ev.editor.dataProcessor.writer.setRules( 'cfinclude',
{
indent : false,
breakBeforeOpen : false,
breakAfterOpen : false,
breakBeforeClose : false,
breakAfterClose : false
});
ev.editor.dataProcessor.writer.setRules( 'p',
{
indent : false,
breakBeforeOpen : false,
breakAfterOpen : false,
breakBeforeClose : false,
breakAfterClose : false
}
);
/*// Output self closing tags the HTML4 and HTML5 way
ev.editor.dataProcessor.writer.selfClosingEnd = '>';*/
}
Now, so far all of my CF tags are protected and it is working fine. If you see that I am missing something, let me know. Also let me know how this works for you.
Saturday, November 5, 2011
Output 2 word columns
One issue I ran into recently was creating reports in excel. The ASP app calls a stored proc which retrieves the columns headers as 2 words i.e. First Name, Last Name. This works properly in ASP but CF does not like two-word values in the output.
So this:
Here is how to solve this issue:
#myquery["First Name"][myquery.currentRow]#
Enjoy!
Friday, November 4, 2011
Customizing JQuery Error Messages
Ok so I went on a wild goose chase to find out how to customize jQuery messages AND place them in a nicer area on the page than the default which is somewhere that doesn't look good.
I had to dig around in Google land but finally pieced together a solution:
Here is my jQuery code snippet:
$(document).ready(function(){
$("#step1").validate({
rules: {
institutionName: "required",
institutionAddress: "required",
institutionCity: "required",
institutionState: "required",
institutionPostalCode: "required",
institutionCountry: "required",
institutionLanguage: "required"
},
messages: {
institutionName: "Please enter the name of your institution",
institutionAddress: "Please enter your institution's address",
institutionCity: "Please enter your institution's city",
institutionState: "You must select a state",
institutionPostalCode: "Please enter your institution's postal code",
institutionCountry: "Please select a country",
institutionLanguage: "Please select a preferred language"
},
// the errorPlacement has to take the table layout into account
errorPlacement: function(error, element) {
if ( element.is(":radio") )
error.appendTo( element.parent().next() );
else if ( element.is(":checkbox") )
error.appendTo( element.parent().next() );
else
error.appendTo( element.parent().next() );
},
});
});
Now let's explain:
1. In the code snippet above, step1 is the NAME of my form.
2. In the RULES piece of the code, these are all of the fields that I would like to be required.
3. the MESSAGES piece is "What do I want the user to see when he/she gets the required alert
4. ERROR PLACEMENT - this places the error message into the NEXT element.
Ok so here is part of my form:
<tr>
<td class="label"> <span class="alerttext4"> *</span>
<label id="institutionName" for="institutionName"> Name of Institution</label> </td>
<td class="field"> <input id="institutionName" size="45" name="institutionName" type="text" value="#form.institutionName#" /> </td>
<td class="status"> </td>
</tr>
See that last little TD that has nothing in it: <td class="status"> </td> - that is where the error message will be displayed. Nice and neatly placed on the right side of the field.
*ALL SMILES*
Let me know how it works out for you!