Codeigniter Form post controller advice - php

would like some advice/help on how to connect form controller to post form method in my CI site. I want to data submitted from one viewer to another. Thank you for the help!!
Here is the controller Im using (Form.php), took if from another site:
Form.php
<?php
class Form extends CI_Controller {
public function __construct() {
parent::__construct();
}
// Show form in view page i.e view_page.php
public function form_show() {
$this->load->view("addEdit");
}
// When user submit data on view page, Then this function store data in array.
public function data_submitted() {
$data = array(
'file_name' => $this->input->post('file'),
'title' => $this->input->post('title')
);
// Show submitted data on view page again.
$this->load->view("profile", $data);
}
}
?>
Its to connect to this code:
addEdit.php
<form method="post" action="postAction.php" enctype="multipart/form-data">
<div class="form-group">
<label>Image</label>
<?php if(!empty($imgData['file_name'])){ ?>
<img src="uploads/images/<?php echo $imgData['file_name']; ?>">
<?php } ?>
<input type="file" name="image" class="form-control" >
</div>
<div class="form-group">
<label>Title</label>
<input type="text" name="title" class="form-control" placeholder="Enter title" value="<?php echo !empty($imgData['title'])?$imgData['title']:''; ?>" >
</div>
Back
<input type="hidden" name="id" value="<?php echo !empty($imgData['id'])?$imgData['id']:''; ?>">
<input type="submit" name="imgSubmit" class="btn btn-success" value="SUBMIT">
</form>
When I first tried to make it work I got this error:
404 Page Not Found
The page you requested was not found.
http://culturedkink.com/index.php/register/postAction.php(the url)
postAction.php is the form Im trying to get the data to work from
The end result is to have info submitted from addEdit.php be seen on profile.php with the help of postAction.php

make routes for it first.
config/routes.php
$route['add'] = 'Controller_name/data_submitted';
$route['edit/(:any)'] = 'Controller_name/data_submitted/$1';
where is your add/edit button put this there
for add
Add New
for edit button
$row['id'] is an example i m giving. you can get data by name and id..whatever you want.
Update
//controller
public function data_submitted($id=0) {
$data=array();
$data['dataDetails']=$this->get_profile_data_by_id($id);
$data['view'] = 'folder_name/addEdit';
if ($id > 0) {
$profileArray = [
'file_name' => $this->input->post('file'),
'title' => $this->input->post('title')
];
if ($this->User_model->editById($id, $profileArray)) {
$id = $id;
}
}
else{
$profileArray = [
'file_name' => $this->input->post('file'),
'title' => $this->input->post('title')
];
if ($this->User_model->add($id, $profileArray)) {
$id = $id;
}
}
$this->load->view("profile", $data);
}
form view page
<?php echo isset($dataDetails) ? "Update" : "Add"; ?>

First check your form method and action. Your action does not exist. First check how CI works with form. The action should have a method declared in a controller. The url looks like this,
When you submit the form the data will be submitted in this method. Whatever you need to do with this form data you can do that in this method.

Related

check the array if it is empty or not that is received from the FORM that has CSRF generate token

