ColdFusion Mad Libs ? Part 2 of 2

Wow! You?re back for more. I take it to mean you?re ready to take the next step in your Mad Libs application (if you have no idea what I?m talking about, stop reading right now and go check out the ColdFusion Mad Libs Part 1 tutorial)

In this tutorial, we?re going to allow the user to save the completed Mad Lib to a database. This will allow all of your site visitors to peruse all of the previous Mad Libs that have gone on before.

Wanna see it in action? http://charlie.griefer.com/madlibs_1_a.cfm.

First thing to do is create a database. It will be very simple?just one table with the following columns:

madlibID (autonumber, PK) *   
madlibDate (date/time)        
postedBy (text(30)) *         
madLib (memo) *               


* the datatypes above assume MS Access. Adjust accordingly depending on your DB.

Now onto the code.

The first template (madlibs_1.cfm) will not change. For that reason, I do not include it in this tutorial. It is shown in its entirety in the previous Mad Libs tutorial.

The second template (madlibs_2_a.cfm) needs only a few minor revisions (shown in bold).

madlibs_2.cfm (revised)
**************************************
<cfsilent>

<cfif NOT structKeyExists(form,
'ff_1')>
    <cflocation url=
"madlibs_1.cfm" addtoken="no" />
    <cfabort />
</cfif>

</cfsilent>
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC
"-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
>

<html xmlns=
"http://www.w3.org/1999/xhtml">
<head>
<title>
Untitled</title>
<meta http-equiv=
"Content-Type" content="text/html;charset=utf-8" />

