Thursday, December 31, 2020

Send user to a new url with parameter using React

Here is the scenario - You need update the page view when a user makes a selection from a drop down. Example: There is a drop down of employees and when the user makes a selection, you need to change the employee profile view to the selected employee.

First, you can pass a url parameter like so:   /yourUrl/2202.

You then read the parameter in the code like so: props.match.params.id

EX:     

let emp_id = {
      emp_id: props.match.params.id,
    };


SIDE NOTE: You will need to add match to propTypes and you do that like so:

  match: PropTypes.shape({
    params: PropTypes.shape({
      id: PropTypes.string,
    }),
  })

You also need to pass it in App.js like so: 

<Route path="/yourUrl/:id" component={YourComponent} />

Now that you have passed in your parameter, you can use it to get the employee info from the database. In this case, I am using useEffect. I create an argument from the ID passed in (see green text below) and then I pass the emp_id into my function to get the data for the employee (see blue text below). The red text below will call this function only if the ID has changed.

  useEffect(() => {

    let emp_id = {
      emp_id: props.match.params.id,
    };

    props.loadEmployee(emp_id);
  

  }, [props.match.params.id]);


Ok so now, lets add in a select function so the user can change the employee.

Simply add a select drop down like so:

<ValidationForm onSubmit={handleSubmit}>
<SelectGroup
  name="emp_id"
  id="emp_id"
  value={props.match.params.id}
  onChange={handleEmployeeChange.bind(this)}
>
  <option value=""></option>
  {props.employees.map((e, key) => {
return (
  <option key={key} value={e.employee_emp_id}>
{e.employee_name} ({e.employee_emp_id})
  </option>
);
  })}
</SelectGroup>
  </ValidationForm>

Ok let's walk through this code. 
  1. The blue line defaults the selection to the current url param.
  2. The red line handles the change
  3. The orange lines populate the drop down
Now, the red line calls another function and binds the selected employee ID. When the user makes a selection, here is the handleEmployeeChange function that is called:

 const handleEmployeeChange = (event) => {
    props.history.push(`/yourUrl/${event.target.value}`);
  };


handleEmployeeChange takes the selected value and calls the url which will load the data of the newly selected employee.

SIDE NOTE:  You can learn more about props.history.push here

That's it!

Let me know if you have any questions or suggestion of a better way!

Tuesday, August 14, 2018

How to require at least one checkbox

Here is your script:


<script>
            $(document).ready(function () {
                $('#checkBtn').click(function() {
                  checked = $("input[type=checkbox]:checked").length;

                  if(!checked) {
                    alert("You must check at least one record.");
                    return false;
                  }

                });
            });
</script>
            

Add this to your submit button:

 id="checkBtn"

Thursday, March 22, 2018

Turn Off Auto-Complete for all browsers

While we all love the auto-complete function on browsers, there may be a reason to turn it off.  Mainly, for security reasons, like on banking sites.

This is a hack and the only solution that will work on all browsers. 

Add the following to all fields that you don't want to auto-fill:

readonly onfocus="this.removeAttribute('readonly');" style="background-color:white;"

What happens is, when the page loads, the fields are read only. Once the user clicks on the field to enter a value, the readonly attribute is removed.

Now, an important part of this is to make sure you add a white background so the fields don't appear to be readonly.

That's it!

nJoy.

Thursday, March 8, 2018

How to keep a user's session alive

There may be instances where you need to keep a user's session alive. For example, your visitors need to take an hour long course, but the global session timeout is 30 minutes. You don't want the user's session to time out before they finish the course, right?

Here is a simple way to keep the session alive.

Add this script to the very top of the pages. Then, add a blank page in the same directory. Notice the bold red line below - I have a 'keep_alive.cfm" file in the same directory, which is accessed by the script which in turn keeps the session alive.

<script>
    var xmlhttp;