Since I am using csrf in the form, the array $data that is passed in request function is never empty.
How to resolve this so that when i submit the form without any input fields filled, I get "data is empty"?
view.blade.php
<form action="{{url('/userdata')}}" method="POST">
#csrf
<div class="form-group">
<label for="name">Name:</label>
<input type="text" class="form-control" name="name">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
Controller.php
public function userdata(Request $request)
{
$data=$request ->all();
if(!empty($data)){
echo "data is filled";
}else{
echo "data is empty";
}
}
You can use required in the input fields if you don't want the form to submit empty.
<form action="{{url('/userdata')}}" method="POST">
#csrf
<div class="form-group">
<label for="name">Name:</label>
<input type="text" class="form-control" name="name" required>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
Otherwise if name is your only field you can do this:
public function userdata(Request $request){
$data = $request->except(["_token"]);
if($data['name'] != ""){
echo "data is filled";
} else {
echo "data is empty";
}
}
You can use the get() method:
public function userdata(Request $request){
$data = $request->get("_token");
if(!empty($data)){
echo "data is filled";
} else {
echo "data is empty";
}
}
Sorry I misunderstood your question on my first answer. A value will always be submitted for input elements on the page, even if they're empty. The proper way to do this is to create a request validation.
Create something like this class, though much neater I'm sure ;)
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class StoreUserdata extends FormRequest {
public function authorize() {return true;}
public function rules() {
return ["name" => ["required", "max:64"]];
}
}
And then edit the signature of your controller method so instead of expecting a Request it looks for your validation class (don't forget a use statement above):
public function userdata(StoreUserdata $request){
// ....
}
Now, your requests will fail if the name input is empty, or is too long. There are a lot of possible validation rules.

variable in codeigniter controller never accessible to view template when re-populating input form

I've exhausted all research endpoints (docs, Google, SO, etc.), so I've been driven to ask this question publicly. The very nature of my problem should have been solved by the CodeIgniter 3.0.6 official documentation in the section entitled "Adding Dynamic Data to the View" as I (think) I'm dealing with a variable never making the scope of my controller to be accessed by my view.
I'm adding a single, custom modification to a content publishing app consisting of an edit page fetching content by ID for table data update. 1st, the form;
EDIT.PHP
<div class="row">
<div class="col-md-12">
<h3>Update post</h3>
<form method="post" action="<?php echo base_url('post/update'); ?>" enctype="multipart/form-data">
<div class="form-group">
<label for="title">Title</label>
<input type="text" name="title" id="title" placeholder="News title" value="<?php echo $data['post']->title; ?>" class="form-control" />
</div>
<div class="form-group">
<label for="category">Category</label>
<select name="category" id="category" class="form-control">
<?php foreach($data['categories'] as $category): ?>
<option value="<?php echo $category->idcategory; ?>" <?php echo set_select('category', $category->idcategory); ?>><?php echo $category->title; ?></option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group">
<label for="image">Image</label>
<input type="file" name="image" id="image" class="form-control" placeholder="Upload an image" />
</div>
<div class="form-group">
<label for="body">Post detail</label>
<textarea name="body" id="body" class="form-control" placeholder="Provide news content. Basic HTML is allowed."><?php echo $data['post']->body; ?></textarea>
</div>
<div class="form-group">
<label for="tags">Tags</label>
<input type="text" name="tags" id="tags" value="<?php echo set_value('tags'); ?>" class="form-control" placeholder="Comma separated tags" />
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
I've edited the input values to target the values I need the form populated with in the cases of the Title and Post detail inputs (didn't need to alter anything for the category input, as it's a dropdown working brilliantly), and leaving the tags form input as is to not break output layout while I troubleshoot. Controller/function Post.php was duped from original 'add' function, and I'm including the entirety rather than what I feel is the problematic code chunk;
UPDATE FUNCTION
public function update($idpost) {
$this->load->helper('form');
$data['title'] = 'Update post | News Portal';
$data['post'] = $this->posts->get($idpost);
$this->load->model('category_model', 'cm');
$data['categories'] = $this->cm->get_all();
$this->load->library('form_validation');
$this->form_validation->set_rules('title', 'title', 'trim|required');
$this->form_validation->set_rules('body', 'post body', 'trim|required');
$this->form_validation->set_rules('tags', 'tags', 'required');
if($this->input->method(TRUE) == 'POST' && $this->form_validation->run()) {
$config['upload_path'] = './assets/uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '2000';
$config['max_width'] = '2000';
$config['max_height'] = '1200';
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
if (!$this->upload->do_upload('image')) {
$this->template->alert(
$this->upload->display_errors(),
'danger'
);
} else {
$upload_data = $this->upload->data();
$idpost = $this->posts->add(array(
'iduser' => $this->user->id(),
'title' => $this->input->post('title'),
'body' => $this->input->post('body'),
'image' => $upload_data['file_name']
));
$tags = $this->input->post('tags');
if(strlen($tags) > 0) {
$this->load->model('tag_model', 'tm');
$tags = explode(',', trim($tags));
$tags = array_map(array($this->tm, 'set_tag'), $tags);
$this->load->model('post_tag_model', 'ptm');
foreach($tags as $idtag) {
$this->ptm->add(array(
'idpost' => $idpost,
'idtag' => $idtag
));
}
}
$idcategory = $this->input->post('category');
if($idcategory) {
$this->load->model('post_category_model', 'pcm');
$this->pcm->add(array(
'idpost' => $idpost,
'idcategory' => $idcategory
));
}
$this->template->alert(
'Updated news item successfully',
'success'
);
redirect('post');
return;
}
}
$this->template->view('post/edit', $data);
}
This variable ($tags) is somehow lost between the controller and view, confirmed by using var_dump($this->_ci_cached_vars); to check all available objects within that corresponding view. I just need the variable $tags to repopulate with the data appropriate to the form input. How is it that there was no initialization of $tags within this function?
I COMPLETELY understand that the variable WILL NEVER be passed to the corresponding view because it's non-existant (as confirmed by my previous var_dump), but I'm lost as to how exactly to draw $tags within function scope so it can help form input to retrieve targeted data? All the other inputs are repopulating as needed. And, as an aside, I actually tracked down the original developer of this project and conferred with him on this. I tried to wrangle two approaches he outlined, but I ended up getting blank or erroring pages. The closest I could come theoretically to his second point - adapting a bit of code already in the news view partial;
<?php
if($tags = get_tags($data['news']->idpost)) {
echo '<div class="tags">';
echo 'Terms: ';
foreach($tags as $tag) {
echo ' <i class="fa fa-fw fa-link"></i> ' . $tag->title . ' ';
}
echo '</div>';
}
?>
which always ends in Undefined Index/Variable or some other damnable error message that I try to break my neck to solve, but just keep sinking further into the quagmire (lol!). It SEEMS simple to me, the basis of my problem, but I keep going around, and around, and around until I'm drunk dizzy and ten time more lost than I started out. Could someone provide a crumb of understanding?
I mean, I'm getting a conniption fit as it should be as simple as the answer provided here # Passing variable from controller to view in CodeIgniter. But, alas, 'tis not...thanks in advance for any clarificative leads.
#DFriend - I'm not wanting to alter the structure too much as ;
a) the code this is duped from is working and the only goal is to pull data from the appropriate table into that form input,
b) I don't want to disturb current functionality or inadvertently open another issue, and,
c) I'm trying to zero in on the correct elements.
Thank you for your time and answer, #DFriend.
I believe that the reason for your problems is because of the redirect call. By calling that you are essentially putting a new URL into the browser. Websites are stateless. Without using sessions or other means each request for a URL is unique. So by calling redirect you are wiping any knowledge of $tags from existence.
You can probably get around this by pushing $tags into the $_SESSION array and then checking for and retrieving it in the post controller.
Alternately, if post() is in the same controller you can simple call it instead of the redirect. post() will have be modified to accept an argument, or $tags will have to be a property of the controller class.
So to call directly to post, instead of
redirect('post');
return;
do this
$this->post($tags);
return;
Then define post to accept an optional argument
public function post($tags=null){
//somewhere in here
if(isset($tags)){
//$data is sent to views
$data['tags'] = $tags;
}
}
Expanded Answer:
How to implement a Post/Read/Get pattern in Codeigniter and still use field validation and repopulated form fields.
Using Codeigniter (CI) to implement a PRG pattern for processing requires an extension of the CI_Form_validation class. The code that follows should be in /application/libraries/MY_Form_validation.php
<?php
/**
* The base class (CI_Form_validation) has a protected property - _field_data
* which holds all the information provided by validation->set_rules()
* and all the results gathered by validation->run()
* MY_Form_validation provides a public 'setter' and 'getter' for that property.
*
*/
class MY_Form_validation extends CI_Form_validation{
public function __construct($rules = array())
{
parent::__construct($rules);
}
//Getter
public function get_field_data() {
return $this->_field_data;
}
//Setter
public function set_field_data($param=array()){
$this->_field_data = $param;
}
}
Without the template library you are using I fell back on $this->load->view(). And without access to your models and associated data I had to make some assumptions and, in some cases, leave db calls out.
Overall, I tried not to alter the structure too much. But I also wanted to demonstrate a couple handy uses of the form helper functions.
for the most part the restructuring I did was mostly an attempt at providing a clear example. If I succeed as showing the concepts you should be able to implement this fairly easily.
Here's the revised view. It makes more use of the 'form' helper functions.
<head>
<style>
.errmsg {
color: #FF0000;
font-size: .8em;
height: .8em;
}
</style>
</head>
<html>
<body>
<div class="row">
<div class="col-md-12">
<h3>Update post</h3>
<?php
echo form_open_multipart('posts/process_posting');
echo form_hidden('idpost', $idpost);
?>
<div class="form-group">
<label for="title">Title</label>
<input type="text" name="title" id="title" placeholder="News title" value="<?php echo $title; ?>" class="form-control" />
<span class="errmsg"><?php echo form_error('title'); ?> </span>
</div>
<div class="form-group">
<label for="category">Category</label>
<?php
echo form_dropdown('category', $categories, $selected_category, ['class' => 'form-control']);
?>
</div>
<div class="form-group">
<label for="image">Image</label>
<input type="file" name="image" id="image" class="form-control" placeholder="Upload an image" />
</div>
<div class="form-group">
<label for="body">Post detail</label>
<textarea name="body" id="body" class="form-control" placeholder="Provide news content. Basic HTML is allowed."><?php echo $body; ?></textarea>
<span class="errmsg"><?php echo form_error('body'); ?> </span>
</div>
<div class="form-group">
<label for="tags">Tags</label>
<input type="text" name="tags" id="tags" value="<?php echo $tags ?>" class="form-control" placeholder="Comma separated tags" />
<span class="errmsg"><?php echo form_error('tags'); ?> </span>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
<?= form_close(); ?>
</div>
</div>
</body>
</html>
The crux of this solution is to store form_validation->_field_data in the session when validation fails. The view loading function looks for a failure flag in session data and, if the flag is true, restores form_validation->_field_data to the current form_validation instance.
I tried to put a lot of explanation in the comments. What follows in the controller complete with display and processing methods.
class Posts extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->library('session');
$this->load->library('form_validation', NULL, 'fv');
}
/**
* post()
* In this example the function that shows the posting edit page
* Note the use of the optional argument with a NULL default
*/
function post($idpost = NULL)
{
$this->load->model('category_model', 'cm');
$categories = $this->cm->get_all();
/*
* Your model is returning an array of objects.
* This example is better served by an array of arrays.
* Why? So the helper function form_dropdown() can be used in the view.
*
* Rather than suggest changing the model
* these lines make the conversion to an array of arrays.
*/
$list = [];
foreach($categories as $category)
{
$list[$category->idcategory] = $category->title;
}
$data['categories'] = $list; // $data is used exclusivly to pass vars to the view
if(!empty($idpost))
{
//if argument is passed, a database record is retrieved.
$posting = $this->posts->get($idpost);
//Really should test for a valid return from model before using it.
//Skipping that for this example
$title = $posting->title;
$body = $posting->body;
//assuming your model returns the next two items like my made up model does
$selected_category = $posting->category;
$tags= $posting->tags;
}
else
//a failed validation (or a brand new post)
{
//check for failed validation
if($this->session->failed_validation)
{
// Validation failed. Restore validation results from session.
$this->fv->set_field_data($_SESSION['validated_fields']);
}
}
//setup $data for the view
/* The 'idpost' field was add to demonstrate how hidden data can be pasted to and from
* a processing method. In this case it would be useful in providing a 'where = $value'
* clause on a database update.
* Also, a lack of any value could be used indicate an insert is requried for a new record.
*
* Notice the ternary used to provide a default value to set_value()
*/
$data['idpost'] = $this->fv->set_value('idpost', isset($idpost) ? $idpost : NULL);
$data['title'] = $this->fv->set_value('title', isset($title) ? $title : NULL);
$data['body'] = $this->fv->set_value('body', isset($body) ? $body : NULL);
$data['tags'] = $this->fv->set_value('tags', isset($tags) ? $tags : NULL);
$data['selected_category'] = $this->fv->set_value('category', isset($selected_category) ? $selected_category : '1');
$this->load->view('post_view', $data);
}
public function process_posting()
{
if($this->input->method() !== 'post')
{
//somebody tried to access this directly - bad user, bad!
show_error('The action you have requested is not allowed.', 403);
// return; not needed because show_error() ends with call to exit
}
/*
* Note: Unless there is a rule set for a field the
* form_validation->_field_data property won't have
* any knowledge of the field.
* In Addition, the $_POST array from the POST call to the this page
* will be GONE when we redirect back to the view!
* So it won't be available to help repopulate the <form>
*
* Rather than making a copy of $_POST in $_SESSION we will rely
* completely on form_validation->_field_data
* to repopulate the form controls.
* That can only work if there is a rule set
* for ANY FIELD you want to repopulate after failed validation.
*/
$this->fv->set_rules('idpost', 'idpost', 'trim'); //added any rule so it will repopulate
// in this example required would not be useful for 'idpost'
$this->fv->set_rules('title', 'title', 'trim|required');
$this->fv->set_rules('body', 'post body', 'trim|required');
$this->fv->set_rules('tags', 'tags', 'required');
//add rule for category so it can be repopulated correctly if validation fails
$this->fv->set_rules('category', 'category', 'required');
if(!$this->fv->run())
{
// Validation failed. Make note in session data
$this->session->set_flashdata('failed_validation', TRUE);
//capture and save the validation results
$this->session->set_flashdata('validated_fields', $this->fv->get_field_data());
//back to 'posts/index' with server code 303 as per PRG pattern
redirect('posts/post', 'location', 303);
return;
}
// Fields are validated
// Do the image upload and other data storage, set messges, etc
// checking for $this->input->idpost could be used in this block
// to determine whether to call db->insert or db->update
//
// When process is finished, GET the page appropriate after successful <form> post
redirect('controller/method_that_runs_on_success', 'location', 303);
}
//end Class
}
Questions? Comments? Insults?

