Words about stuff, and things related to stuff

Persist form values on reload w/ jQuery & ColdFusion

A designer friend presented me with a somewhatlong and complicated HTML form. It is a survey/contest entry for employees of a specific industry, with dozens of fields which include regular text inputs, text areas, and radio buttons.

My task is to create a routine to submit this form via e-mail and store the contents in the database. ColdFusion makes that easy with the built-in #form# scope. And for validation, I simply made his HTML < form > into a <cfform>, and all of the <input> and < textarea > elements into <cfinput> and <cftextarea>, adding 'required="true"' and a validation rule and/or message for each. Whipping up a quick server-side validation for the required fields was also a snap with CF.

Then it occurred to me - if there is in fact some error with the user submission, we will return the user to the form showing an error message at the top of the page.

However, unless we somehow persist the values that were entered, the form will be blank, and the user will no doubt be a little frustrated. This is a long form!

one method would be to create <cfparam> values for each element in the form, and then give each input the a value like value='#form.thisFieldName#" - that's common practice, and works great, but I don't want to do the tedious work. Also, I will be passing this form back to the designer, and don't want him to have to create the default value if he decides to change the names of any inputs, or at other input to the form.

So, I came up with this.

Assuming you already have jQuery in your page, this little block of code will loop through all of the posted values in the ColdFusion form scope, then, using jQuery, will assign the given value to any form element with a matching "name" attribute, allowing us to easily re-populate all the form fields in the page, in one fell swoop with javascript.

Since i only had input / textarea / select / radio button inputs, this just handles those types, but could easily be ammended to include checkboxes and more.

<!--- if form scope exists --->
<cfif isDefined('form.fieldnames')>
    <cfsavecontent variable="hcode">
    <script type="text/javascript">
    <cfloop list="#form.fieldNames#" index="ff">
    <cfset rawVal = form[ff]>
    <cfset ffVal = jsStringFormat(form[ff])>
    //end jQuery
<cfhtmlhead text="#hcode#">

Yes, this makes a big long looped jQuery script in the head of the user's page. But in this instance, it is working perfectly, with no noticeable slowing of page load, or other drawbacks that i can see.

HTML Formatter ColdFusion-friendly code cleanup tool

No matter how clean your code, there's something to be said for a fast, clean pre-launch cleanup with a reliable code formatter . My favorite by far is the HTML Formatter from LogicHammer.com:  http://www.logichammer.com/html-formatter/

Complete with a full set of ColdFusion-friendly options, this simple tool makes cleaning your code a snap. I use it as I'm working, to clean up the work-so-far at any point, and before final launch to make sure the production code will be as easy as possible to maintain and revisit later on. It is a standalone executable, which means there's no installation, and you can put in anywhere you like on your hard drive.

I simply create a taskbar shortcut on my Windows PC and drag the files I want to clean directly from the 'project' view in Eclipse onto the icon - couldn't be faster, simpler or easier. I prefer to have my original files altered, with the originals automatically put in a specified backup location - you can also assign the option to leave the original alone and create a cleaned-up copy.

Among other fav features, HTML Formatter ships with a simple text-based config file which makes it incredibly easy to specify tags to ignore or to indent, and file extensions to be formatted or skipped ( you can run the formatting on specific files, or an entire directory).

For only $14.99 you get all the features and 2 years of updates (there is also an 8.99 version with a basic feature set). The program's developer has answered every question I ask directly and has been very helpful with customizations, even building in some features I requested a while back (for the record - I'm not affiliated with logichammer in any way, just very pleased with this slick little tool).

mySQL str_to_date converts text formatted dates and times to real SQL timestamps

I am working on a site where dates have been stored as text strings in a mySQL database, such as '2009-10-17' , and I need to create a 'search by date' function where a given start and end date can be compared to the date stored in the database. In other words, i need to convert the text-formatted date to a real 'datetime' value , that can be compared with (greater than) and (less than) logic within the query itself.

Like all things CF/mySQL , there are usually multiple ways to get things done. After kicking it around a few different ways, I settled on mySQL's built-in "str_to_date" function as the easiest and most efficient solution.

The str_to_date()  function takes two arguments: the string that is to be converted, and a format string, which uses the same syntax as mysql date_format() and other related mySQL date functions.

Since the dates are entered in 'yyyy-mm-dd' format, my format string is" %Y-%m-%d "
(Note the capital Y which signifies a 4-digit year)

My query now looks something like this - note the second line:

str_to_date(aa.date_published,'%Y-%m-%d') as articleDate,
aa.title, aa.ID,
FROM articles_table ...

This converts the date, 2009-10-17,
to a datetime stamp,
{ts '2009-09-17 00:00:00'},
which can now be used for any type of date comparisons.

To keep things clean, if an article happens to be entered with a different format that does not match our format pattern (i.e. somebody types in '10/17/09'),  str_to_date() will simply return an empty string in that column, rather than throwing an error.

The mySQL specification for this and other functions is here:




