Administrator Recipe: Modifying User Profiles

In the best of all possible worlds, an administrator would never have to see a user's record much less alter it. Very few administrators are lucky enough to live in that world, however, so an administrative-strength edit record application is needed.

In addition to the functionality we've already seen in the user-oriented edit record page, the administrator also requires the capability to alter a user's access group level and to delete the record altogether. Moreover, to maintain security, the SQL statements involved in this page are somewhat more complex than those used in the user version.

Step 1: Implement Login Design

Let's begin by building the basic page.

  1. Open a new dynamic page, either constructing one by hand or deriving one from a template.

    graphics/book.gif In the UserLogin folder, locate the folder for your server model and open the edit_user page found there.

  2. Add a table to the content region of your page to contain the interface elements for the application.

    graphics/book.gif From the Snippets panel, drag the Recipes > UserLogin > Wireframes > Edit User - Wireframe snippet into the Content editable region.

  3. Within the table, insert the form and any necessary form elements for the application. You'll need five text fields one for each of the fields (First Name, Last Name, User Name, Password, and Email Address) and a select list to hold the Group Access data. In addition, this application requires three buttons: Update, Delete, and Cancel.

    graphics/book.gif Place your cursor in the row below the words EDIT USER in the second cell and insert the Recipes > UserLogin > Forms > Edit User - Form snippet [r1-23].


    Figure r1-23.

    graphics/03fig23.jpg


  4. ColdFusion and PHP Users: Both of these server models require a unique record ID for the Update Record server behavior to work properly. In these situations, a Hidden Form Field is used to convey the needed data.

    graphics/cf.gif graphics/php.gif ColdFusion and PHP developers should drag a Hidden Form Field from the Forms category of the Insert bar and name it UserID.

  5. Save the page.

Step 2: Add Database Components

The Edit User page displays when a link is selected in the Manage Users page. The link selected contains a URL parameter, ID, which we will use on this page to filter one of the two recordsets required. The second recordset gets the values necessary to dynamically fill the Access Group list.

  1. From the Server Behaviors panel, choose Add (+) and select Recordset (Query).

  2. Using the simple view of the Recordset dialog, give the recordset a meaningful name.

    graphics/book.gif Enter Users in the Recordset field.

  3. Choose the connection for your data source.

    graphics/book.gif Select Recipes from the Connection list.

  4. Choose the desired table.

    graphics/book.gif Select Users (users for PHP) from the Table list.

  5. Keep the Columns option set to All.

  6. In the Filter area of the Recordset dialog, set the four Filter list elements like this:

    graphics/108fig01.gif

  7. Leave the Sort option set to None and then click OK to confirm your choices and close the dialog.

  8. Save the page.

The second recordset, AccessGroups, is just as straightforward.

  1. From the Bindings panel, choose Add (+) and select Recordset (Query).

  2. In the Recordset dialog's simple view, enter the desired name, such as AccessGroups.

  3. Select your data source connections.

    graphics/book.gif Choose Recipes from the Connections list.

  4. Select the table containing the user information.

    graphics/book.gif Choose AccessGroups from the Table list.

  5. Click OK to close the dialog.

Note

The second recordset, AccessGroups, is an exact duplicate of the one built in the Manage User page. If that page has already been developed, you can copy and paste the recordset. To copy a recordset, select it in the Bindings panel and, from the panel Options menu, select Copy. To paste a recordset, switch to the page where the recordset is needed, select the Bindings panel Options menu, and choose Paste. Your recordset should appear in the Bindings panel. Please note that standard Copy and Paste commands will not work with recordsets.


Step 3: Data Binding Process

The data-binding procedure for this page is identical to the one followed on the edit profile page with one exception. The Access Group form element a drop-down list must be bound to data from the accessgroup table. ColdFusion and PHP users will also need to bind the current record ID to the hidden form field.

  1. In the Bindings panel, make sure the Users recordset entry is expanded so that all data columns are displayed.

  2. Drag each of the following data columns over the corresponding text field:

    • Drag column UserFirstName to field FirstName.

    • Drag column UserLastName to field LastName.

    • Drag column UserName to field UserName.

    • Drag column Password to field Password.

    • Drag column UserEmail to field EmailAddress.

  3. Leave the default formatting for all dynamic text fields.

    Let's now set up the list element to populate dynamically.

  4. Select the Access Group list element.

  5. In the Property inspector, click the Dynamic button to open the Dynamic List/Menu dialog.

  6. Verify that the AccessGroup list element is selected in the Menu list.

  7. From the Options From Recordset list, choose AccessGroups.

  8. Set the Values list to AccessGroupID.

  9. Set the Labels (what the user sees) to AccessGroupNames.

  10. In the Select Value Equal To field, select the lightning icon to open the Dynamic Data dialog.

  11. Expand the Users recordset, if necessary, and choose the UserAccess (AccessGroup for PHP) field.

    Linking the selected value to the UserAccess/AccessGroup field, the record will initially display the current user group level while allowing the administrator to adjust it if necessary.

  12. Click OK to close the Dynamic Data dialog. After you've confirmed your selections, click OK in the Dynamic List/Menu dialog to close it.

