Fuel PHP Example Tutorial Part 3 (Crud MVC Application)

FUEL PHP EXAMPLE TUTORIAL PART 3 (CRUD MVC Application)


Please Subscribe Youtube| Like Facebook | Follow Twitter

Introduction

In this article we will built CRUD MVC Application in Fuel PHP Framework. 

Tips

ArticleURL
FUEL PHP Example Tutorial Part 1 (Config and Run)link
FUEL PHP EXAMPLE TUTORIAL PART 2 (MVC Sample Application)link
FUEL PHP EXAMPLE TUTORIAL PART 3 (CRUD MVC Application)link

Our Example (Fuel PHP CRUD MVC Application)

In our example we will setup CRUD MVC Application. We will perform CRUD Operation of Student Entity. Which allows user to create, read, update, delete and list record of Student Entity.

Requirements:

  1. PHP SERVER (XAMP, WAMP, Laragon)
  2. FuelPHP Framework

Note: First you need to configure FuelPHP Project. You can follow this article to set it up. After that it is recommended to follow this article to understand FuelPHP and MVC pattern of this Framework.

Steps

Follow below steps

1 Configure Database And Application Settings

2 Coding

3 Run Application

1 Configure Database And Application Settings

Step 1 is already defined in this article. Follow it from there.

2 Coding

Model

Create new php File named “student.php” inside FuelSample\fuel\app\classes\model

Add below code to student.php file

<?php

class Model_Student extends Orm\Model
{
    protected static $_table_name = 'student'; 
    protected static $_properties = array ('id','roll_no','name');

}

Model_Student class represent our Table student and $_properties correspond to columns of our Table student

Template

Create new php File named “template.php” inside FuelSample\fuel\app\views

Add below code to template.php file

<!DOCTYPE html>
<html>
<head>
</head>
<body>
	<header>
            <h1>Header Template</h1>  
            <h3><?php echo $title; ?></h3>            
	</header>
    
	<div class="container">		 
		<?php echo $content; ?>		
	</div>
    
        <footer>
                <h2>Footer Template</h2>   
	</footer>
</body>
</html>

Template is used to display common layout elements of Application to all our Web Pages i.e header, footer, navigation. It also Allows to set section/content of corresponding view page, which will be embedded or set through $title and $content variable.

<?php echo $title; ?> will set title of corresponding view page.

<?php echo $content; ?> will set content of corresponding view page.

Controller

Create new php File named “student.php” inside FuelSample\fuel\app\classes\controller

Add below code to student.php file

<?php

class Controller_Student extends Controller_Template
{
    public function action_index()
    {  
        $data = array(); 
        $data['Students'] = Model_Student::find('all');
        $this->template->title="Student List";
        $this->template->content=View::forge('student/index',$data,false);
    }
    
    public function action_view($id)
    {
        $Student = Model_Student::find('first',
                array(
                    'where' => array(
                        'id' =>  $id
                    )
                )
                );
        
        if($Student==null){
             throw new HttpNotFoundException();
        }
        $data=array('Student' => $Student);
        $this->template->title="View Student";
        $this->template->content=View::forge('student/view',$data,false);
    }
    
    public function action_create()
    {
        $data = array();
        
        //button create clicked
        if(Input::post('create')){
            
            $val = Validation::forge();

            $val->add('roll_no', 'Roll No')->add_rule('required')
                                           ->add_rule('numeric_min', 1)
                                           ->add_rule('numeric_max', 100);

            $val->add('name', 'Name')->add_rule('required')
                                           ->add_rule('min_length', 3)
                                           ->add_rule('max_length', 10);
            // validation Succeed
            if($val->run()){
                // get an array of successfully validated fields => value pairs
                $validatedFields  = $val->validated();
                //create student model and save to db    
                $Student = new Model_Student();
                $Student->roll_no  = $validatedFields['roll_no'];
                $Student->name   = $validatedFields['name'];
                $Student->save();
                //redirect to Student List
                Response::redirect('/fuelsample/public/student');
            }
            // validation failed
            //redirect back with error message
            else{
                // get an array of validation errors as field => error pairs
                $data['errors']= $val->error();
                $this->template->title="Create Student";
                $this->template->content=View::forge('student/create',$data,false);
            }

        }
        // show form on new page load
        else{
            $this->template->title="Create Student";
            $this->template->content=View::forge('student/create',$data,false);     
        }
    }
    
