FeaturesPluginsDocs & SupportCommunityPartners

Lesson 6: Editing The Wish List - Adding a New Wish The document applies to NetBeans 6.1 only

Contributed by Barbara Mityashina
June 27, 2008

Contents

Application Source Code from the Previous Lesson

Click here to download the source code that reflects the project state after the previous lesson is completed.

Lesson Scope

In this lesson you will expand the application functionality with two features:

The implementation will affect the editWishList.php file and a new file editWish.php will be created.

Adding a New Wish

The functionality supports the following use case:

  • The user logs in, switches to the editWishList.php page, and presses the Add Wish button. The editWish.php page opens.
  • On the editWish.php page, the user enters a description of a wish and possibly the date by when he/she wants it and presses the Save Changes button.
  • If the description is not filled in, an error message is displayed and the user returns to the editWish.php page.
  • Else, if a description is filled in, the application returns to the editWishList.php page with the list of wishes expanded with the new wish.

The implementation consists of the following steps:

Implementing the Add Wish Button

To In the editWishList.php file, enter the following HTML form:
<form name="addNewWish" action="editWish.php">
            <input type="submit" value="Add Wish"/>
        </form>
The form contains an Add Wish input field of the submit type. This field implements the Add Wish button. When the user clicks Add Wish, they are redirected to the editWishList.php page. Because no data is transferred through this form there is not used any Server Request method.

Implementing the Add Wish Form

The Add Wish form is displayed in two cases:

Displaying an Empty Input Form

Create the editWish.php file. To implement an empty form for entering a description and saving a new wish, in the editWish.php file enter the following code outside the <? php ?> block:
<form name="editWish" action="editWish.php" method="POST">
Describe your wish: <input type="text" name="wish" value="" /><br/>
When do you want to get it? <input type="text" name="dueDate" value=""/><br/>
<input type="submit" name="saveWish" value="Save Changes"/>
<input type="submit" name="back" value="Back to the List"/> </form>
The HTML input form contains:

  • Two empty text fields for entering the wish description and due date.
  • The texts to be printed next to the input fields.
  • A submit field that represents a Save Changes button
  • A submit field that represents a Back to the List button for returning to the editWishList.php page
  • The <br/> tags indicate compulsory line breaks to improve the look of the form.

Upon pressing the Add Wish button, the form submits the entered data to the same page, editWish.php, through the Request method POST.

Storing the Wish Data in an Array

When the user is redirected to the input form from the editWish.php page the form must still show the possibly entered dueDate. In the current implementation of the form both fields are always empty. To save the entered values, you need to present the data of a new wish in an array. The array will consist of two elements named description and due-date.

Enter the following code block right above the input form:
<?php
           if ($_SERVER["REQUEST_METHOD"] == "POST")
$wish = array("description" => $_POST["wish"],
"due_date" => $_POST["dueDate"]);
else
$wish = array("description" => "",
"due_date" => ""); ?>

The code checks which Request Server method was used for transferring the data and creates an array named $wish. If the method is POST, which means that the input form is displayed after unsuccessful attempt to save a wish with an empty description, the elements description and due_date accept the values transferred through POST.

If the method is not POST, which means that the input form is displayed for the first time after redirection form the editWishList.php page, the elements description and due_date are empty.

Note: In either case the description is empty. The difference is only in the dueDate.

Displaying the Input Form after Unsuccessful Save Attempt

Now you need to update the input form so that the values of its input fields are retrieved from the $wish array. Replace the lines in the HTML input form:

Describe your wish: <input type="text" name="wish"  value="" /><br/>
When do you want to get it? <input type="text" name="dueDate" value=""/><br/>
with:
Describe your wish: <input type="text" name="wish"  value="<?php echo $wish['description'];?>" /><br/>
When do you want to get it? <input type="text" name="dueDate" value="<?php echo $wish['due_date']; ?>"/><br/>

Verifying Wisher's Logon

In the editWish.php file, enter the following session handling code inside the <? php ?> block:
session_start();
if (!array_key_exists("user", $_SESSION)) {
header('Location: index.php');
exit;
}
The code:
  • Opens the $_SESSION array for retrieving data..
  • Verifies that the array $_SESSION contains an element with the identifier "user".
  • If the check fails, which means that the user is not logged on, redirects the application to the front index.php page and cancels the PHP processing.

To check that session handling works correctly, run the editWish.php file from the IDE. The editWishList.php page opens, because no user has been transferred to the editWish.page through a session.

Saving the New Wish

In order to implement the Save Wish functionality, you will need to add two more auxiliary functions to the WishDB class. One function must add a new record to the wishes table. The other function must convert dates into the format that the MySQL databases server supports.

Adding New Functions to the WishDB Class

Open the db.php file and add the following functions to the class WishDB:

Function format_date_for_sql

The function requires a string with a date as the input parameter. The function returns a date in the format that can be processed by the MySQL database server or null if the input string is empty.

