CRUD Application: Create New form

In previous article we looked at how to setup the routing rules to forward the HTTP requests to appropriate Controller method.

Create the Controller

Since Crud_Controller is the controller that will be handling all the requests for this app, let's go ahead and create it. So create a file crud_controller.php in app/controllers directory. Insert below code inside it.

namespace app\Controllers;

class Crud_Controller {
    
}

Add Controller method for /crud/add

Whenever someone visits the /crud/add page he'll see the user form for adding new user. Let's add the method for GET request to /crud/add. Since we are using CONTROLLER routing our method name will be get_add. As explained in previous article, get is the HTTP VERB and add is the first url segment after crud.

namespace app\Controllers;

class Crud_Controller {
    
    public function get_add() {
        
    }
    
}

Add User form

First we'll create a view file that contains the user form. Go ahead and create a new file form.php in app/views directory and insert below code in it.

<form>
    <h2><?php echo $title; ?></h2>
    
    <p>
    <?php echo Form::text("first_name", null, ["placeholder"=>"First Name"]); ?>
    <!-- Above will produce <input type="text" name="first_name" placeholder="First Name"> -->
    </p>
    
    <p>
    <?php echo Form::text("last_name", null, ["placeholder"=>"Last Name"]); ?>
    </p>
    
    <p>
    <?php echo Form::select("gender", ["male"=>"Male", "female"=>"Female"]); ?>
    <!-- Above will produce <select name="gender">
                                <option value="male">Male</option>
                                <option value="female">Female</option>
                            </select> -->
    </p>
    
    <p><input type="submit"></p>
</form>

Notice the use of Form::text() and Form::textarea().

Calling the view file

Let's call this view file in our controller method.

namespace app\Controllers;

class Crud_Controller {
    
    public function get_add() {
        return View::make("form", ["title"=>"Add New User"]);
    }
    
}

Now visiting /crud/add should display the user form

Validate received data and create user

Since we haven't added action attribute in form tag this form will submit to itself i.e it will POST to /crud/add. So this request will be handled by a method with name post_add. Let's go ahead and create it.

public method post_add() {
    
    //define validation rules
    $rules = [
            "first_name"    => "required",
            "last_name"     => "required",
            "gender"        => "required"
        ];
    
    //run validation
    $result = Validator::validate(Request::post(), $rules);
            
    //if validation fails then flash error message and user filled form details
    if( $result == false ) {
        Session::flash("errors", Validator::errors());
        return Request::redirect_to("crud/add")->with_inputs();    
    }
    
    //if validation successful then create new user
    $user_id = DB::table("users")->insert([
                            "first_name"    => Request::post("first_name"),
                            "last_name"     => Request::post("last_name"),
                            "gender"        => Request::post("gender")
                               ]);
                               
    return Request::redirect_to("crud/edit/".$user_id)->with(["success"=>"User added successfully"]);                               
}

For sake of simplicity rest of class methods are not shown.

Here we first define an array of rules for each field.

$rules = [
            "first_name"    => "required",
            "last_name"     => "required",
            "gender"        => "required"
        ];

We then run the validation on all the data received. Request::post(), when called without any parameters, returns entire $_POST array

$result = Validator::validate(Request::post(), $rules);

The validator will pick up the appropriate fields that need to be validated and run validation on them. If validation fails then validate() returns a boolean false. All errors can be captured using Validator::errors() which returns an array of errors.

Pre populating form fields if errors in validation

You don't have to do anything to pre populate the form details on validation failure. The Form_Helper class will do this for you. If validation fails then below is code that is exectued

return Request::redirect_to("crud/add")->with_inputs();

Here with_input() method will flash all the user entered form data to Session. Since we have used Form::text() and Form::select(), the user entered data will be pre populated. The Form_Helper class first checks if the field value is set in session. If set then it sets the value of the field to the session value. You may verify this by leaving any one of the form field empty and filling the rest.