    public function action_edit($id)
    {
        $data = array();
        //check student exist in db or not
        $Student = Model_Student::find('first',
        array(
            'where' => array(
                'id' =>  $id
            )
        )
        );
        
        if($Student==null){
             throw new HttpNotFoundException();
        }
        
        //button update clicked
        if(Input::post('update')){
            
            $val = Validation::forge();

            $val->add('roll_no', 'Roll No')->add_rule('required')
                                           ->add_rule('numeric_min', 1)
                                           ->add_rule('numeric_max', 100);

            $val->add('name', 'Name')->add_rule('required')
                                           ->add_rule('min_length', 3)
                                           ->add_rule('max_length', 10);
            // validation Succeed
            if($val->run()){
                // get an array of successfully validated fields => value pairs
                $validatedFields  = $val->validated();
                //update existing student model values and save to db    
                $Student->roll_no  = $validatedFields['roll_no'];
                $Student->name   = $validatedFields['name'];
                $Student->save();
                //redirect to Student List
                Response::redirect('/fuelsample/public/student');
            }
            // validation failed
            //redirect back with error message
            else{
                // get an array of validation errors as field => error pairs
                //set error
                $data['errors']= $val->error();
                //set student value to last filled values
                $Student->roll_no = Input::post('roll_no');
                $Student->name = Input::post('name');
                $data['Student']= $Student;
                $this->template->title="Edit Student";
                $this->template->content=View::forge('student/edit',$data,false);
            }

        }
        // show form on new page load
        else{
            //set student from db
            $data['Student']= $Student;
            $this->template->title="Edit Student";
            $this->template->content=View::forge('student/edit',$data,false);     
        }
    }
    
    public function action_delete($id)
    {
        //check student exist in db or not
        $Student = Model_Student::find('first',
        array(
            'where' => array(
                'id' =>  $id
            )
        )
        );
        
        if($Student==null){
             throw new HttpNotFoundException();
        }
        //delete student
        $Student->delete();
        //redirect to Student List
        Response::redirect('/fuelsample/public/student');
    }
}

Controller_Student class represent Controller of student.

Controller Name after _ i.e Student and method name after _ i.e index resolves to url student/index So whole url to fire action_index() method of Student Controler would resolve to

http://localhost/fuelsample/public/student/index

Similarly To fire action_view($id) method of Student Controler for viewing record of student whose id is 1 then url would resolve to

http://localhost/fuelsample/public/student/view/1

where $id=1 i.e action_view($id=1)

You can change app root url of appliaction using virtual host settings in Apache server.

In action_index() function, we are retrieving list of all student from student table through Model_Student::find() function and saving it inside array $data[‘Students’] and passing that $data array to our view student/index.

In action_view($id) function, we are retrieving student $id from parameter url base on that we are fetching student from student table through Model_Student::find() function and saving it inside array $data[‘Student’] and passing that $data array to our view student/view.

In action_create() function, first we are displaying form for user to input details. We can check whether user press submit button or not by Input::post(‘create’) . Then when user submit form by pressing submit button, we will validate form fields,

i.e roll_no required and value range 1-100 name required and char limit range 3 to 10

If validation fails then we redirect back user to create page with errors.

If validation succeed then we are saving validated values of Student Table to database. And redirect to student list page

In action_edit($id) function, first we are displaying student form with specified id for user to update details. We can check whether user press submit button or not by Input::post(‘update’) . Then when user submit form by pressing submit button, we will validate form fields,

If validation fails then we redirect back user to edit page with errors.

If validation succeed then we are saving validated values of Student Table to database. And redirect to student list page

In action_delete($id) function, we are deleting student with specified id.

View

Create new folder “student” inside FuelSample\fuel\app\view

All the views of student (index,create,edit,view) will be placed here inside student folder

Create new php File named “index.php” inside FuelSample\fuel\app\view\student

Add below code to index.php file

<h2 ><a href="/fuelsample/public/student/create">Create</a> </h2>
<style>
table, th, td {
  border: 1px solid black;
}
</style>
<table  >
    <tr><th>Student Id</th><th>Student Roll No</th><th>Student Name</th><th>Action</th><tr>
<?php foreach ($Students  as $Student): ?>
    <tr>
    <td><?php echo  $Student->id;  ?> </td> 
    <td><?php echo  $Student->roll_no;  ?></td> 
    <td><?php echo  $Student->name; ?> </td> 
    <td>
        <a href="/fuelsample/public/student/view/<?php echo  $Student->id; ?> " >View Details</a>
        <a href="/fuelsample/public/student/edit/<?php echo  $Student->id; ?>" >Edit Details</a>
        <a href="/fuelsample/public/student/delete/<?php echo  $Student->id; ?>"  >Delete</a>
    </td> 
    </tr>
