How to process a form with CodeIgniter - php

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
}
}

Related

Codeigniter Form post controller advice

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.

Is model and view have direct relationship in codeigniter

i have a view file view.php .Have following code.
<form method="post">
<input type="text" name="profession_name" />
<input type="button" name="submit" value="Add Profession" onClick="add_profession" class="btn btn-success" />
</form>
and i have model file Model_model.php.Have following code.
<?php
class Model_model extends CI_Model{
function __construct(){
parent::__construct();
}
function insert_data(){
$data = array(
"profession_name" => $_POST['profession_name']
);
$this->db->insert('table_name',$data);
}
}?>
Is it possible without using controller i directly access form value in model?
For best practices you would want to handle this with a MVC approach where all form information etc is sent from the view to the controller, handled and processed in the controller and then passed to the model for access to the db.
However, you can access the model in the view exactly like you would in your controller:
<? $this->model_model->insert_data(); ?>
And you can get post values from a form on the same page by using the method shown in this answer: php form - on submit stay on same page

$_POST is working but $this->input->post empty

I have form in my nav template in codeigniter view
<form action="<?php echo base_url()?>account/login/" class="navbar-form navbar-left" method="post" accept-charset="utf-8">
<div class="form-group">
<input type="text" name="adres" class="form-control" placeholder="Email">
<input type="password" name="pass" class="form-control" placeholder="Password">
</div>
<button type="submit" class="btn btn-default">Login</button>
</form>
In my controller method i can echo $_POST['adres'] and its fine, but when i try with codeigniter helper $this->input->post('adres') its empty . Whats wrong ?
I'm using input->post in my registration form and its working fine.
General Advice of using the forms in CodeIgnitor
Step 1: Try to use the native form method that are available in CI.
Syntax for Form Open:
form_open('[controller]/[action]')
Hence below is the sample example of how to open up the form based on the controller that we have created.
<?php echo form_open('todos/update_completed'); ?>
<?php echo form_close(); ?>
Where todos/update_completed means
todos - Controller Name
update_completed - Method name in that Controller.
Step 2: Load up the form elements during the auto load itself or you can load up the form elements in the Construct function itself.
Loading the form attributes via the helper in the construct function.
$this->load->helper('form');
Below is the example of how to call it.
function __construct()
{
parent::__construct();
$this->load->helper('form');
}
Step 3: And in the Controller or in the model you have to get the Input that has been posted like this below.
$this->input->post('title')
$this->input->post('username')
These are all the General Checks that has to be made while using the form elements in CodeIgnitor.
Yes, problem solved. I was using curly brace and i should use a normal one. My bad
Have you used helper class in constructor $this->load->helper('form'); or in method .
You can load helper function in your controller like this
function __construct()
{
$this->load->helper('form');
}

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?

The form action and anchor is not working in codeigniter PHP

I was trying to set the action of a form in the form_open(). And there I specified the login file (present in the controller and its also the base controller file), and its function named as validate. But the page is giving 404 object not found error. What is it that I'm doing wrong? And the same error occurs in anchor('login/signup','Create Account');. I hope I'm able to explain myself.
/controller/login.php
<?php
class Login extends CI_Controller
{
function index()
{
$this->load->helper('HTML');
$this->load->view('includes/header');
$this->load->view('login_form');
}
function signup()
{
$this->load->view('signup_form');
}
function validate()
{
}
}
?>
/view/login_form.php
<div class="form_login">
<?php echo heading("Login",1); ?>
<?php
echo form_open('login/validate');
echo form_input('username','','placeholder ="Enter Username"');
echo form_password('pass','','placeholder ="Enter Password"');
echo form_submit('sub','Submit');
echo br();
echo anchor('login/signup','Create Account');
echo form_close();
?>
</div>
you can create form also like that --
<div class="form_login">
<form method="post" action="<?php echo base_url(); ?>login/insert">
<input type="text" name="username" placeholder ="Enter Username">
<input type="password" name="pass" placeholder ="Enter Password">
<input type="submit" value="Submit"></br>
Create Account
</form>
</div>
You did not load the form helper. If you load models, helpers, etc in a class constructor they are available for every method in your Class. Even easier is going to application/config/autoload.php and putting them there. But here is an example constructor and a bunch of different things that can happen including loading your helpers...
class Login extends CI_Controller{
function __construct() {
// this is always required
parent::__construct();
// load some helpers
$this->load->helper('html');
$this->load->helper('url');
$this->load->helper('form');
// load some libraries
$this->load->library('form_validation');
$this->load->library('database');
$this->load->library('session');
// load models
$this->load->model( 'superusers' );
$this->load->model( 'dailyword' );
// create a variable with $this that can be used anywhere
$this->devmessage = '' ;
// call a method and return something that can be used anywhere
$this->wordoftheday = $this->dailyword->returnword() ;
}
so now any method in the Login class, and any Model or View file called by the Login class will have all the above helpers, libraries, models, etc available. Also spelling the helper names upper case might work on some systems but i would suggest always naming them lower case.

Categories