ColdFusion and PHP users need to complete one additional set of steps in binding dynamic data to the hidden form field previously inserted.

  1. Select the desired form element.

    graphics/book.gif Choose the UserID hidden form element.

  2. Bind the current record ID to the element.

    graphics/book.gif Choose the lightning bolt symbol next to the Value field in the Property inspector to open the Dynamic Data dialog.

    graphics/book.gif In the Dynamic Data dialog, expand the Users recordset and choose UserID.

    graphics/book.gif Click OK to close the dialog.

  3. Save your page.

Step 4: Update User Profile

Now we're ready to insert the Update Record server behavior. As part of the procedure, we'll set the behavior to display the Manage User page after the update is complete so that the administrator can continue working.

For ASP
  1. From the Server Behaviors panel, choose Add (+) and select Update Record to display the dialog.

  2. Select the connection to the data source.

    graphics/book.gif Choose Recipes from the Connection list.

  3. Choose the table containing the user data.

    graphics/book.gif From the Table To Update list, select Users.

  4. Select the recordset from which to get data source fields.

    graphics/book.gif Set the Select Record From field to Users.

  5. Set the Primary Key for the recordset.

    graphics/book.gif From the Unique Key Column list, choose UserID and make sure that the Numeric option is checked.

  6. Enter the page you want the users to see after successfully registering.

    graphics/book.gif In the After Inserting, Go To field, select the Browse button and locate the user_manager file for your server model.

  7. Choose the form on the page from which the values are to be taken.

    graphics/book.gif Set the Get Values From field to EditUser.

  8. For the form elements shown in the list, set each one to its equivalent in the data source. All form elements should be submitted as text:

    graphics/book.gif Set form element FirstName to field UserFirstName as Text.

    Set form element Lastname to field UserLastName as Text.

    Set form element UserName to field UserName as Text.

    Set form element Password to field UserPassword as Text.

    Set form element EmailAddress to field UserEmail as Text.

    Set form element AccessGroup to field UserAccess as Numeric.

  9. When you're done, click OK to close the dialog and insert the behavior.

  10. Save your page.

For ColdFusion and PHP
  1. From the Server Behaviors panel, choose Add (+) and select Update Record.

  2. In the Update Record dialog, choose the current form.

    graphics/book.gif Select Users from the Submit Values From list.

  3. Select your data source from the list.

    graphics/book.gif Choose Recipes from the Data Source list.

  4. Enter your username and password, if needed.

  5. Select the table in the data source to insert into from the list.

    graphics/book.gif Choose Users from the Insert Into Table list.

  6. Set the data source fields to their corresponding form elements.

    graphics/book.gif As the Primary Key, UserID selects the record using FORM.UserID as a Numeric (Integer in PHP) type.

    Set UserAccess to get its value from the FORM.AccessGroup from element as Numeric (Integer in PHP).

    Set UserFirstName to get its value from the FORM.FirstName form element as Text.

    Set UserLastName to get its value from the FORM.Lastname form element as Text.

    Set UserName to get its value from the FORM.UserName form element as Text.

    Set UserPassword to get its value from the FORM.Password form element as Text.

    Set UserEmail to get its value from the FORM.EmailAddress form element as Text.

    Make sure UserRegDate does not get a value.

  7. In the After Inserting, Go To field enter the path to the file you want displayed after the record is updated.

    graphics/book.gif In the After Inserting, Go To field, select the usermanager file for your server model.

  8. Check your entries to verify that they are correct; if so, click OK.

  9. Save your page.

Step 5: Add a Delete Command

If you wanted to add a separate page to delete a record, you could use Dreamweaver's standard Delete Record server behavior. However, if, as this application does, you want to combine a couple of administrative tasks such as updating and deleting records you have to take a different approach.

One method is to create a delete command. A command is a specialized SQL statement that, among other things, can delete, insert, or update records. Once the command is created using the Dreamweaver interface, the code must be moved above the Update Record behavior. The final step is to wrap the delete code in a conditional block also called an If statement so that it executes only when the Delete button is selected.