<?php endforeach; ?>
</table>

In index.php we are looping through $Students variable which was passed through action_index() function. We are printing corresponding rows of student table inside html table.

Create new php File named “view.php” inside FuelSample\fuel\app\view\student

Add below code to view.php file

<p>Student ID : <?php echo  $Student->id;  ?> </p> 
<p>Student Roll No : <?php echo  $Student->roll_no;  ?></p>
<p>Student Name : <?php echo  $Student->name; ?></p>
<a href="/fuelsample/public/student/" >Back To List</a>

In view.php we are looping through $Student variable which was passed through action_view() function. We are printing corresponding values of student record.

Create new php File named “create.php” inside FuelSample\fuel\app\view\student

Add below code to create.php file

<?php
if(isset($errors)) {  
   echo '<ul style="color:red"> Errors ';

    foreach($errors as $error)
    {
        echo '<li>'. $error .'</li>';
    }

   echo '</ul>';
} 
?> 

<?php echo Form::open("/fuelsample/public/student/create"); ?>

<div >
<?php echo Form::label('Roll No',"roll_no"); ?>
<?php echo Form::input('roll_no',
        Input::post('roll_no',isset($Student)?$Student->roll_no:''));
?>
</div>

<div >
<?php echo Form::label('Name',"name"); ?>
<?php echo Form::input('name',
        Input::post('name',isset($Student)?$Student->name:''));
?>
</div>

<div>
<?php echo Form::submit('create'); ?>
</div>

<?php echo Form::close();?>

<a href="/fuelsample/public/student/" >Back To List</a>

In create.php we are creating form, displaying error if validation fails after form submit. After form submission action_create() function will be fired for saving student in database.

Create new php File named “edit.php” inside FuelSample\fuel\app\view\student

Add below code to edit.php file

<?php
if(isset($errors)) {  
    echo '<ul style="color:red"> Errors ';

    foreach($errors as $error)
    {
        echo '<li>'. $error .'</li>';
    }

   echo '</ul>';
} 
?> 

<?php echo Form::open('/fuelsample/public/student/edit/'.$Student->id); ?>

<div >
<?php echo Form::label('Roll No',"roll_no"); ?>
<?php echo Form::input('roll_no',
        Input::post('roll_no',isset($Student)?$Student->roll_no:''));
?>
</div>

<div >
<?php echo Form::label('Name',"name"); ?>
<?php echo Form::input('name',
        Input::post('name',isset($Student)?$Student->name:''));
?>
</div>

<div>
<?php echo Form::submit('update'); ?>
</div>

<?php echo Form::close();?>

<a href="/fuelsample/public/student/" >Back To List</a>

In edit.php we are populating student form with values from database (through $Student variable which was passed through action_edit() function). We will display error if validation fails after form submit. After form submission action_edit() function will be fired for saving student in database.

Whole Code

db.php filefrom FuelSample\fuel\app\config\development\db.php

<?php
/**
 * Fuel is a fast, lightweight, community driven PHP 5.4+ framework.
 *
 * @package    Fuel
 * @version    1.8.2
 * @author     Fuel Development Team
 * @license    MIT License
 * @copyright  2010 - 2019 Fuel Development Team
 * @link       https://fuelphp.com
 */

/**
 * -----------------------------------------------------------------------------
 *  Database settings for development environment
 * -----------------------------------------------------------------------------
 *
 *  These settings get merged with the global settings.
 *
 */

return array(
	'default' => array(
		'connection' => array(
			'dsn'      => 'mysql:host=localhost;dbname=fuel_sample',
			'username' => 'root',
			'password' => '',
		),
	),
);

config.php file from FuelSample\fuel\app\config\config.php

<?php
/**
 * Fuel is a fast, lightweight, community driven PHP 5.4+ framework.
 *
 * @package    Fuel
 * @version    1.8.2
 * @author     Fuel Development Team
 * @license    MIT License
 * @copyright  2010 - 2019 Fuel Development Team
 * @link       https://fuelphp.com
 */

