codeigniter search form error - php

I have been trying to figure out what is wrong with my form search form. I have tried to build a basic search form in code igniter. I have built a search form before and I am building it the same way for a different application and I keep getting the
An Error Was Encountered
The action you have requested is not allowed.
This is not very descriptive for troubleshooting. I am using the same config as I did in my last project. So I don't understand why I am getting the above error message.
When I go to the http://www.gaddisweb.com/index.php/childtest/search, the search form displays the view code. Now, I have rules set the the field is required. I click the search button with the field empty and it should give me and error message saying field required.
Instead, I get the above error message. Even If I put anything in the block I get the same error message. I know I am missing something simple but I can't see it.
Controller Code:
class ChildTest extends CI_Controller {
public function index(){
$this->search();
}
public function search(){
$this->load->helper('form');
$this->load->library('form_validation');
$this->form_validation->set_rules(array(
array(
'field' => 'keyword',
'label' => 'Child Family Name',
'rules' => 'required',
)
));
$this->form_validation->set_error_delimiters('<div class="alert alert-error">', '</div>');
if(!$this->form_validation->run()){
$this->load->view('childsearch');
}else{
$keyword = $this->input->post('keyword');
echo $keyword;
}
}
}
View Code:
<div id="search">
<p></p>
<form id="search" method = "post" action="">
<label id="familyname">Child Family Name</label>
<input type="text" size="20" id="keyword" name="keyword"/>
<input type="submit" value="Search" />
</form>
</div>
If the block is empty I should get an error message saying so and if there is anything in the block it should be displayed to me on the post action.
Neither is happening.
Thanks for your help.
Answer
This is my opinion on what happened. I can't find any documentation that says this but. I was able to achieve what I was trying to do. I had to do a slight rewrite because the difference between the first time I did a search form and the second time was the fact of using the security sessions.
In my opinion, CI when you turn on the sessions will not allow post to the same page. The post data must be passed to another controller and cannot post to the originating controller.
This part was taken out of the original controller above and placed in another that I name childvalidation.
$this->load->helper('form');
$this->load->library('form_validation');
$this->form_validation->set_rules(array(
array(
'field' => 'keyword',
'label' => 'Child Family Name',
'rules' => 'required',
)
));
$this->form_validation->set_error_delimiters('<div class="alert alert-error">', '</div>');
if(!$this->form_validation->run()){
}
Once I added the childvalidation controller and passed the form data to it, then I was able to complete the search function.
View Code changed to:
<?php echo validation_errors() . "</br>";?>
<?php echo form_open('childsearchvalidation'); ?>
<label id="familyname">Child Family Name</label>
<input type="text" size="20" id="keyword" name="keyword"/>
<input type="submit" value="Search" />
</form>
Hope this helps someone.

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.

Validation_errors() not showing in the view (CodeIgniter)

I'm working with my first application with CI and I'm having problems with the library form_validation.
The validation and my method are working fine, except for the fact that I can't get to show my error messages. I tried to show them individually, as the manual said, but didn't work. Tried to show them using echo validation_errors();, but the error messages are blank in my page.
So I make a test to put the code in the controller and they work! But they are shown in the beginning of the page. I used some javascript to make it visually better (moved it to where I want it to be shown), but it's not beautiful. I tried everything on the CodeIgniter and still did not get a good result. Please, someone could help me on this?
This is my controller User.php:
public function registrar() {
$this->load->library('form_validation');
$this->load->view('registrar');
$this->form_validation->set_rules('name', 'Nome', 'trim|required|min_length[7]',
array( 'required' => '<br>- Por favor, insira seu nome.',
'min_length' => '<br>- Por favor, insira seu nome completo.'));
// ..... other rules
if ($this->form_validation->run() == TRUE)
{
$password = $this->input->post('password');
$password_hash = password_hash($password, PASSWORD_BCRYPT);
$data = array(
'name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'password' => $password_hash
);
if ($this->user_model->insertUser($data))
{
$this->session->set_flashdata('error_msg','<p>Ok</p>');
redirect('user/registrar');
}
else
{
$this->session->set_flashdata('error_msg','<p>Not ok</p>');
redirect('user/registrar');
}
}
else
{
echo validation_errors('<div class="error">', '</div>'); //THIS LINE WORKS!!!
}
}
This is my view registrar.php:
<form action="" method="post" class="pure-form"> // using this only for css styling
<?php echo validation_errors(); ?> // THIS LINE DOESN'T WORKS :(
<?php echo form_open('user/registrar');?>
<fieldset>
<h1>Registrar</h1>
<div class="pure-control-group group gr-2">
<label for="email">Nome:</label>
<input type="text" class="pure-input-1" id="name" name="name" placeholder="Nome" value="<?php echo set_value('name');?>">
</div>
// ....... everything else
<input type="submit" class="pure-button pure-button-primary verde" value="Cadastrar" name="register_submit">
</div>
<?php echo form_close();?>
</form>
You are loading view page before the validation. That's the reason validation_errors are not showing in registrar.php.
$this->load->view('registrar');
Add this after else condition of validation or end of the function.

$_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?

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