New TinyMCE lets you paste as plain text automatically

When building web applications, one of the most common functions involves allowing a site administrator to add or edit content on a page via some sort of 'wysiwyg' (what you see is what you get) editor. My tool of choice for this purpose is the very versatile, relatively light TinyMCE ( tinymce.moxiecode.com)

As great as these tools are, it is inevitable that the average site administrator will want to copy and paste some text from a word processing function like MS Word or WordPerfect, both of which add invisible formatting to the copy-and-pasted text, which in turn can really mess up even the best of web designs.

TinyMCE has had a very nice 'paste from word' plugin for as long as I can remember, but it still requires the user to click a tiny icon for the 'paste from word' popup, and then paste their text into that. ( There is also a 'paste as plain text' option which removes all formatting just as if you'd copied into notepad first, then pasted into the web form). So, even with these great options, I still find myself answering more than a few support calls related to text not looking quite like it should (or worse) when copying from Word.

Much to my delight, I've found a much better solution - the newest version of TinyMCE has the "paste" plugin built in, and it now includes options for cleaning up the text automatically when pasting right into the main text box (without needing to use the littlepopup icons).

As seen on the paste plugin page (TinyMCE:Plugins/paste - Moxiecode Documentation Wiki) you simply need to include 'paste' in the list of plugins when initializing the tinyMCE script, and then can call the cleanup options like this:

            paste_auto_cleanup_on_paste : true,
            paste_remove_styles: true,
            paste_remove_styles_if_webkit: true,
            paste_strip_class_attributes: "all",

This runs the 'paste from word' function automatically, then removes any remaining inline style and class attributes , leaving you with nice clean paragraph-formatted html.

so, whether your clients remember to use that little button or not, whatever they paste (via ctrl+v on their keyboards) will be stripped clean, ready to be shown in pristine valid html format on your site.

How to show changed input and select fields with jQuery

Here are a few quick easy jquery functions that will add a class of 'changed' to any input or select box if it is changed, and will remove that class if the value is reset to the default.

view plain print about
1// inputs
2        $('form.myForm :input').change(function(){
3        var defval = $(this)[0].defaultValue;
4        if ($(this).val()!=defval){
5            $(this).addClass('changed');
6        } else {
7             $(this).removeClass('changed');
8        }
9        }).keyup(function(){
10             $(this).trigger('change');
11        });
13        // select boxes
14        $('form.myForm select').change(function(){
15        var defval = $(this).find('option[defaultSelected=true]').val();
16        if ($(this).val()!=defval){
17            $(this).addClass('changed');
18        } else {
19             $(this).removeClass('changed');
20        }
21        }).keyup(function(){
22             $(this).trigger('change');
23        });

Note in both cases we use keyup (onkeyup) to trigger the 'change' event. This allows the browser to show the changed class as soon as the user changes the value using a keyboard, rather than 'onblur'.

How to find Specific Column Names or Types in a mySQL Database

I'm working on a rather extensive CMS admin application, and need to make some adjustments to all of the "sort" fields in the database. Many of the tables have either a 'sort' or 'sort_order' (and in one case, I think I saw 'SortOrder'), and I need hunt them down, creating a list of column names and table names so i can quickly find the columns I want to edit.

I could open each table one by one, and look for those column names... but of course, there's a much better way:

view plain print about
3WHERE lower(column_name) LIKE '%sort%'
4AND TABLE_SCHEMA='//my database name here//'

This returns a perfectly formatted query of table names and column names, along with the 'data type' for any column containing 'sort' (or 'Sort'). Now it will be a snap to make my changes to all of the numeric sort fields in the entire database.

The query can be modified to return all sorts of useful info, such as all columns in the entire database:

view plain print about
3WHERE TABLE_SCHEMA='//my database name here//'

or all columns with a specific data type

view plain print about
3WHERE TABLE_SCHEMA='//my database name here//'
4AND DATA_TYPE='varchar'

And then, if you wanted to get really lazy, er, creative... you can loop the results of that query, and 'do stuff' to all of the columns automatically with just a few more lines:

view plain print about
1alter table #table_Name# modify #column_name# VARCHAR(55) ;

(this would set the size of your varchar field to 55 characters, for example)

Installing SQL Server 2008 Management Studio Express

I don't do much work on MS SQL, but a recent project requires I connect to a remote SQL 2008 database, so I went looking for the new version of the SQL Server Management Studio Express program which has worked so well, and so simply, for SQL 2005 databases.

Simple enough, right? Not quite. It didn't take me long on Google to realize i was far from the only one having trouble installing just the Management Studio, without the server components. Microsoft has managed to make this process incredibly unintuitive, including links and download pages which don't actually point you to what you think you are getting.
( for examples, see the google link above... i'm being really nice in this post by comparison!)

The best compromise i could find was the official MS download page, which offers a 160+mb file containing the full database server system. Blog posts mention compatibility issues (Win7 did throw up some warnings of its own when i started the process, so i backed out and kept looking), incomplete installations and the need to run the installer twice so you can 'add' the Management Studio as a component to an existing installation.

Huh? Exactly.

So, anyway...  for those that might be in the same plight... I have the solution!

Go here: http://www.microsoft.com/web/Downloads/platform.aspx and install the MS 'Web Platform Installer'.  Then, when the installer loads up, find the little 'customize' link under the "Database" section, where you can tick the boxes for the components you want to install. ( see image )

Once i got it going, this was actually a slick little installer.
(So finally I have SQL 2008 Management Studio ready to go.
Now, what was i going to use it for?)


How to find Duplicate Entries in a mySQL Database

Here's a quick easy query that will return all records where a given column's value appears more than once.

The trick is the 'group by' phrase, combined with the selection of the 'count(*)' value, which simply counts the records found for each match of 'Name'.

This query will return any records where the same value appears more than one time in the given column (in this case, the 'Name' column), along with the 'Counter' value showing how many times the duplicate appears.

view plain print about
1SELECT Name,count(*) as Counter
2FROM Table_Name
4HAVING Counter >

Javascript How To: Add a Number of Days to a Date

I have a form where a user can input a date in the format mm/dd/yyyy, and we need to add an 'expiration date' that is 30 days from the date entered, regardless of calendar month, leap years, or other complex calculations.

Thankfully, javascript already has the 'setDate()' function built in. We just have to parse the date object (a full javascript formatted date string) out of the given form input ( e.g. '11/10/2009').

Easy enough - first we parse out the numeric date/time object, and in this example, write it to the screen.

Then, we add 30 days (the number of days can be changed in the setting for the 'interval' variable - use a negative number to remove days)

Again, this example simply writes the date to the screen. In the current usage, I will use that date value to populate another text input in the same form as the initial date being entered.

view plain print about
1<script type="text/javascript">
2function setExpDate(formDate){
3    // set number of days to add
4    var interval = 30;
5    var startDate = new Date(Date.parse(formDate));
6    document.write('start: ' + startDate);
7    var expDate = startDate;
8    expDate.setDate(startDate.getDate() + interval);
9    document.write('<br>expire: ' + expDate);

Example usage on a form input:

view plain print about
1<input type="text" size="10" maxlength="10" id="startDate" name="startDate" onblur="setExpDate(this.value)">   

jQuery Cycle slideshow demo with next/back/paging links

This demo uses some of the advanced features of the jQuery Cycle plugin to create a mixed content slideshow (html/text/images) with a visual navigation bar, and next/back arrows

In this setup, the slideshow advances automatically, until somebody clicks one of the links, which stops the automatic action and allows the user to control the advancement of the slides. The Cycle plugin allows for pausing, resuming or stopping the slideshow with a simple click action.

See the demo (includes css/jquery code for easy reuse) http://www.gowestwebdesign.com/demos/jquery-cycle-gallery-next-back-paging/

Thanks to Mike Alsup for the versatile Cycle plugin: http://www.malsup.com/jquery/cycle/

Feel free to use the code for any purpose, and please drop me a comment or link to check out your work. As always, comments/suggestions/fixes are welcome.

Show any Twitter Feed on your site with ColdFusion and CFFEED

This is so simple, I'll let the comments do the 'splainin:

view plain print about
2start CF Twitter Feed

5<!--- SET THE URL: add your username instead of mine --->
7<cfset feedurl="http://search.twitter.com/search.atom?q=from%3Agowestweb" />
9<!--- CFFEED does all the work --->
12 source="#feedurl#"
13 properties="feedmeta"
14 query="feeditems"
15 overwrite="true" />

17<!--- CFOUTPUT shows the feed like a query --->
19<ul class="tweet">
20<!--- change maxrows to suit your layout --->
21<cfoutput query="feeditems" maxrows="3">
27end CF Twitter Feed

31NOTE: in addition to #content#, you can show date and other columns related to each feed item.
32Use <cfdump var="#feeditems#"> to see all the available columns in the query

...Show Newer

Recent Comments

Importing Events Calendar Data into Mura CMS
Jon said: Hi Michael, Thanks for this post - similarly looking to import data from excel spreadsheet into mur... [More]

New TinyMCE lets you paste as plain text automatically
PRR said: I am using tinyMCE 4.2.3 and configured as suggested in this post but when i try pasting in editor i... [More]

Searching and collecting Mura CMS content by Extended Attribute Value with feed.addParam()
Armando Faes said: After a few hours of head banging - finally thanks to this - Once more THANK YOU! [More]

CF Gallery Creator & jQuery Slider Gallery !New and Improved!
Jan Willis said: Okay, I realized that you are calling my root as the Site - not the wwwroot. So, I moved the JS, CS... [More]

CF Gallery Creator & jQuery Slider Gallery !New and Improved!
Michael Evangelista said: @Jan, it has been a long time (6+ years) so my memory of the details is vague, but I think the image... [More]