return array(
	/**
	 * -------------------------------------------------------------------------
	 *  The base URL of the application
	 * -------------------------------------------------------------------------
	 *
	 *  You can set this to a full or relative URL:
	 *
	 *      'base_url' => '/foo/',
	 *      'base_url' => 'http://foo.com/'
	 *
	 *  It MUST contain a trailing slash (/).
	 *
	 *  Set this to null to have it automatically detected.
	 *
	 */

	// 'base_url' => null,

	/**
	 * -------------------------------------------------------------------------
	 *  Any suffix that needs to be added to
	 * -------------------------------------------------------------------------
	 *
	 *  URL's generated by Fuel. If the suffix is an extension, make sure to
	 *  include the dot.
	 *
	 *      'url_suffix' => '.html',
	 *
	 *  Set this to an empty string if no suffix is used.
	 *
	 */

	// 'url_suffix' => '',

	/**
	 * -------------------------------------------------------------------------
	 *  The name of the main bootstrap file
	 * -------------------------------------------------------------------------
	 *
	 *  Set this to 'index.php if you don't use URL rewriting.
	 *
	 */

	// 'index_file' => false,

	// 'profiling' => false,

	/**
	 * -------------------------------------------------------------------------
	 *  Default location for the file cache
	 * -------------------------------------------------------------------------
	 */

	// 'cache_dir' => APPPATH.'cache/',

	/**
	 * -------------------------------------------------------------------------
	 *  Settings for the file finder cache
	 *
	 *  Note: The Cache class has it's own config!
	 * -------------------------------------------------------------------------
	 *
	 *  The 'cache_lifetime' value is in seconds.
	 *
	 */

	// 'caching' => false,

	// 'cache_lifetime' => 3600,

	/**
	 * -------------------------------------------------------------------------
	 *  Callback to use with ob_start(), set this to 'ob_gzhandler'
	 *  for gzip encoding of output
	 * -------------------------------------------------------------------------
	 */

	// 'ob_callback' => null,

	// 'errors' => array(
		/**
		 * ---------------------------------------------------------------------
		 *  Which errors should we show, but continue execution? You can add
		 *  the following:
		 *
		 *      E_NOTICE, E_WARNING, E_DEPRECATED, E_STRICT
		 *
		 *  to mimic PHP's default behaviour (which is to continue
		 *  on non-fatal errors). We consider this bad practice.
		 * ---------------------------------------------------------------------
		 */

		// 'continue_on' => array(),

		/**
		 * ---------------------------------------------------------------------
		 *  How many errors should we show before we stop showing them?
		 *
		 *  Note: This is useful to prevents out-of-memory errors.
		 * ---------------------------------------------------------------------
		 */

		// 'throttle' => 10,

		/**
		 * ---------------------------------------------------------------------
		 *  Should notices from Error::notice() be shown?
		 * ---------------------------------------------------------------------
		 */

		// 'notices' => true,

		/**
		 * ---------------------------------------------------------------------
		 *  Render previous contents or show it as HTML?
		 * ---------------------------------------------------------------------
		 */

		// 'render_prior' => false,
	// ),

	/**
	 * -------------------------------------------------------------------------
	 *  Localization & internationalization settings
	 * -------------------------------------------------------------------------
	 */

	/**
	 *  The default language.
	 */

	// 'language' => 'en',

	/**
	 *  Fallback language when file isn't available for default language.
	 */

	// 'language_fallback' => 'en',

	/**
	 *  PHP set_locale() setting. Use null to not set.
	 */

	// 'locale' => 'en_US',

	/**
	 * -------------------------------------------------------------------------
	 *  Internal string encoding charset
	 * -------------------------------------------------------------------------
	 */

	// 'encoding' => 'UTF-8',

	/**
	 * -------------------------------------------------------------------------
	 *  DateTime settings
	 * -------------------------------------------------------------------------
	 */

	/**
	 *  The server offset in seconds from GMT timestamp when time() is used.
	 */

	// 'server_gmt_offset' => 0,

	/**
	 *  Change the server's default timezone. This is optional.
	 */

	// 'default_timezone' => null,

	/**
	 * -------------------------------------------------------------------------
	 *  Logging threshold.
	 * -------------------------------------------------------------------------
	 *
	 *  Can be set to any of the following:
	 *
	 *      Fuel::L_NONE
	 *      Fuel::L_ERROR
	 *      Fuel::L_WARNING
	 *      Fuel::L_DEBUG
	 *      Fuel::L_INFO
	 *      Fuel::L_ALL
	 *
	 */

	// 'log_threshold'   => Fuel::L_WARNING,
	// 'log_path'        => APPPATH.'logs/',
	// 'log_date_format' => 'Y-m-d H:i:s',

	/**
	 * -------------------------------------------------------------------------
	 *  Security settings
	 * -------------------------------------------------------------------------
	 */

	'security' => array(
		/**
		 * ---------------------------------------------------------------------
		 *  CSRF settings
		 * ---------------------------------------------------------------------
		 */

		// 'csrf_autoload'            => false,
		// 'csrf_autoload_methods'    => array('post', 'put', 'delete'),
		// 'csrf_bad_request_on_fail' => false,
		// 'csrf_auto_token'          => false,
		// 'csrf_token_key'           => 'fuel_csrf_token',
		// 'csrf_expiration'          => 0,

		/**
		 * ---------------------------------------------------------------------
		 *  Salt to make sure the generated security tokens aren't predictable.
		 * ---------------------------------------------------------------------
		 */

		// 'token_salt' => 'put your salt value here to make the token more secure',

		/**
		 * ---------------------------------------------------------------------
		 *  Allow the Input class to use X headers when present.
		 *
		 *  Examples of these are:
		 *
		 *      HTTP_X_FORWARDED_FOR and HTTP_X_FORWARDED_PROTO
		 *
		 *  which can be faked which could have security implications.
		 * ---------------------------------------------------------------------
		 */

		// 'allow_x_headers' => false,

		/**
		 * ---------------------------------------------------------------------
		 *  This input filter can be any normal PHP function
		 *  as well as 'xss_clean'
		 *
		 *  WARNING: Using xss_clean will cause a performance hit. How much is
		 *  depend on how much input data there is.
		 * ---------------------------------------------------------------------
		 */

		'uri_filter' => array('htmlentities'),

		// 'input_filter' => array(),

		/**
		 * ---------------------------------------------------------------------
		 *  This output filter can be any normal PHP function
		 *  as well as 'xss_clean'
		 *
		 *  WARNING: Using xss_clean will cause a performance hit. How much is
		 *  depend on how much input data there is.
		 * ---------------------------------------------------------------------
		 */

		'output_filter' => array('Security::htmlentities'),

		/**
		 * ---------------------------------------------------------------------
		 *  Encoding mechanism to use on htmlentities()
		 * ---------------------------------------------------------------------
		 */

		// 'htmlentities_flags' => ENT_QUOTES,

		/**
		 * ---------------------------------------------------------------------
		 *  Whether to encode HTML entities as well
		 * ---------------------------------------------------------------------
		 */

		// 'htmlentities_double_encode' => false,

		/**
		 * ---------------------------------------------------------------------
		 *  Whether to automatically filter view data
		 * ---------------------------------------------------------------------
		 */

		// 'auto_filter_output' => true,

		/**
		 * ---------------------------------------------------------------------
		 *  With output encoding switched on, all objects passed will be
		 *  converted to strings or throw exceptions unless they are instances
		 *  of the classes in this array.
		 * ---------------------------------------------------------------------
		 */

		'whitelisted_classes' => array(
			'Fuel\\Core\\Presenter',
			'Fuel\\Core\\Response',
			'Fuel\\Core\\View',
			'Fuel\\Core\\ViewModel',
			'Closure',
		),
	),

	/**
	 * -------------------------------------------------------------------------
	 *  Cookie settings
	 * -------------------------------------------------------------------------
	 */

	// 'cookie' => array(
		/**
		 * ---------------------------------------------------------------------
		 *  Number of seconds before the cookie expires
		 * ---------------------------------------------------------------------
		 */

		// 'expiration' => 0,

		/**
		 * ---------------------------------------------------------------------
		 *  Restrict the path that the cookie is available to
		 * ---------------------------------------------------------------------
		 */

		// 'path' => '/',

		/**
		 * ---------------------------------------------------------------------
		 *  Restrict the domain that the cookie is available to
		 * ---------------------------------------------------------------------
		 */

		// 'domain' => null,

		/**
		 * ---------------------------------------------------------------------
		 *  Only transmit cookies over secure connections
		 * ---------------------------------------------------------------------
		 */

		// 'secure' => false,

		/**
		 * ---------------------------------------------------------------------
		 *  Only transmit cookies over HTTP, disabling Javascript access
		 * ---------------------------------------------------------------------
		 */

		// 'http_only' => false,
	// ),

	/**
	 * -------------------------------------------------------------------------
	 *  Validation settings
	 * -------------------------------------------------------------------------
	 *
	 *  Whether to fallback to global when a value is not found in the
	 *  input array.
	 *
	 */

	// 'validation' => array(
		// 'global_input_fallback' => true,
	// ),

	/**
	 * -------------------------------------------------------------------------
	 *  Controller class prefix
	 * -------------------------------------------------------------------------
	 */

	 // 'controller_prefix' => 'Controller_',

	/**
	 * -------------------------------------------------------------------------
	 *  Routing settings
	 * -------------------------------------------------------------------------
	 */

	// 'routing' => array(
		/**
		 * ---------------------------------------------------------------------
		 *  Whether URI routing is case sensitive or not
		 * ---------------------------------------------------------------------
		 */

		// 'case_sensitive' => true,

		/**
		 * ---------------------------------------------------------------------
		 *  Whether to strip the extension
		 * ---------------------------------------------------------------------
		 */

		// 'strip_extension' => true,
	// ),

	/**
	 * -------------------------------------------------------------------------
	 *  Module paths
	 * -------------------------------------------------------------------------
	 *
	 *  To enable you to split up your application into modules which can be
	 *  routed by the first uri segment you have to define their basepaths here.
	 *  By default is empty, but to use them you can add something like this:
	 *
	 *      'module_paths' => array(APPPATH.'modules'.DS)
	 *
	 *  Paths MUST end with a directory separator (the DS constant)!
	 *
	 */

	// 'module_paths' => array(
	// 	// APPPATH.'modules'.DS
	// ),

	/**
	 * -------------------------------------------------------------------------
	 *  Package paths
	 * -------------------------------------------------------------------------
	 *
	 *  To enable you to split up your additions to the framework, packages are
	 *  used. You can define the basepaths for your packages here. By default is
	 *  empty, but to use them you can add something like this:
	 *
	 *      'package_paths' => array(APPPATH.'modules'.DS)
	 *
	 *  Paths MUST end with a directory separator (the DS constant)!
	 *
	 */

	'package_paths' => array(
		PKGPATH,
	),

	/**
	 * -------------------------------------------------------------------------
	 *  Always load
	 * -------------------------------------------------------------------------
	 */
        'always_load' => array(
            'packages' => array(
		 'orm',
		 ),
            ),
   
	// 'always_load' => array(
		/**
		 * ---------------------------------------------------------------------
		 *  These packages are loaded on Fuel's startup.
		 *  You can specify them in the following manner:
		 *
		 *      'packages' => array('auth');
		 *
		 *  This will assume the packages are in PKGPATH.
		 *
		 *  Use this format to specify the path to the package explicitly.
		 *
		 *      'packages' => array(
		 *          array('auth' => PKGPATH.'auth/')
		 *      );
		 * ---------------------------------------------------------------------
		 */

		// 'packages' => array(
		// 	// 'orm',
		// ),

		/**
		 * ---------------------------------------------------------------------
		 *  These modules are always loaded on Fuel's startup.
		 *  You can specify them in the following manner:
		 *
		 *      'modules' => array('module_name');
		 *
		 *  A path must be set in 'module_paths' for this to work.
		 * ---------------------------------------------------------------------
		 */

		// 'modules' => array(),

		/**
		 * ---------------------------------------------------------------------
		 *  Classes to autoload & initialize even when not used
		 * ---------------------------------------------------------------------
		 */

		// 'classes' => array(),

		/**
		 * ---------------------------------------------------------------------
		 *  Configurations to autoload
		 *
		 *  If you want to load 'session' config into a group 'session',
		 *  you only have to add 'session'.
		 *
		 *      'config' => array('session')
		 *
		 *  If you want to add it to another group (example: 'auth'),
		 *  you have to add it like:
		 *
		 *      'config' => array('session' => 'auth')
		 *
		 *  If you don't want the config in a group, use null as groupname.
		 * ---------------------------------------------------------------------
		 */

		// 'config' => array(),

		/**
		 * ---------------------------------------------------------------------
		 *  Language files to autoload
		 *
		 *  If you want to load 'validation' lang into a group 'validation',
		 *  you only have to add 'validation'.
		 *
		 *      'language' => array('validation')
		 *
		 *  If you want to add it to another group (example: 'forms'),
		 *  you have to add it like:
		 *
		 *      'language' => array('validation' => 'forms')
		 *
		 *  If you don't want the lang in a group, use null as groupname.
		 * ---------------------------------------------------------------------
		 */

		// 'language' => array(),
	// ),
);