How to send id from view to Controller CodeIgniter via form_open_multipart

I am trying to an send id from a view to controller in CodeIgniter.My requirement is to switch the functions based on button id.Here is my HTML code.
View HTML
<?php echo form_open_multipart('upload_control/switch_load','id="bt_addImage"');?>
<input id= "bt_addImage" type="submit" value="Add Image" /> <br>
<?php echo form_open_multipart('upload_control/switch_load','id="bt_chooseImage"');?>
<input type="submit" id="bt_chooseImage" value="Submit"/><br>
Upload_control.php Code
public function switch_load($id)
{
if($id == "bt_addImage")
{
do_loadcategories();
}
else
{
do_upload();
}
}
public function do_loadcategories()
{
//code list categories
}
public function do_upload()
{
//code to upload
}
is it corrrect?
or
have any other way to do this?
help me to solve the issue.
In View
$hiddenFields = array('id' => 'bt_addImage'); # add Hidden parameters like this
echo form_open_multipart('upload_control/switch_load', '', $hiddenFields);
In Controller
public function switch_load()
{
$id = $this->input->post('id');
if($id == "bt_addImage")
{
do_loadcategories();
}
else
{
do_upload();
}
}
view look like this
<form method="post" accept-charset="utf-8" action="http:/example.com/index.php/upload_control/switch_load">
<input type="hidden" name="id" value="bt_addImage" /> # hidden filed.
Codeigniter Form Helper
Change from
if($id == "bt_addImage")
Into
if($this->input->post('id') == "bt_addImage")