setInterval
    (
        function() {
            if (window.XMLHttpRequest) {
                // code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp = new XMLHttpRequest();
            } else {
                // code for IE6, IE5
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.open("POST", "keep_alive.cfm", true);
            xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            xmlhttp.send("foo=bar");
        }, 60000
); // 1 minute
</script>



Enjoy!

Wednesday, February 21, 2018

Quick and easy way to hide and show items on a page with JavaScript



In this scenario, we want to hide/show salary questions IF the user is in certain states:


Step 1: The Form

Form Fields: I added an onClick event to the radio buttons which will kick off the SHOW/HIDE function: 

<input type="radio" value="0" onclick="javascript:showHideSalary();" id="legalStates0" name="legalStates"> NO

<input type="radio" value="1" onclick="javascript:showHideSalary();" id="legalStates1" name="legalStates"> YES





Step 2: The script

Add this script to the top of the page. Here I am saying if the users selects YES to the legal states question, hide the salary div.

<script>
function showHideSalary() {
    if (document.getElementById('legalStates0').checked){
        document.getElementById('salaryDiv').style.display = 'block';  display it
    }
    else document.getElementById('salaryDiv').style.display = 'none'; don't display it

}
</script>




Step 3: The DIV you want to hide. 


<div id="salaryDiv" style="display:none">

* add whatever you want to hide/display here *

</div>


Enjoy and let me know if you have any issues.


Tuesday, October 3, 2017

Bootstrap: Collapse panel with radio buttons

There are many examples of this code that don't have the radio button actually selected.

Here is the code that does so:



<!DOCTYPE html>
<html >
<head>
  <meta charset="UTF-8">
  <title>Bootstrap: Collapse panel with radio buttons</title>
   
   
  <link rel='stylesheet prefetch' href='http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css'>

      <link rel="stylesheet" href="css/style.css">

   
</head>

<body>
  <h2>Bootstrap: Collapse panel with radio buttons</h2>
<i>A simple method to collapse and expand a Bootstrap collapsable panel using radio buttons</i>

<div class="container">
  <div class="row">
    <div class="col-xs-12">
      <span>Display panel: </span>
      <input name="collapseGroup" type="radio" data-toggle="collapse" data-target="#collapseOne"/> Yes
      <input name="collapseGroup" type="radio" data-toggle="collapse" data-target="#collapseOne" checked/> No
      <div class="panel-group" id="accordion">
        <div class="panel panel-default">
          <div class="panel-heading">
            <h4 class="panel-title">
              Header
            </h4>
          </div>
          <div id="collapseOne" class="panel-collapse collapse">
            <div class="panel-body">
              <p>Content</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
  <script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js'></script>

   
</body>
</html>

Friday, August 4, 2017

Find a specific column and/or table in SQL

I'll make this quick and just share the query:

SELECT       c.name  AS 'ColumnName',t.name AS 'TableName'
FROM          sys.columns c
JOIN             sys.tables  t   ON c.object_id = t.object_id
WHERE        c.name LIKE '%addNameHere%'
ORDER BY  TableName   ,ColumnName;


Enjoy!

Thursday, July 7, 2016

Country Select HTML

<select name='Country' size='1'>
  <option value='' SELECTED></option>
  <option value='United States'>United States</option>
  <option value='Canada'>Canada</option>
  <option value='Afghanistan'>Afghanistan</option>
  <option value='Albania'>Albania</option>
  <option value='Algeria'>Algeria</option>
  <option value='American Samoa'>American Samoa</option>
  <option value='Andorra'>Andorra</option>
  <option value='Angola'>Angola</option>
  <option value='Anguilla'>Anguilla</option>
  <option value='Antarctica'>Antarctica</option>
  <option value='Antigua And Barbuda'>Antigua And Barbuda</option>
  <option value='Argentina'>Argentina</option>
  <option value='Armenia'>Armenia</option>
  <option value='Aruba'>Aruba</option>
  <option value='Australia'>Australia</option>
  <option value='Austria'>Austria</option>
  <option value='Azerbaijan'>Azerbaijan</option>
  <option value='Bahamas'>Bahamas</option>
  <option value='Bahrain'>Bahrain</option>
  <option value='Bangladesh'>Bangladesh</option>
  <option value='Barbados'>Barbados</option>
  <option value='Belarus'>Belarus</option>
  <option value='Belgium'>Belgium</option>
  <option value='Belize'>Belize</option>
  <option value='Benin'>Benin</option>
  <option value='Bermuda'>Bermuda</option>
  <option value='Bhutan'>Bhutan</option>
  <option value='Bolivia'>Bolivia</option>
  <option value='Bosnia And Herzegowina'>Bosnia And Herzegowina</option>
  <option value='Botswana'>Botswana</option>
  <option value='Bouvet Island'>Bouvet Island</option>
  <option value='Brazil'>Brazil</option>
  <option value='British Indian Ocean Territory'>British Indian Ocean Territory</option>
  <option value='Brunei Darussalam'>Brunei Darussalam</option>
  <option value='Bulgaria'>Bulgaria</option>
  <option value='Burkina Faso'>Burkina Faso</option>
  <option value='Burundi'>Burundi</option>
  <option value='Cambodia'>Cambodia</option>
  <option value='Cameroon'>Cameroon</option>
  <option value='Canada'>Canada</option>
  <option value='Cape Verde'>Cape Verde</option>
  <option value='Cayman Islands'>Cayman Islands</option>
  <option value='Central African Republic'>Central African Republic</option>
  <option value='Chad'>Chad</option>
  <option value='Chile'>Chile</option>
  <option value='China'>China</option>
  <option value='Christmas Island'>Christmas Island</option>
  <option value='Cocos (Keeling) Islands'>Cocos (Keeling) Islands</option>
  <option value='Colombia'>Colombia</option>
  <option value='Comoros'>Comoros</option>
  <option value='Congo'>Congo</option>
  <option value='Cook Islands'>Cook Islands</option>
  <option value='Costa Rica'>Costa Rica</option>
  <option value='Cote D\'Ivoire'>Cote D\'Ivoire</option>
  <option value='Croatia'>Croatia</option>
  <option value='Cuba'>Cuba</option>
  <option value='Cyprus'>Cyprus</option>
  <option value='Czech Republic'>Czech Republic</option>
  <option value='Denmark'>Denmark</option>
  <option value='Djibouti'>Djibouti</option>
  <option value='Dominica'>Dominica</option>
  <option value='Dominican Republic'>Dominican Republic</option>
  <option value='East Timor'>East Timor</option>
  <option value='Ecuador'>Ecuador</option>
  <option value='Egypt'>Egypt</option>
  <option value='El Salvador'>El Salvador</option>
  <option value='Equatorial Guinea'>Equatorial Guinea</option>
  <option value='Eritrea'>Eritrea</option>
  <option value='Estonia'>Estonia</option>
  <option value='Ethiopia'>Ethiopia</option>
  <option value='Falkland Islands'>Falkland Islands</option>
  <option value='Faroe Islands'>Faroe Islands</option>
  <option value='Fiji'>Fiji</option>
  <option value='Finland'>Finland</option>
  <option value='France'>France</option>
  <option value='France, Metropolitan'>France, Metropolitan</option>
  <option value='French Guiana'>French Guiana</option>
  <option value='French Polynesia'>French Polynesia</option>
  <option value='French Southern Territories'>French Southern Territories</option>
  <option value='Gabon'>Gabon</option>
  <option value='Gambia'>Gambia</option>
  <option value='Georgia'>Georgia</option>
  <option value='Germany'>Germany</option>
  <option value='Ghana'>Ghana</option>
  <option value='Gibraltar'>Gibraltar</option>
  <option value='Greece'>Greece</option>
  <option value='Greenland'>Greenland</option>
  <option value='Grenada'>Grenada</option>
  <option value='Guadeloupe'>Guadeloupe</option>
  <option value='Guam'>Guam</option>
  <option value='Guatemala'>Guatemala</option>
  <option value='Guinea'>Guinea</option>
  <option value='Guinea-Bissau'>Guinea-Bissau</option>
  <option value='Guyana'>Guyana</option>
  <option value='Haiti'>Haiti</option>
  <option value='Heard And Mc Donald Islands'>Heard And Mc Donald Islands</option>
  <option value='Honduras'>Honduras</option>
  <option value='Hong Kong'>Hong Kong</option>
  <option value='Hungary'>Hungary</option>
  <option value='Iceland'>Iceland</option>
  <option value='India'>India</option>
  <option value='Indonesia'>Indonesia</option>
  <option value='Iran'>Iran</option>
  <option value='Iraq'>Iraq</option>
  <option value='Ireland'>Ireland</option>
  <option value='Israel'>Israel</option>
  <option value='Italy'>Italy</option>
  <option value='Jamaica'>Jamaica</option>
  <option value='Japan'>Japan</option>
  <option value='Jordan'>Jordan</option>
  <option value='Kazakhstan'>Kazakhstan</option>
  <option value='Kenya'>Kenya</option>
  <option value='Kiribati'>Kiribati</option>
  <option value='North Korea (People\'s Republic Of Korea)'>North Korea (People\'s Republic Of Korea)</option>
  <option value='South Korea (Republic Of Korea)'>South Korea (Republic Of Korea)</option>
  <option value='Kuwait'>Kuwait</option>
  <option value='Kyrgyzstan'>Kyrgyzstan</option>
  <option value='Lao People\'s Republic'>Lao People\'s Republic</option>
  <option value='Latvia'>Latvia</option>
  <option value='Lebanon'>Lebanon</option>
  <option value='Lesotho'>Lesotho</option>
  <option value='Liberia'>Liberia</option>
  <option value='Libyan Arab Jamahiriya'>Libyan Arab Jamahiriya</option>
  <option value='Liechtenstein'>Liechtenstein</option>
  <option value='Lithuania'>Lithuania</option>
  <option value='Luxembourg'>Luxembourg</option>
  <option value='Macau'>Macau</option>
  <option value='Macedonia'>Macedonia</option>
  <option value='Madagascar'>Madagascar</option>
  <option value='Malawi'>Malawi</option>
  <option value='Malaysia'>Malaysia</option>
  <option value='Maldives'>Maldives</option>
  <option value='Mali'>Mali</option>
  <option value='Malta'>Malta</option>
  <option value='Marshall Islands'>Marshall Islands</option>
  <option value='Martinique'>Martinique</option>
  <option value='Mauritania'>Mauritania</option>
  <option value='Mauritius'>Mauritius</option>
  <option value='Mayotte'>Mayotte</option>
  <option value='Mexico'>Mexico</option>
  <option value='Micronesia'>Micronesia</option>
  <option value='Moldova'>Moldova</option>
  <option value='Monaco'>Monaco</option>
  <option value='Mongolia'>Mongolia</option>
  <option value='Montserrat'>Montserrat</option>
  <option value='Morocco'>Morocco</option>
  <option value='Mozambique'>Mozambique</option>
  <option value='Myanmar'>Myanmar</option>
  <option value='Namibia'>Namibia</option>
  <option value='Nauru'>Nauru</option>
  <option value='Nepal'>Nepal</option>
  <option value='Netherlands'>Netherlands</option>
  <option value='Netherlands Antilles'>Netherlands Antilles</option>
  <option value='New Caledonia'>New Caledonia</option>
  <option value='New Zealand'>New Zealand</option>
  <option value='Nicaragua'>Nicaragua</option>
  <option value='Niger'>Niger</option>
  <option value='Nigeria'>Nigeria</option>
  <option value='Niue'>Niue</option>
  <option value='Norfolk Island'>Norfolk Island</option>
  <option value='Northern Mariana Islands'>Northern Mariana Islands</option>
  <option value='Norway'>Norway</option>
  <option value='Oman'>Oman</option>
  <option value='Pakistan'>Pakistan</option>
  <option value='Palau'>Palau</option>
  <option value='Panama'>Panama</option>
  <option value='Papua New Guinea'>Papua New Guinea</option>
  <option value='Paraguay'>Paraguay</option>
  <option value='Peru'>Peru</option>
  <option value='Philippines'>Philippines</option>
  <option value='Pitcairn'>Pitcairn</option>
  <option value='Poland'>Poland</option>
  <option value='Portugal'>Portugal</option>
  <option value='Puerto Rico'>Puerto Rico</option>
  <option value='Qatar'>Qatar</option>
  <option value='Reunion'>Reunion</option>
  <option value='Romania'>Romania</option>
  <option value='Russian Federation'>Russian Federation</option>
  <option value='Rwanda'>Rwanda</option>
  <option value='Saint Kitts And Nevis'>Saint Kitts And Nevis</option>
  <option value='Saint Lucia'>Saint Lucia</option>
  <option value='Saint Vincent And The Grenadines'>Saint Vincent And The Grenadines</option>
  <option value='Samoa'>Samoa</option>
  <option value='San Marino'>San Marino</option>
  <option value='Sao Tome And Principe'>Sao Tome And Principe</option>
  <option value='Saudi Arabia'>Saudi Arabia</option>
  <option value='Senegal'>Senegal</option>
  <option value='Seychelles'>Seychelles</option>
  <option value='Sierra Leone'>Sierra Leone</option>
  <option value='Singapore'>Singapore</option>
  <option value='Slovakia'>Slovakia</option>
  <option value='Slovenia'>Slovenia</option>
  <option value='Solomon Islands'>Solomon Islands</option>
  <option value='Somalia'>Somalia</option>
  <option value='South Africa'>South Africa</option>
  <option value='South Georgia And The South Sandwich Islands'>South Georgia And The South Sandwich Islands</option>
  <option value='Spain'>Spain</option>
  <option value='Sri Lanka'>Sri Lanka</option>
  <option value='St Helena'>St Helena</option>
  <option value='St Pierre and Miquelon'>St Pierre and Miquelon</option>
  <option value='Sudan'>Sudan</option>
  <option value='Suriname'>Suriname</option>
  <option value='Svalbard And Jan Mayen Islands'>Svalbard And Jan Mayen Islands</option>
  <option value='Swaziland'>Swaziland</option>
  <option value='Sweden'>Sweden</option>
  <option value='Switzerland'>Switzerland</option>
  <option value='Syrian Arab Republic'>Syrian Arab Republic</option>
  <option value='Taiwan'>Taiwan</option>
  <option value='Tajikistan'>Tajikistan</option>
  <option value='Tanzania'>Tanzania</option>
  <option value='Thailand'>Thailand</option>
  <option value='Togo'>Togo</option>
  <option value='Tokelau'>Tokelau</option>
  <option value='Tonga'>Tonga</option>
  <option value='Trinidad And Tobago'>Trinidad And Tobago</option>
  <option value='Tunisia'>Tunisia</option>
  <option value='Turkey'>Turkey</option>
  <option value='Turkmenistan'>Turkmenistan</option>
  <option value='Turks And Caicos Islands'>Turks And Caicos Islands</option>
  <option value='Tuvalu'>Tuvalu</option>
  <option value='Uganda'>Uganda</option>
  <option value='Ukraine'>Ukraine</option>
  <option value='United Arab Emirates'>United Arab Emirates</option>
  <option value='United Kingdom'>United Kingdom</option>
  <option value='United States'>United States</option>
  <option value='United States Minor Outlying Islands'>United States Minor Outlying Islands</option>
  <option value='Uruguay'>Uruguay</option>
  <option value='Uzbekistan'>Uzbekistan</option>
  <option value='Vanuatu'>Vanuatu</option>
  <option value='Vatican City State'>Vatican City State</option>
  <option value='Venezuela'>Venezuela</option>
  <option value='Viet Nam'>Viet Nam</option>
  <option value='Virgin Islands (British)'>Virgin Islands (British)</option>
  <option value='Virgin Islands (U.S.)'>Virgin Islands (U.S.)</option>
  <option value='Wallis And Futuna Islands'>Wallis And Futuna Islands</option>
  <option value='Western Sahara'>Western Sahara</option>
  <option value='Yemen'>Yemen</option>
  <option value='Zaire'>Zaire</option>
  <option value='Zambia'>Zambia</option>
  <option value='Zimbabwe'>Zimbabwe</option>
  <option value='Other - Not Shown'>Other - Not Shown</option>
</select>

State select html

<select name='State' size='1'>
  <option value='' SELECTED>[State]</option>
  <option value='ZZ'>International</option>
  <option value='AL'>AL-Alabama</option>
  <option value='AK'>AK-Alaska</option>
  <option value='AZ'>AZ-Arizona</option>
  <option value='AR'>AR-Arkansas</option>
  <option value='CA'>CA-California</option>
  <option value='CO'>CO-Colorado</option>
  <option value='CT'>CT-Connecticut</option>
  <option value='DC'>DC-Washington D.C.</option>
  <option value='DE'>DE-Delaware</option>
  <option value='FL'>FL-Florida</option>
  <option value='GA'>GA-Georgia</option>
  <option value='HI'>HI-Hawaii</option>
  <option value='ID'>ID-Idaho</option>
  <option value='IL'>IL-Illinois</option>
  <option value='IN'>IN-Indiana</option>
  <option value='IA'>IA-Iowa</option>
  <option value='KS'>KS-Kansas</option>
  <option value='KY'>KY-Kentucky</option>
  <option value='LA'>LA-Louisiana</option>
  <option value='ME'>ME-Maine</option>
  <option value='MD'>MD-Maryland</option>
  <option value='MA'>MA-Massachusetts</option>
  <option value='MI'>MI-Michigan</option>
  <option value='MN'>MN-Minnesota</option>
  <option value='MS'>MS-Mississippi</option>
  <option value='MO'>MO-Missouri</option>
  <option value='MT'>MT-Montana</option>
  <option value='NE'>NE-Nebraska</option>
  <option value='NV'>NV-Nevada</option>
  <option value='NH'>NH-New Hampshire</option>
  <option value='NJ'>NJ-New Jersey</option>
  <option value='NM'>NM-New Mexico</option>
  <option value='NY'>NY-New York</option>
  <option value='NC'>NC-North Carolina</option>
  <option value='ND'>ND-North Dakota</option>
  <option value='OH'>OH-Ohio</option>
  <option value='OK'>OK-Oklahoma</option>
  <option value='OR'>OR-Oregon</option>
  <option value='PA'>PA-Pennsylvania</option>
  <option value='PR'>PR-Puerto Rico</option>
  <option value='RI'>RI-Rhode Island</option>
  <option value='SC'>SC-South Carolina</option>
  <option value='SD'>SD-South Dakota</option>
  <option value='TN'>TN-Tennessee</option>
  <option value='TX'>TX-Texas</option>
  <option value='UT'>UT-Utah</option>
  <option value='VT'>VT-Vermont</option>
  <option value='VA'>VA-Virginia</option>
  <option value='WA'>WA-Washington</option>
  <option value='WV'>WV-West Virginia</option>
  <option value='WI'>WI-Wisconsin</option>
  <option value='WY'>WY-Wyoming</option>
</select>

Friday, January 22, 2016

Dynamically update multiple rows in one form

This is one of those functions that I have avoided for a long time.

I decided that is was time for me to tackle it so here goes.

Scenario:

You have a form with multiple rows.

You need to perform CRUD on the records all in one place. (Brain starting to hurt yet?)

Don't worry. It's fairly easy.

Step 1 - Retrieve your records:

<cfquery name="getArt" datasource="cfartgallery" maxrows="10"> 
select artid, artname from art 
</cfquery>

Step 2 - Build Your Form.

#currentRow# is used to give each row a unique identifier and I pass the row count as a hidden field to use to loop through the fields once submitted (see red highlights below).

<form action="formLoopUpdate.cfm" method="post">
  <table>
    <cfloop query="getArt">
      <tr> <cfoutput>
          <td>
          <input type="text" name="art#currentRow#" value="#artname#" />
          <input type="hidden" name="artID#currentRow#" value="#artID#" />
          </td>
        </cfoutput> </tr>
    </cfloop>
  </table>
  
  <input type='hidden' name='totalNumberOfRecords' value='<cfoutput>#getArt.recordCount#</cfoutput>'>
  
  <input type="submit" name="save" value="Save" />
</form>


3. Submit and save

No need for commentary here. It's explains itself.

<cfif structKeyExists(form, "save")>
   
        <cfloop from="1" to="#form.totalNumberOfRecords#" index="counter">
          <!--- extract the values of the dynamic form fields --->
          <cfset art   = form["art"   & counter]>
          <cfset artID   = form["artID"   & counter]>
    
            <cfquery datasource="cfartgallery"> 
                    update art 
                    set artname = <cfqueryparam cfsqltype="cf_sql_varchar" value="#art#"> 
                    where artid = <cfqueryparam cfsqltype="cf_sql_integer" value="#artid#"> 
            </cfquery> 
    
         </cfloop>
    
    
    </cfif>


That's it.

Let me know what you think or how this could have been done differently.

-MB



Another example:



<cfloop from="1" to="#form.totalNumberItems#" index="counter">


<!--- update category order --->

<cfif isdefined("form.categoryOrder#counter#")> 


<cfset categoryOrder = form["categoryOrder"   & counter]>

<cfset categoryID   = form["categoryID"   & counter]>


<cfquery name="updateCategoryOrder" datasource="#application.var#"> 

update Checklist_Category 

set sortOrder = <cfqueryparam cfsqltype="cf_sql_integer" value="#categoryOrder#"> 

where categoryID = <cfqueryparam cfsqltype="cf_sql_integer" value="#categoryID#"> 

</cfquery>  


</cfif>    



<!--- update checklist item order --->

<cfif isdefined("form.checkListOrder#counter#")> 


<cfset checkListOrder = form["checkListOrder"   & counter]>

<cfset checkDetailID    = form["checkDetailID"    & counter]>


<cfquery name="updateCheckListOrder" datasource="#application.var#"> 

update Checklist_Admin 

set sortOrder = <cfqueryparam cfsqltype="cf_sql_integer" value="#checkListOrder#"> 

where checkDetailID = <cfqueryparam cfsqltype="cf_sql_integer" value="#checkDetailID#"> 

</cfquery> 


</cfif>

</cfloop>


</cfif>



Tuesday, October 6, 2015

Remove Trailing Characters with Javascript

This is not CF but it sure comes in handy.

If for any reason you need to get rid pesky trailing characters, here's the script:

<script>
function trimTrailingChars(s, charToTrim)
   {
     var regExp = new RegExp(charToTrim + "+$");
     var result = s.replace(regExp, "");

     return result;
   }
</script>




And here is how you use it in your code:

var sText = trimTrailingChars(sText, ',');


Note the red text above. Change the comma to whatever you want to get rid of.


Friday, March 13, 2015

Customized placement of jQuery error messages

The code is pretty simple. I have highlighted the most important parts in red.




<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">
<script src='//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js'></script>
<script src='https://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.js'></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
  $(function() {
    $( "#DateChooser" ).datepicker();
  });
  </script>
<style class="cp-pen-styles">
.error {font-size:12px; color:#CC0000;}
</style>
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$(function(){
$("#form").validate({
    messages: {
        name: "Please enter name.",
        surname: "Please enter surname.",  
DateChooser: "Please enter date."
    },
    errorElement: "div",   
    errorPlacement: function(error, element) {
            error.insertAfter(element);
        }   
});
});
});//]]>

</script>
</head>
<body>
<cfform id="form">
  <label for="name">Name</label>
  <input type="text" name="name" id="name" class="required" minlength="2" />
  <br/>
  <div></div>
  <br>
  <label for="DateChooser">Date</label>
  <input   id="DateChooser" class="required"  name="DateChooser">
  <br/>
  <div></div>
  <br>
  <label for="surname">Surname</label>
  <input type="text" name="surname" id="surname" class="required" minlength="2" />
  <br />
  <div></div>
  <input type="submit" value="submit" id="submit" />
</cfform>
</body>
</html>

Thursday, March 12, 2015

Easy jQuery Error Message Customization

This code will allow you to customize your jQuery error messages:


Add these links to your page

<link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">
<script src='//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js'></script>
<script src='https://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.js'></script>



You can style your error messages:

<style class="cp-pen-styles">
.error {
color:red;
font-family:verdana, Helvetica;
}
</style>



Your script


<script>
$(function () {
    $('#formTest').validate({
        rules: {
            name: { required: true },
address: { required: true }

        },
        messages: {
            name: { required: 'Please enter your name' },
address: { required: 'Please enter your address' }
        }
    });


});
  </script>

Your form

<form action='test.cfm' id="formTest" name="formTest" method='POST'>
  <input name="name" value="" />
  <input name="address" value="" />
  <input type="submit" class="submit" value="Add Appeal Info">
</form>

Thursday, January 29, 2015

How to find spaces in a form field in Coldfusion

This is pretty straight forward

<cfset strTest = "#form.variable#">
<cfset strTarget = " ">
<cfset newTest=Chr(1) & strTest & Chr(1)>
<cfset intCount=DecrementValue(ArrayLen(newTest.split(strTarget.replaceAll("(\W)","\\$1"))))>
<cfoutput>#intCount#</cfoutput>

This will count the number of spaces in the variable.

If the intCount = 0, you are good to go.

You can use the code to test for any character.

Enjoy!

Thursday, December 18, 2014

How to dynamically define quarterly dates in Coldfusion

You know those reports that upper management request from time to time? The ones that give you nightmares? Yeah those. Well sometimes they will request quarterly reports so I wanted to share an easy way to define quarterly dates.

So we start with our default variables:

<cfset quarter = 1>
<cfset year = "#year(now())#">
<cfset startmonth = 1>

And here are the functions that create the dates:

<cffunction name="QuarterFirstDate" returnType="date">
    <cfargument name="quarternumber" required="yes" type="numeric">
    <cfargument name="yr" type="numeric" default="#year(now())#">
    <cfargument name="startmonth" type="numeric" default="1">
    <cfset firstDate = DateAdd("m",startmonth-1,CreateDate(yr, ((quarternumber-1)*3)+1, "1"))>
    <cfreturn firstDate>
</cffunction>

<cffunction name="QuarterLastDate" returnType="date">
    <cfargument name="quarternumber" required="yes" type="numeric">
    <cfargument name="yr" type="numeric"  default="#year(now())#">
    <cfargument name="startmonth" type="numeric" default="1">
    <cfset lastDate = DateAdd("m",startmonth-1,CreateDate(yr, quarternumber*3, DaysInMonth(CreateDate(yr, quarternumber*3, "1"))))>
    <cfreturn lastDate>
</cffunction>


And here is how I define my returned variables to be used in my code:

<cfset startDate = #DateFormat(QuarterFirstDate(quarter, year, startmonth))#>
<cfset endDate = #DateFormat(QuarterLastDate(quarter, year, startmonth))#>

To change the quarters, simply change the default quarter variable define at the top of the page:

<cfset quarter = 1> = 01-Jan-14 - 31-Mar-14
<cfset quarter = 2>  = 01-Apr-14 - 30-Jun-14
<cfset quarter = 3>  = 01-Jul-14 - 30-Sep-14
<cfset quarter = 4>  01-Oct-14 - 31-Dec-14


nJoy!

Wednesday, July 9, 2014

How to return a set number of rows in SQL using a variable

You're gonna love me for this one :)

I'll make it very simple too.

So I am sure you've use the TOP clause to retreive a certain number of rows from a query, right?


Here is an example of how you can set the value of TOP as a variable based on, let's say...user input.

CREATE PROCEDURE [dbo].[testRowCount]
    (
        @total int=0  input variable. This can be based on anything like user input, etc.
    )

AS
DECLARE @top INT what you will use as the TOP variable
SET @top = @total  here you set the value for TOP based on the input

And here is how you use in in the select statement

SELECT TOP(@top) *
            FROM  table
WHERE....



You're welcome :)

Tuesday, June 10, 2014

Stored Proc Clean Up - Getting rid of procs you don't use

If you are like me, then you HATE clutter. I am a minimalist - yep even when coding. I hate to see stored procs laying around that I:

1. Don't know what they do OR
2. Don't know if they are even in use

Of course, you don't want to start deleting procs randomly (that's a no-no)

So here are a few snippets to help you with your SQL house keeping:

This one tells you all of the procs that have run since the last restart.

SELECT p.name, last_execution_time, s.type_desc, create_date, modify_date
 FROM sys.dm_exec_procedure_stats AS s
INNER JOIN sys.procedures AS p
ON s.[object_id] = p.[object_id]
ORDER BY p.name;

And this one shows procs that have NOT been run since last restart:

SELECT p.*
FROM sys.procedures AS p
LEFT JOIN sys.dm_exec_procedure_stats AS s
ON s.[object_id] = p.[object_id]
WHERE s.object_id IS null
order by name


Happy Cleaning!

Thursday, October 31, 2013

Ajax with Double Bind

Ok this was pretty tricky but I figured it out :-)

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.

 here is my first input:

   <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

So let's say you've built a really cool content management system (CMS) using ckeditor which has you feeling all "rock star-like" when you suddenly realize that you can't have everyone hitting the SOURCE button on the toolbar (things can get pretty ugly...)

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! :)