To implement this functionality, enter the following code:
 function format_date_for_sql($date){
if ($date == "")
return "NULL";
else {
$dateParts = date_parse($date);
return $dateParts["year"]*10000 + $dateParts["month"]*100 + $dateParts["day"]
If the input string is empty, the code returns NULL. Otherwise, the internal date_parse function is called with the $date as the input parameter. The date_parse function returns an array that consists of three elements named $dateParts["year"], $dateParts["month"], and $dateParts["day"]. The final output string is constructed of the elements of the $dateParts array.
Function insert_wish
The function requires the wisher's id, a description of the new wish, and the due date of the wish as the input parameters and enters this data to the database in a new record. The function does not return and values.
function insert_wish($wisherId, $description, $duedate){
return mysql_query("INSERT INTO wishes (wisher_id, description, due_date)" .
" VALUES (" . $wisherId . ", '" . $description . "', "
. $this->format_date_for_sql($duedate) . ")"); }
The code calls the function format_date_for_sql to convert the entered due date into a format that can be processed by the MySQL server. Then the query INSERT INTO wishes (wisher_id, description, due_date)is executed to enter the new wish to the database.

Entering the New Wish Record in the Database

Now that you have developed the auxiliary functions, implement the Save Wish functionality.

Enter the following code inside the <? php?> block:
	   require_once("Includes/db.php");
    $db = new WishDB;
    $wisherId = $db->get_wisher_id_by_name($_SESSION["user"]);

    $wishDescriptionIsEmpty = false;
    if ($_SERVER["REQUEST_METHOD"] == "POST"){
        if (array_key_exists("back", $_POST)) {
           header('Location: editWishList.php' );
           exit;
        } else
         if ($_POST["wish"] == "") {
            $wishDescriptionIsEmpty =  true;
        }
			 else {
           $db->insert_wish($wisherId, $_POST["wish"], $_POST["dueDate"]);
           header('Location: editWishList.php' );
           exit;
        }
    }
	
The code enables using the db.php file, creates a new $db object of the class WishDB, retrieves the id of the wisher who is attempting to add a wish by calling the function get_wisher_id_by_name, and initializes the $wishDescriptionIsEmpty flag which will be later used for showing error messages.

Then it is checked that the Request method is POST, which means that the data was submitted from the form for entering the wish data on the editWish.php page itself.

Next, the code checks whether the $_POST array contains an element with the "back" key, which means that the Back to the List button was pressed before submitting the form. In this case the correct behavior is to return to the list of wishes without saving any data that is possibly entered in the fields. The code redirects the application to the editWishList.php page and stops the PHP processing.

Otherwise, if the $_POST array does not contain an element with the "back" key, this means that the data was submitted by pressing the Save Changes button. In this case it is necessary to validate whether the wish description is filled in. The code does it by checking whether the element with the "wish" key in the $_POST array is empty and, if the key is empty, changes the $wishDescriptionIsEmpty flag to true.

Otherwise, if the Back button was not pressed and the wish description is filled in, the code calls the function insert_wish with the wisher's id, the description, and the due date for the wish as the input parameters, redirects the user to the editWishList.php page, and stops the PHP processing.

Displaying Error Messages

If the user attempts to save a wish but has not entered a description for it, an error message must be displayed.
Enter the following <? php?> block inside the HTML input form, below the "wish" input field:
<?php
if ($wishDescriptionIsEmpty) echo "Please enter description<br/>";
?>
The error message is displayed if the $wishDescriptionIsEmpty flag is true. The flag is processed during the input form validation.

Returning to the Front index.php Page

The user should be able to return to the front page of the application at ny time by pressing a button.
To implement this functionality, enter the following HTML input form in the editWishList.php file:
<form name="backToMainPage" action="index.php">
<input type="submit" value="Back To Main Page"/>
</form>
The form redirects the user to the front index.php page upon pressing the Back to Main Page button.

Testing the Add Wish Functionality

  1. Run the application. On the index.php page, fill in the fields: in the Username field, enter "Tom", in the Password field, enter "tomcat".
    User Logs on to Edit Wish List
  2. Press the Edit My Wish List button. The editWishList.php page opens.
    Edit Wish List with the Add button added
  3. Press the Back to Main Page button. The index.php page opens.
  4. Logon as Tom and press the Edit My Wish List button again. The editWishList.php page opens.
  5. Press the Add Wish button. The editWish.php page opens. Fill in the form.
    The form for a new wish is filled in
    Press the Back to the List button. The editWishList.php page opens but the entered wish is not added.
  6. Press the Add Wish button again. The editWish.php page opens. Fill in the due date ad leave the description empty. Press the Save Changes button. The editWish.php page displays the input form with an error message and filled in due date.
  7. Press the Add Wish button again. The editWish.php page opens. Fill in the form and press the Save Changes button. The editWishList.php page shows an updated list of wishes.
    The new wish is added to the Wish List

Application Source Code after the Current Lesson Is Completed

Click here to download the source code that reflects the project state after the lesson is completed


  << Previous lesson

Next lesson >>

Back to the Tutorial main page

Back to the PHP Learning Trail

Companion
Projects:
MySQL Database Server   Open JDK: an Open SourceJDK   GlassFish Community: an Open Source Application Server    Mobile & Embedded Community    Open Solaris   java.net - The Source for Java Technology Collaboration   Virtual Box - full virtualizer  Open ESB - The Open Enterprise Service Bus Powered by