<style type="text/css">
    body, input { font-family:verdana,arial,helvetica; font-size:11px; }
    b { color:#ff0000; font-variant:small-caps; background-color:#ffffcc; }
    h3 { color:#0000cc; font-size:14px; font-weight:bold; text-decoration:underline; }
    a { color:#0000ff; text-decoration:underline; }
    a:hover { color:#ff0000; text-decoration:none; }
</style>
</head>

<body>

<h3>
Your Mad Lib:</h3>

<cfoutput>
<cfsavecontent variable="madlib">

<b>#form.ff_1#</b> and <b>#form.ff_2#</b> went up the <b>#form.ff_3#</b> to <b>#form.ff_4#</b> a pail of <b>#form.ff_5#</b>.
<br />
<b>#form.ff_1#</b> fell down and broke his <b>#form.ff_6#</b> and <b>#form.ff_2#</b> came <b>#form.ff_7#</b> after.
</cfsavecontent>
</cfoutput>


<cfoutput>#variables.madlib#</cfoutput>

<form action="madlibs_3_a.cfm" method="post">
<cfoutput><input type="hidden" value="#replace(variables.madlib, '"', '""', 'all')#" name="madlib" /></cfoutput>
<input type="text" value="Enter Your Name" name="postedBy" />
<input type=
"submit" value="add to hall of fame" />
</form>

<br /><br />

<a href="madlibs_1_a.cfm">play again</a>

</body>
</html>

*************************************

What we?ve done differently is save the output of the mad lib into a variable (named madlib) using the <cfsavecontent> tag. 

We then output it to the screen (a simple <cfoutput>#variables.madlib#</cfoutput>, and we then have a form, which contains one hidden form field. That hidden form field contains the mad lib content. And just to be safe, we are going to make sure there are no double-quotes within the Mad Lib content (this would break the form). So we use the ColdFusion replace() function to swap all double-quotes with doubled-up double quotes (the CF method of escaping double quotes). We are then going to submit this information to madlibs_3_a.cfm, which will insert the mad lib into our database.

madlibs_3.cfm
**************************************
<cfsilent>

<cfif NOT structKeyExists(form,
'madlib')>
    <cflocation url=
"madlibs_1_a.cfm" addtoken="no" />
    <cfabort />
</cfif>

<cfquery name=
"insertMadLib" datasource="charlieSQL">
    INSERT INTO madLibs (
                            madLibDate,
                            postedBy,
                            madLib
                        )
                        VALUES (
                            <cfqueryparam value=
"#createODBCDate(now())#" cfsqltype="cf_sql_timestamp">,
                            <cfqueryparam value=
"#form.postedBy#" cfsqltype="cf_sql_char">,
                            <cfqueryparam value=
"#replace(form.madlib, '""', '"', 'all')#" cfsqltype="cf_sql_longvarchar">
                        )
</cfquery>

</cfsilent>
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC
"-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
>

<html xmlns=
"http://www.w3.org/1999/xhtml">
<head>
<title></title>
<meta http-equiv=
"Content-Type" content="text/html; charset=utf-8" />

<style type="text/css">
    body { font-family:verdana,arial,helvetica; font-size:11px; }
</style>
</head>

<body>

<cfoutput>
Thanks for posting your Mad Lib, #form.postedBy#!

<br /><br />
<a href="madlibs_view_1.cfm">Click here to see all Mad Libs</a>
</cfoutput>

</body>
</html>

*******************************************

Again, a very straightforward template. As with madlibs_2.cfm, we first check to make sure that the user came from the form (if not, we redirect them back to madlibs_1_a.cfm).

We then insert the new Mad Lib into our database (if you?re unfamiliar with <cfqueryparam>, please view my tutorial on it?it should take all of 5 minutes). Note that we are using the replace() function again in order to switch the escaped double-quotes back to regular double-quotes.

Finally, we provide a link to a page where the user can view all of the Mad Libs that have been saved?shown below:

madlibs_view_1.cfm
*******************************************
<cfsilent>

<cfquery name=
"getMadLibs" datasource="charlieSQL">
   
SELECT *
    FROM madLibs
    ORDER BY madLibDate DESC
</cfquery>

<cfscript>

    /**
    * Removes HTML from the string.
    * 
    * @param string String to be modified. 
    * @return Returns a string. 
    * @author Raymond Camden (ray@camdenfamily.com) 
    * @version 1, December 19, 2001 
    */
   
function StripHTML(str) {
                 return REReplaceNoCase(str,"<[^>]*>","","ALL");
    }
</cfscript>



</cfsilent><?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC
"-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
>

<html xmlns=
"http://www.w3.org/1999/xhtml">
<head>
<title></title>
<meta http-equiv=
"Content-Type" content="text/html; charset=utf-8" />

<style type="text/css">
    body, td { font-family:verdana,arial,helvetica; font-size:11px; }
    a { color:#0000ff; text-decoration:underline; }
    a:hover { color:#ff0000; text-decoration:none; }
</style>
</head>

<body>


<table border="1">
    <tr>
        <td>
Date:</td>
        <td>
Posted By:</td>
        <td>
Mad Lib:</td>
    </tr>

    <cfoutput query="getMadLibs">
    <tr>
        <td><a href=
"madlibs_view_2.cfm?madlibID=#getMadLibs.madlibID#">#dateFormat(getMadLibs.madLibDate, 'mm/dd/yyyy')#</a></td>
        <td><a href=
"madlibs_view_2.cfm?madlibID=#getMadLibs.madlibID#">#postedBy#</a></td>
        <td><a href=
"madlibs_view_2.cfm?madlibID=#getMadLibs.madlibID#">#left(stripHTML(trim(getMadLibs.madlib)), 100)#...</a></td>
    </tr>

    </cfoutput>
</table>

<br /><br />

<a href="madlibs_1_a.cfm">back to Main Mad Libs page</a>

</body>
</html>


****************************************

What?s going on here? We first query our database table to get all of the Mad Libs records.

You?ll also see a User-Defined Function (UDF) courtesy of http://www.cflib.org. This UDF strips all HTML tags from the content passed to it. Because the Mad Lib content contains <b> tags (to indicate the user?s input), we need to strip those in order to display the value to the user.

In the table in the body, we output three columns. The first contains the date that the Mad Lib was submitted?the second column shows the name of the user that posted it?the third and final contains a ?teaser??it shows the first 100 characters of the Mad Lib content. All 3 columns link to a page (madlibs_view_2.cfm) where the user can see the full Mad Lib (note that we?re passing the madlibID in the URL).


madlibs_view_2.cfm
*****************************************
<cfsilent>

<cfif NOT structKeyExists(URL,
'madlibID')>
    <cflocation url=
"madlibs_1_a.cfm" addtoken="no" />
    <cfabort />
</cfif>

<cfquery name=
"getMadLib" datasource="charlieSQL">
   
SELECT *
    FROM madLibs
    WHERE madlibID = <cfqueryparam value="#URL.madLibID#" cfsqltype="cf_sql_integer">
</cfquery>

</cfsilent>
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC
"-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
>

<html xmlns=
"http://www.w3.org/1999/xhtml">
<head>
<title></title>
<meta http-equiv=
"Content-Type" content="text/html; charset=utf-8" />

<style type="text/css">
    body, td { font-family:verdana,arial,helvetica; font-size:11px; }
    b { color:#ff0000; font-variant:small-caps; background-color:#ffffcc; }
    a { color:#0000ff; text-decoration:underline; }
    a:hover { color:#ff0000; text-decoration:none; }
</style>
</head>

<body>

<cfoutput query="getMadLib">
<table>
    <tr>
        <td style=
"font-weight:bold; width:80px;">Posted By:&nbsp;</td>
        <td style=
"width:400px;">#getMadLib.postedBy#</td>
    </tr>
    <tr>
        <td style=
"font-weight:bold; width:80px;">Date:&nbsp;</td>
        <td style=
"width:400px;">#dateFormat(madLibDate, 'mm/dd/yyyy')#</td>
    </tr>
    <tr>
        <td colspan=
"2"><br /><br /></td>
    </tr>
    <tr>
        <td colspan=
"2">#madLib#</td>
    </tr>
</table>

</cfoutput>

<br /><br />

<a href="madlibs_view_1.cfm">back</a>

</body>
</html>

****************************************

Again, a very straightforward template. We first check to see that URL.madlibID was passed (if not, relocate the user to madlibs_1_a.cfm). We then query the database to get the selected Mad Lib, and finally, we display it (notice I also added a custom style for the <b> tag, which will show the ?user input? values more clearly).

Finally, we add a link allowing the user to go back to view all Mad Libs in the database.

That?s it! You?re now ready to unleash your Mad Libs application on an unsuspecting public.

A few final notes:

1) Mad Libs *is* a registered trademark. You might want to consider calling your application something else.
2) If you get a lot of entries in your database, your madlibs_view_1.cfm page might get a bit unruly. If that happens, consider using the previous/next records tutorial found here on easycfm.com.
3) Of course, be aware that you run the risk of displaying vulgar content on your site by allowing users to post their own content. If this is unacceptable to you, consider adding the following content to the madlibs_3.cfm template (new content in bold):

madlibs_3_a.cfm (modified to disallow certain language)
****************************************
<cfsilent>

<cfif NOT structKeyExists(form,
'madlib')>
    <cflocation url=
"madlibs_1.cfm" addtoken="no" />
    <cfabort />
</cfif>

<cfset variables.myBadWordList =
"xxxx, yyyy, zzzz" />

<cfset variables.badWords = 0>
<cfloop list=
"#variables.myBadWordList#" index="i"
>
    <cfif findNoCase(i, madLib)>
        <cfset variables.badWords = variables.badWords + 1>
    </cfif>
</cfloop>

<cfif variables.badWords EQ 0>


    <cfquery name="insertMadLib" datasource=
"charlieSQL">
       
INSERT INTO madLibs (
                            madLibDate,
                            postedBy,
                            madLib
                           )
                           VALUES (
                                <cfqueryparam value=
"#createODBCDate(now())#" cfsqltype="cf_sql_timestamp">,
                                <cfqueryparam value=
"#form.postedBy#" cfsqltype="cf_sql_char">,
                                <cfqueryparam value=
"#replace(form.madlib, '""', '"', 'all')#" cfsqltype="cf_sql_longvarchar">
                           
)
        </cfquery>
</cfif>

</cfsilent>
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC
"-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
>

<html xmlns=
"http://www.w3.org/1999/xhtml">
<head>
<title></title>
<meta http-equiv=
"Content-Type" content="text/html; charset=utf-8" />

<style type="text/css">
    body { font-family:verdana,arial,helvetica; font-size:11px; }
</style>
</head>

<body>


<cfoutput>
    <cfif NOT variables.badWords>

        Thanks for posting your Mad Lib, #form.postedBy#!
    <cfelse>
        Sorry, but your Mad Lib contained content that is not suitable for this site. 
    </cfif>

    <br /><br />
    <a href="madlibs_view_1.cfm">Click here to see all Mad Libs</a>
</cfoutput>


</body>
</html>


****************************************

Ok?let?s break this down.

First, we create a list of known ?objectionable words?:
<cfset variables myBadWordList = ?xxxx, yyyy, zzzz, aaaa?>
(yes, I know ?yyyy? is not objectionable?you?ll need to come up with your own list)

Second, we create a variable called badWords, and set it to 0.
<cfset variables badWords = 0>

Next, we loop over that list, looking for each element of the list in the madlib content. If we find one, we increment the value of variables.badWords by 1.

Once we?re done looping, if the value of variables.badWords is still 0, that means no objectionable words were found, and we can do our INSERT query.

In the body of the page, we also run a condition based on the value of variables.badWords. If it?s 0, we thank the user for their submission. If it?s greater than 0, we notify the user that their content contained objectionable word(s), and therefore were not added to the database.

As always, if you have any questions, feel free to contact me personally, or preferably on the easycfm.com forums (so everyone can benefit from the discussion)

About This Tutorial
Author: Charlie Griefer (CJ)
Skill Level: Beginner 
 
 
 
Platforms Tested: CF5,CFMX
Total Views: 99,012
Submission Date: May 29, 2003
Last Update Date: June 05, 2009
All Tutorials By This Autor: 15
Discuss This Tutorial
  • como fa├žo um replace no coldfusion T+

Advertisement

Sponsored By...
Mobile App Development (IOS, Android, Cordova, Phonegap, Objective-C, Java) - Austin, Texas Mobile Apps - Touch512, LLC.