For ASP
  1. From the Bindings panel, choose Add (+) and select Command.

    The Command dialog displays [r1-24].


    Figure r1-24.

    graphics/03fig24.gif


  2. Enter an appropriate name for the command.

    graphics/book.gif Enter DeleteCommand in the Name field.

  3. Choose your data source connection from the list.

    graphics/book.gif Select Recipes from the Connections list.

  4. Choose Delete for the Command Type.

  5. Enter the following code in the SQL field:

     
     DELETE FROM Users WHERE UserID = IDParam 
     
  6. In the Variables section, select Add (+) and enter IDParam under the Name column.

  7. In the Run-Time Value column, enter Request.Form("MM_recordId") and click OK when you're done.

    Inserting the command creates two code blocks. We'll need to move one of them so that the delete command is processed before the update command.

  8. In Code view, find the code block for the delete command. It will look like this:

    graphics/vb.gif

    [View full width]

     <% set DeleteCommand = Server.CreateObject("ADODB.Command") DeleteCommand.ActiveConnection = MM_Recipes_VB_STRING DeleteCommand.CommandText = "DELETE FROM Users WHERE UserID graphics/ccc.gif = " +Replace(DeleteCommand__IDParam, "'", "''") + "" DeleteCommand.CommandType = 1 DeleteCommand.CommandTimeout = 0 DeleteCommand.Prepared = true DeleteCommand.Execute() %> 

    graphics/js.gif

     <% var DeleteCommand = Server.CreateObject("ADODB.Command"); DeleteCommand.ActiveConnection = MM_Recipes_STRING; DeleteCommand.CommandText = "DELETE FROM Users WHERE UserID  "+ DeleteCommand__IDParam.replace(/'/g, "''") + " "; DeleteCommand.CommandType = 1; DeleteCommand.CommandTimeout = 0; DeleteCommand.Prepared = true; DeleteCommand.Execute(); %> 

  9. Cut the code block and move it near the top of the page after this related code block:

    graphics/vb.gif

     <% if(Request("MM_recordId") <> "") then DeleteCommand__IDParam = Request("MM_recordId") %> 

    graphics/js.gif

     <% if(String(Request("MM_recordId")) != "undefined") { DeleteCommand__IDParam = String(Request("MM_recordId"));} %> 

Now all that remains to complete the delete command is to make sure it is only executed when the user selects the Delete button on the form. If this step is not taken, the delete command will run when this page was loaded not a desirable circumstance. To avoid such a disastrous situation, we'll wrap the two delete command code blocks within an If statement.

  1. In Code view, locate the two adjacent delete command code blocks.

    graphics/book.gif Select the two code blocks to prepare for inserting the snippet.

  2. Insert the following code:

    graphics/book.gif From the Snippets panel, open the Recipes > UserLogin > Custom Code folder for your server model and insert the Delete Button - If Statement snippet.

    Before:

    graphics/vb.gif

     <% if (cStr(Request.Form("Delete"))<>"")  then %> 

    After:

     
     <%   Response.Redirect("user_manager.asp") end if %> 
     

    Before:

    graphics/js.gif

     <% if (String(Request("Delete"))!="undefined")  { %> 

    After:

     
     <%   Response.Redirect("user_manager.asp"); } %> 
     

You can, of course, change the page to redirect to after the delete is completed, if your page is named something different than user_manager.asp.

For ColdFusion
  1. From the Bindings panel, choose Add (+) and select Recordset (Query).

    Unlike with the ASP server models, there is no separate user interface in ColdFusion for Commands, and the Recordset dialog is used.

  2. If the simple view is displayed, select Advanced.

  3. In the Name field, enter an appropriate name.

    graphics/book.gif Enter DeleteOperation in the Name field.

  4. Choose your data source connection from the list.

    graphics/book.gif Select Recipes from the Data Source list.

  5. If necessary, enter the User Name and Password in their respective fields.

  6. Enter the following code in the SQL field:

     
     DELETE FROM Users WHERE UserID = #FORM.UserID# 
     
  7. In the Page Parameters section, select Add (+) to display the Add Parameter dialog.

  8. In the Add Parameter dialog, enter FORM.UserID in the Name field.

  9. In the Default Value fields, enter 0 and click OK to close the Add Parameter dialog.

  10. When you're done, click OK to close the Recordset dialog.

    Now all that remains to complete the delete command is to make sure it is only executed when the user selects the Delete button on the form. To do this, we'll wrap the two delete command code blocks within an If statement.

  11. In Code view, find the code block for the delete command. It will look like this:

     
     <cfquery name="DeleteCommand" datasource="Recipes">   DELETE FROM Users WHERE USERID = #FORM.UserID# </cfquery> 
     

    graphics/book.gif Select the two code blocks to prepare for inserting the snippet.

  12. Insert the following code:

    graphics/book.gif From the Snippets panel, insert the Recipes > UserLogin > Custom Code-CF > Delete Button - If Statement snippet.

    Before:

    graphics/cf.gif

     <cfif IsDefined("form.DeleteUser")> 

    After:

     
     <cflocation url="user_manager.cfm" addtoken="no"> </cfif> 
     

You can, of course, change the page to redirect to after the delete is completed, if your page is named something different from user_manager.cfm.

For PHP

Adding a Delete button in PHP is simpler than in other server models and requires the addition of a single function.

  1. In Code view, position your cursor at the end of the opening line that begins <?php require_once...> and press Enter (Return).

  2. Enter the following code:

    graphics/book.gif Insert the Recipes > UserLogin > Custom Code-PHP > Edit User Delete User snippet.

    graphics/php.gif

    [View full width]

     <?php if ((isset($_POST['Delete'])) && ($_POST['Delete']=="Delete")) {  mysql_select_db($database_Recipes_PHP, $Recipes_PHP);  $deleteSQL = "DELETE FROM users WHERE User0" width="14" height="9" align="left" src="/books/2/711/1/html/2/files/ccc.gif" alt="graphics/ccc.gif">.$_POST['UserID'];  $deleteRS = mysql_query($deleteSQL,$Recipes_PHP);  header("Location: user_manager.php"); } ?> 

  3. Save the page.

Step 6: Cancel Editing Process

As we did on the Update Record page, we'll use some JavaScript code to implement the Cancel button.

  1. Select the Cancel form button.

  2. From the Behaviors panel, select Add (+) and choose Call JavaScript.

  3. In the Call JavaScript dialog, enter the following code:

     
     history.back(); 
     
  4. When you're done, click OK to close the dialog.

  5. Save the file.

Step 7: Validate the User Name

One final aspect still needs to be addressed. Since this page can potentially alter the username, we must make sure that the new name chosen is unique. Unfortunately, we cannot just apply the Check User Name server behavior as we did in the register_user page because this particular server behavior requires that a variable, MM_flag, be set to MM_insert, and an update page sets MM_flag to MM_update.

The solution is to copy the Macromedia code used on the register_user page and adapt it to our needs. In all, three changes will need to be made. While these modifications will give us the functionality we need, it will also prevent further changes to the Update Record server behavior through the dialog. This is indicated by a red exclamation mark next to the server behavior in the Server Behaviors panel.

  1. Open the register_user page in Code view and copy the following code block:

    graphics/vb.gif

    [View full width]

     <% ' *** Redirect if username exists MM_flag="MM_insert" If (CStr(Request(MM_flag)) <> "") Then   MM_dupKeyRedirect="register_user.asp?repeat=true"   MM_rsKeyConnection=MM_Recipes_VB_STRING   MM_dupKeyUsernameValue = CStr(Request.Form("UserName"))   MM_dupKeySQL="SELECT UserName FROM Users WHERE UserName='" graphics/ccc.gif &  MM_dupKeyUsernameValue & "'"   MM_adodbRecordset="ADODB.Recordset"   set MM_rsKey=Server.CreateObject(MM_adodbRecordset)   MM_rsKey.ActiveConnection=MM_rsKeyConnection   MM_rsKey.Source=MM_dupKeySQL   MM_rsKey.CursorType=0   MM_rsKey.CursorLocation=2   MM_rsKey.LockType=3   MM_rsKey.Open   If Not MM_rsKey.EOF Or Not MM_rsKey.BOF Then     ' the username was found - can not add the requested graphics/ccc.gif username     MM_qsChar = "?"     If (InStr(1,MM_dupKeyRedirect,"?") >= 1) Then MM_qsChar graphics/ccc.gif = "&"     MM_dupKeyRedirect = MM_dupKeyRedirect & MM_qsChar & graphics/ccc.gif "requsername=" & MM_dupKeyUsernameValue     Response.Redirect(MM_dupKeyRedirect)   End If   MM_rsKey.Close End If %> 

    graphics/js.gif

    [View full width]

     <% // *** Redirect if username exists var MM_flag="MM_insert"; if (String(Request(MM_flag)) != "undefined") {   var MM_dupKeyRedirect="register_user.asp?repeat=true";   var MM_rsKeyConnection=MM_Recipes_STRING;   var MM_dupKeyUsernameValue = String(Request.Form("UserName"));   var MM_dupKeySQL = "SELECT UserName FROM Users WHERE graphics/ccc.gif UserName='" + MM_dupKeyUsernameValue + "'"   var MM_adodbRecordset = "ADODB.Recordset";   var MM_rsKey = Server.CreateObject(MM_adodbRecordset);   MM_rsKey.ActiveConnection = MM_rsKeyConnection;   MM_rsKey.Source = MM_dupKeySQL;   MM_rsKey.CursorType=0;   MM_rsKey.CursorLocation=2;   MM_rsKey.LockType=3;   MM_rsKey.Open();   if (!MM_rsKey.EOF || !MM_rsKey.BOF) {     // the username was found - can not add the requested graphics/ccc.gif username     var MM_qsChar = "?";     if (MM_dupKeyRedirect.indexOf("?") >= 0) MM_qsChar = "&";     MM_dupKeyRedirect = MM_dupKeyRedirect + MM_qsChar + graphics/ccc.gif "requsername=" + MM_dupKeyUsernameValue;     Response.Redirect(MM_dupKeyRedirect);   }   MM_rsKey.Close(); } %> 

    graphics/cf.gif

    [View full width]

     <cfif IsDefined("FORM.UserName")>   <cfquery name="MM_search" datasource="Recipes">   SELECT UserName FROM Users WHERE UserName='#FORM.UserName#'   </cfquery>   <cfif MM_search.RecordCount GTE 1>     <cflocation url="register_user.cfm?failed= graphics/ccc.gif true&requsername=#FORM.UserName#" addtoken="no">   </cfif> </cfif> 

    graphics/php.gif

    [View full width]

     <?php // *** Redirect if username exists $MM_flag="MM_insert"; if (isset($_POST[$MM_flag])) {   $MM_dupKeyRedirect="register_user.php?repeat=true";   $loginUsername = $_POST['UserName'];   $LoginRS__query = "SELECT UserName FROM users WHERE graphics/ccc.gif UserName='" . $loginUsername . "'";   mysql_select_db($database_Recipes_PHP, $Recipes_PHP);   $LoginRS=mysql_query($LoginRS__query, $Recipes_PHP) or die graphics/ccc.gif(mysql_error());   $loginFoundUser = mysql_num_rows($LoginRS);   //if there is a row in the database, the username was graphics/ccc.gif found - can not add the requested username   if($loginFoundUser){     $MM_qsChar = "?";     //append the username to the redirect page     if (substr_count($MM_dupKeyRedirect,"?") >=1) $MM_qsChar graphics/ccc.gif = "&";     $MM_dupKeyRedirect = $MM_dupKeyRedirect . $MM_qsChar  graphics/ccc.gif."requsername=".$loginUsername;     header ("Location: $MM_dupKeyRedirect");     exit;   } } ?> 

  2. Open the edit_user page and paste the code after the complete delete command sequence.

    Make sure you paste the code after the close of the If statement where the redirection occurs.

  3. Near the top of the pasted code block, change the following line from

     
     MM_flag=MM_insert 
     

    to

     
     MM_flag=MM_update 
     

    This change allows the server behavior to work with a record update.

  4. Make a second change from

     
     MM_dupKeyRedirect="register_user" 
     

    to

     
     MM_dupKeyRedirect="edit_user" 
     

    This modification specifies the proper page for the redirect operation.

  5. Locate the line that starts with the following code:

    graphics/vb.gif

     var MM_dupKeySQL 

    graphics/js.gif

     var MM_dupKeySQL 

    graphics/cf.gif

     var MM_dupKeySQL

    graphics/php.gif

    $LoginRS__query 

  6. Append the following to the end of the code line:

    graphics/vb.gif

     + Request("MM_recordId") 

    graphics/js.gif

     + Request("MM_recordId") 

    graphics/cf.gif

    + Request("MM_recordId") 

  7. PHP users should remove the final three characters on the line (single quote, double quote, and semicolon) and add the following:

    graphics/php.gif Change:

     
     "'"; 
     

    to:

     
     "' AND UserID != ".$_POST['UserID']; 
     

    With this change, the SQL statement ignores the current record. This action is necessary in case the administrator made other changes to the record other than the username. Without this modification, the SQL statement would identify the current record as the duplicate and the update would not take place.

  8. Additionally, PHP users need to locate the code line that ends as follows:

    graphics/php.gif

    "requsername=".$loginUsername; 

    Remove the semicolon at the end and append the following:

    graphics/php.gif

    ."&font-weight:normal" value="9">

    Save the page when your edits are complete.



    Macromedia Dreamweaver MX 2004 Web Application Recipes
    Macromedia Dreamweaver MX 2004 Web Application Recipes
    ISBN: 0735713200
    EAN: 2147483647
    Year: 2003
    Pages: 131

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net