Codeigniter can't login

Here is the controller, when I click the login button, nothing happens. What I want is to load the success screen when user data is validated and show error messages when user data is not validated.
I have set my base_controller as Login
<?php
class Login extends CI_Controller {
/**
*
* load the magazines
*/
function __construct(){
parent::__construct();
$this->load->library('form_validation');
$this->load->model('User','National_Holiday','Updated_Holiday');
}
public function index() {
$this->load->view('login');
}
/**
*
* add a magazine
*/
public function login(){
$this->form_validation->set_rules(array (
array(
'field' => 'username',
'label' => 'username',
'rules' => 'required',
) ,
array(
'field' => 'password',
'label' => 'password',
'rules' => 'required|is_numeric',
),
));
$this -> form_validation ->set_error_delimiters('<div class="alert alert-error">','</div>');
if(!$this->form_validation->run()){
$this->load->view('login');
}
else {
$this->load->view('national_holiday_screen');
}
}
}
here is the view
<?php echo validation_errors(); ?>
<form method="post">
<!-- LOGIN DIV STARTS HERE -->
<div>
<div> <h2> Log In </h2></div>
<div>
<lablel for="username"> Username </label>
<input type="text" name="username" value=""/>
</div>
<div>
<label for="password"> Password </label>
<input type="password" name="password" value=""/>
</div>
<div>
<br>
<input type="submit" value="Login">
</div>
</div>
<!-- LOGIN DIV ENDS HERE -->
</form>
When I click the login button, nothing happens. What am I doing wrong?
You have to give action attribute in form tag, like this:
action="http://yoursitename.com/controllername"
in your case controllername is login.
For more help, you can refer:
[https://ellislab.com/codeigniter/user-guide/helpers/form_helper.html][1]
Hope this help!
this link shows how form_open() works, one of codeigniter's utility functions from the form helper libary.
In your case you would want this line of code:
<?php echo form_open('/login'); ?>
or something that you want to be the login url.
This line would replace
<form method="post">
in your html and when rendered would be something like
<form method="post" accept-charset="utf-8" action="http:/example.com/index.php/login" />
If you aren't familiar with URI routing, then you should read about that here](https://ellislab.com/codeigniter/user-guide/general/routing.html). I would recommedn setting up a route for you login, but the default format for a url is
example.com/class/function/id/
so yours might look like
example.com/login/login
And form_open() would then look like (even though its kind of cluncky)
<?php echo form_open('/login/login'); ?>
You can try below code
login.php controller file
<?php
class Login extends CI_Controller {
/**
*
* load the magazines
*/
function __construct(){
parent::__construct();
$this->load->library('form_validation');
$this->load->helper('url');
$this->load->model('User','National_Holiday','Updated_Holiday');
}
public function index() {
$this->load->view('login');
}
/**
*
* add a magazine
*/
public function validate(){
$this->form_validation->set_rules(array (
array(
'field' => 'username',
'label' => 'username',
'rules' => 'required',
) ,
array(
'field' => 'password',
'label' => 'password',
'rules' => 'required|is_numeric',
),
));
$this -> form_validation ->set_error_delimiters('<div class="alert alert-error">','</div>');
if(!$this->form_validation->run()){
$this->load->view('login');
}
else {
$this->load->view('national_holiday_screen');
}
}
}
Here I have loaded one helper to give action url in view file
$this->load->helper('url');
Also I have changed function name from login to validate as function name should not be similar to class name as constructor is already defined there
login.php view file
<?php echo validation_errors(); ?>
<form method="post" action = "<?php echo site_url("login/validate"); ?>">
<!-- LOGIN DIV STARTS HERE -->
<div>
<div> <h2> Log In </h2></div>
<div>
<lablel for="username"> Username </label>
<input type="text" name="username" value=""/>
</div>
<div>
<label for="password"> Password </label>
<input type="password" name="password" value=""/>
</div>
<div>
<br>
<input type="submit" value="Login">
</div>
</div>
<!-- LOGIN DIV ENDS HERE -->
</form>
Hope this will help you

How to process a form with CodeIgniter

I am new to CodeIgniter. I need to process a form. I have a form.html page in view
<html>
<head>
<title>Search</title>
</head>
<body>
<form action="search">
<input type="text" name="search" value="" size="50" />
<div>
<input type="submit" value="Submit" />
</div>
</form>
</body>
</html>
and form controller
class Form extends Controller {
function Form() {
parent::Controller();
}
function index() {
$this->load->view('form');
}
}
and I have an view file search.php but when it is processed it shows page not found...
In M.odel V.iew C.ontroller setups like CodeIgniter the Views are user interface elements. They should not be parsing results.
If I am not mistaken, what you are looking to do is pass data from www.yoursite.com/index.php/form to www.yoursite.com/index.php/search
In unstructured php you might have a form.html with a form action of search.php. A user would navigate to yoursite.com/form.html, which would call yoursite.com/search.php, which might redirect to yoursite.com/results.php.
In CodeIgniter (and, as far as I understand it, in any MVC system, regardless of language) your Controller, Form calls a function which loads the form.html View into itself and then runs it. The View generates the code (generally HTML, but not necessarily) which the user interacts with. When the user makes a request that the View cannot handle (requests for more data or another page) it passes that request back to the Controller, which loads in more data or another View.
In other words, the View determines how the data is going to be displayed. The Controller maps requests to Views.
It gets slightly more complicated when you want to have complex and / or changing data displayed in a view. In order to maintain the separation of concerns that MVC requires CodeIgniter also provides you with Models.
Models are responsible for the most difficult part of any web application - managing data flow. They contain methods to read data, write data, and most importantly, methods for ensuring data integrity. In other words Models should:
Ensure that the data is in the correct format.
Ensure that the data contains nothing (malicious or otherwise) that could break the environment it is destined for.
Possess methods for C.reating, R.eading, U.pdating, and D.eleting data within the above constraints.
Akelos has a good graphic laying out the components of MVC:
(source: akelos.org)
That being said, the simplest (read "easiest", not "most expandable") way to accomplish what you want to do is:
function Form()
{
parent::Controller();
}
function index()
{
$this->load->view('form');
}
function search()
{
$term = $this->input->post('search');
/*
In order for this to work you will need to
change the method on your form.
(Since you do not specify a method in your form,
it will default to the *get* method -- and CodeIgniter
destroys the $_GET variable unless you change its
default settings.)
The *action* your form needs to have is
index.php/form/search/
*/
// Operate on your search data here.
// One possible way to do this:
$this->load->model('search_model');
$results_from_search = $this->search->find_data($term);
// Make sure your model properly escapes incoming data.
$this->load->view('results', $results_from_search);
}
View file is useless without the controller to load and displaying it. You must create a controller to receive the form data, process it, then displaying the process result.
You can use a form helper to set the form open tags, also the close tags:
<?php echo form_open('form/search'); ?>
<input type="text" name="search" value="" size="50" />
<div><input type="submit" value="Submit" /></div>
<?php echo form_close(); ?>
Without using form helper, you can still write it this way:
<form action="<?php echo site_url('form/search'); ?>">
Then add the search method into form controller:
function search()
{
//get form field
$search = $this->input->post('search');
// do stuffs here
//...
}
Remember that CI only help you with the basic code organization and provide a helpful library and helper. But you still need to write the algorithm of the process in your site.
Don't forget to read the included user guide in the downloaded codeigniter package. You can learn many stuffs from the example in there. Don't hesitate to ask things you don't know here, many member of stackoverflow will help you.
This is form validation and submit in controller
My whole controller class
class MY_Controller extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->library(array('session','form_validation'));
$this->load->helper(array('form', 'url', 'date'));
//$this->load->config('app', TRUE);
//$this->data['app'] = $this->config->item('app');
}
}
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Article extends MY_Controller {
function __construct() {
parent::__construct();
$this->load->model('article_model');
}
public function index() {
$data['allArticles'] = $this->article_model->getAll();
$data['content'] = $this->load->view('article', $data, true);
$this->load->view('layout', $data);
}
public function displayAll() {
$data['allArticles'] = $this->article_model->getAll();
$data['content'] = $this->load->view('displayAllArticles', $data, true);
$this->load->view('layout', $data);
}
public function displayArticle($id) {
$data['article'] = $this->article_model->read($id);
$data['articleId'] = $id;
$data['comment'] = $this->load->view('addComment', $data, true);
$data['content'] = $this->load->view('displayArticle', $data, true);
$this->load->view('layout', $data);
}
public function add() {
$this->form_validation->set_message('required', '%s is required');
$this->form_validation->set_rules('title', 'Title', 'required|xss_clean');
$this->form_validation->set_rules('description', 'Description type', 'required|xss_clean');
$this->form_validation->set_error_delimiters('<p class="alert alert-danger"><a class="close" data-dismiss="alert" href="#">×</a>', '</p>');
if ($this->form_validation->run() == TRUE) {
$article = array(
'title' => $this->input->post('title'),
'description' => $this->input->post('description'),
'created' => date("Y-m-d H:i:s")
);
$this->article_model->create($article);
redirect('article', 'refresh');
} else {
$data['article'] = array(
'title' => $this->input->post('title'),
'description' => $this->input->post('description'),
);
$data['message'] = validation_errors();
$data['content'] = $this->load->view('addArticle', $data, true);
$this->load->view('layout', $data);
}
}
}
We can use normal html form like this.
<?php echo $message; ?>
<form method="post" action="article/add" id="article" >
<div class="form-group">
<label for="title">Article Title</label>
<input type="text" class="form-control" id="title" name="title" value="<?php echo $article['title']; ?>" >
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea class="form-control" rows="13" name="description" id="description"><?php echo $article['description']; ?></textarea>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
</div>
Try using the codeigniter 'site_url' in your action to make sure you are pointing to the right place. The action in your example would have gone to the 'search' controller rather than the 'form' controller.
<html>
<head>
<title>Search</title>
</head>
<body>
<form action="<?= site_url('form/process_search') ?>">
<input type="text" name="search" value="" size="50" />
<div><input type="submit" value="Submit" /></div>
</form>
</body>
</html>
index is only used in your controller when nothing else is passed.. So in the case of my example above you would want something like this:
function Form()
{
parent::Controller();
}
function process_search()
{
print "<pre>";
print_r($_POST);
print "</pre>";
}
Nettuts has a great tutorial for CodeIgniter for Login form. Follow the screencast and it will clear up your questions.
http://net.tutsplus.com/videos/screencasts/codeigniter-from-scratch-day-6-login/
replace this <form action="search"> with <?php echo form_open('form/search');?>
and autoload.php file add $autoload['helper'] = array('form');
and then file dont use file search.php just add your search.php code into your Controller file
like here
class Form extends Controller {
function Form() {
parent::Controller();
}
function index() {
$this->load->view('form');
}
function search(){
//your code here
}
}

Categories