student.php file from FuelSample\fuel\app\classes\model\student.php

<?php

class Model_Student extends Orm\Model
{
    protected static $_table_name = 'student'; 
    protected static $_properties = array ('id','roll_no','name');

}

student.php file from FuelSample\fuel\app\classes\controller\student.php

<?php

class Controller_Student extends Controller_Template
{
    public function action_index()
    {  
        $data = array(); 
        $data['Students'] = Model_Student::find('all');
        $this->template->title="Student List";
        $this->template->content=View::forge('student/index',$data,false);
    }
    
    public function action_view($id)
    {
        $Student = Model_Student::find('first',
                array(
                    'where' => array(
                        'id' =>  $id
                    )
                )
                );
        
        if($Student==null){
             throw new HttpNotFoundException();
        }
        $data=array('Student' => $Student);
        $this->template->title="View Student";
        $this->template->content=View::forge('student/view',$data,false);
    }
    
    public function action_create()
    {
        $data = array();
        
        //button create clicked
        if(Input::post('create')){
            
            $val = Validation::forge();

            $val->add('roll_no', 'Roll No')->add_rule('required')
                                           ->add_rule('numeric_min', 1)
                                           ->add_rule('numeric_max', 100);

            $val->add('name', 'Name')->add_rule('required')
                                           ->add_rule('min_length', 3)
                                           ->add_rule('max_length', 10);
            // validation Succeed
            if($val->run()){
                // get an array of successfully validated fields => value pairs
                $validatedFields  = $val->validated();
                //create student model and save to db    
                $Student = new Model_Student();
                $Student->roll_no  = $validatedFields['roll_no'];
                $Student->name   = $validatedFields['name'];
                $Student->save();
                //redirect to Student List
                Response::redirect('/fuelsample/public/student');
            }
            // validation failed
            //redirect back with error message
            else{
                // get an array of validation errors as field => error pairs
                $data['errors']= $val->error();
                $this->template->title="Create Student";
                $this->template->content=View::forge('student/create',$data,false);
            }

        }
        // show form on new page load
        else{
            $this->template->title="Create Student";
            $this->template->content=View::forge('student/create',$data,false);     
        }
    }
    
    public function action_edit($id)
    {
        $data = array();
        //check student exist in db or not
        $Student = Model_Student::find('first',
        array(
            'where' => array(
                'id' =>  $id
            )
        )
        );
        
        if($Student==null){
             throw new HttpNotFoundException();
        }
        
        //button update clicked
        if(Input::post('update')){
            
            $val = Validation::forge();

            $val->add('roll_no', 'Roll No')->add_rule('required')
                                           ->add_rule('numeric_min', 1)
                                           ->add_rule('numeric_max', 100);

            $val->add('name', 'Name')->add_rule('required')
                                           ->add_rule('min_length', 3)
                                           ->add_rule('max_length', 10);
            // validation Succeed
            if($val->run()){
                // get an array of successfully validated fields => value pairs
                $validatedFields  = $val->validated();
                //update existing student model values and save to db    
                $Student->roll_no  = $validatedFields['roll_no'];
                $Student->name   = $validatedFields['name'];
                $Student->save();
                //redirect to Student List
                Response::redirect('/fuelsample/public/student');
            }
            // validation failed
            //redirect back with error message
            else{
                // get an array of validation errors as field => error pairs
                //set error
                $data['errors']= $val->error();
                //set student value to last filled values
                $Student->roll_no = Input::post('roll_no');
                $Student->name = Input::post('name');
                $data['Student']= $Student;
                $this->template->title="Edit Student";
                $this->template->content=View::forge('student/edit',$data,false);
            }

        }
        // show form on new page load
        else{
            //set student from db
            $data['Student']= $Student;
            $this->template->title="Edit Student";
            $this->template->content=View::forge('student/edit',$data,false);     
        }
    }
    
    public function action_delete($id)
    {
        //check student exist in db or not
        $Student = Model_Student::find('first',
        array(
            'where' => array(
                'id' =>  $id
            )
        )
        );
        
        if($Student==null){
             throw new HttpNotFoundException();
        }
        //delete student
        $Student->delete();
        //redirect to Student List
        Response::redirect('/fuelsample/public/student');
    }
}

template.php file from FuelSample\fuel\app\views\template.php

<!DOCTYPE html>
<html>
<head>
</head>
<body>
	<header>
            <h1>Header Template</h1>  
            <h3><?php echo $title; ?></h3>            
	</header>
    
	<div class="container">		 
		<?php echo $content; ?>		
	</div>
    
        <footer>
                <h2>Footer Template</h2>   
	</footer>
</body>
</html>

index.php file from FuelSample\fuel\app\view\student\index.php

<h2 ><a href="/fuelsample/public/student/create">Create</a> </h2>
<style>
table, th, td {
  border: 1px solid black;
}
</style>
<table  >
    <tr><th>Student Id</th><th>Student Roll No</th><th>Student Name</th><th>Action</th><tr>
<?php foreach ($Students  as $Student): ?>
    <tr>
    <td><?php echo  $Student->id;  ?> </td> 
    <td><?php echo  $Student->roll_no;  ?></td> 
    <td><?php echo  $Student->name; ?> </td> 
    <td>
        <a href="/fuelsample/public/student/view/<?php echo  $Student->id; ?> " >View Details</a>
        <a href="/fuelsample/public/student/edit/<?php echo  $Student->id; ?>" >Edit Details</a>
        <a href="/fuelsample/public/student/delete/<?php echo  $Student->id; ?>"  >Delete</a>
    </td> 
    </tr>
<?php endforeach; ?>
</table>

view.php file from FuelSample\fuel\app\view\student\view.php

<p>Student ID : <?php echo  $Student->id;  ?> </p> 
<p>Student Roll No : <?php echo  $Student->roll_no;  ?></p>
<p>Student Name : <?php echo  $Student->name; ?></p>
<a href="/fuelsample/public/student/" >Back To List</a>

create.php file from FuelSample\fuel\app\view\student\create.php

<?php
if(isset($errors)) {  
   echo '<ul style="color:red"> Errors ';

    foreach($errors as $error)
    {
        echo '<li>'. $error .'</li>';
    }

   echo '</ul>';
} 
?> 

<?php echo Form::open("/fuelsample/public/student/create"); ?>

<div >
<?php echo Form::label('Roll No',"roll_no"); ?>
<?php echo Form::input('roll_no',
        Input::post('roll_no',isset($Student)?$Student->roll_no:''));
?>
</div>

<div >
<?php echo Form::label('Name',"name"); ?>
<?php echo Form::input('name',
        Input::post('name',isset($Student)?$Student->name:''));
?>
</div>

<div>
<?php echo Form::submit('create'); ?>
</div>

<?php echo Form::close();?>

<a href="/fuelsample/public/student/" >Back To List</a>

edit.php file from FuelSample\fuel\app\view\student\edit.php

<?php
if(isset($errors)) {  
    echo '<ul style="color:red"> Errors ';

    foreach($errors as $error)
    {
        echo '<li>'. $error .'</li>';
    }

   echo '</ul>';
} 
?> 

<?php echo Form::open('/fuelsample/public/student/edit/'.$Student->id); ?>

<div >
<?php echo Form::label('Roll No',"roll_no"); ?>
<?php echo Form::input('roll_no',
        Input::post('roll_no',isset($Student)?$Student->roll_no:''));
?>
</div>

<div >
<?php echo Form::label('Name',"name"); ?>
<?php echo Form::input('name',
        Input::post('name',isset($Student)?$Student->name:''));
?>
</div>

<div>
<?php echo Form::submit('update'); ?>
</div>

<?php echo Form::close();?>

<a href="/fuelsample/public/student/" >Back To List</a>

3 Run Application

Run Webserver and open browser and type http://localhost/fuelsample/public/student/

Conclusion

So in this article we have built CRUD MVC Application in FuelPHP Framework . If you liked the article then please share this site and article. Thanks.

Please Subscribe Youtube| Like Facebook | Follow Twitter


6 Replies to “FUEL PHP EXAMPLE TUTORIAL PART 3 (CRUD MVC Application)”

  1. I’m truly enjoying the design and layout of your blog. It’s a very easy on the eyes which makes it much more enjoyable for me to come here and visit more often. Did you hire out a designer to create your theme? Superb work!

  2. Great goods from you, man. I’ve take note your stuff previous to and you are simply too magnificent. I really like what you’ve got right here, certainly like what you’re saying and the way in which wherein you assert it. You are making it entertaining and you continue to take care of to keep it sensible. I can’t wait to learn far more from you. This is actually a terrific web site.

  3. Hey there! Would you mind if I share your blog with my zynga group? There’s a lot of folks that I think would really appreciate your content. Please let me know. Many thanks

Leave a Reply

Your email address will not be published. Required fields are marked *