I have a problem on getting post data after submitting a form. What I'm trying to do is that, when the user clicks the submit button, input values stored in the hidden fields will be assigned to a variable into another controller class. However, when I tried to print out the form value, its always giving me NULL
This is my code:
Controller
public function updateOrder(){
$this->form_validation->set_rules('delivery_status_id', 'Delivery Status', 'xss_clean');
$this->form_validation->set_rules('remarks', 'Remarks', 'xss_clean');
$this->form_validation->set_rules('total_amt', 'Total Amount', 'xss_clean');
$data = array('remarks' => $this->input->post('remarks'),
'delivery_status_id' => $this->input->post('delivery_status_id'),
'total_amt' => $this->input->post('total_amt'));
if ($data['delivery_status_id'] == $getDeliveryStatusIdDelivered->row('id'))
{
$this->db->select('*');
$this->db->from('user_has_penalty');
$this->db->where("user_id =" . $this->session->userdata['id']);
$query = $this->db->get();
foreach ($query->result() as $row)
{
$this->db->delete('user_has_penalty', array('user_id' => $this->session->userdata['id']));
$this->db->delete('penalty', array('id' => $row->penalty_id));
}
}else if($data['delivery_status_id'] == $getDeliveryStatusIdCancelled->row('id'))
{
$penalty_amt = $data['total_amt'] / 2;
$data = array('amount' => $penalty_amt);
$this->penalty->insert($data);
$penalty_id = $this->db->insert_id();
//var_dump($penalty_id);
}
var_dump($this->input->post); // Outputs NULL
}
View
...
<?php
$name_c = 'Cancelled';
$query = $this->DeliveryStatus->getDeliveryStatusByName($name_c);
echo form_open('Order_Controller/updateOrder');
?>
<input type="hidden" name="delivery_status_id" value="<?php echo $query->row('id'); ?>"/>
<button type="submit" class="btn btn-danger">YES</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<?php echo form_close(); ?>
Is there something wrong with the code? Any help would be appreciated
In your form tag, if you do not specify the method it will be get method.
<form action="Order_Controller/updateOrder" method="post">
...
</form>
You are missing the method in your form tag.
form_open('order_Controller/updateOrder', array('method'=>'post'));
Note:
Please use model for database related queries.
Pass the query result to the controller and then to the view.
You can add your validation in configuration. To handle all validation at one place.
// This Will outputs always null
var_dump($this->input->post);
// To Get Value Array from codeigniter input class
var_dump($this->input->post());
method will return the values in $_POST variable
because you are accessing uninitialized property of a object
The correct way to get post variable from codeigniter input class is
$this->input->post() is equivalent to $_POST;
$this->input->post('data') is equivalent to $_POST['data']
Related
I am calling the controller function via ahref tag and i want to pass the current record no to the controller to update the record current value is stored in$currentID and i pass this value in input type..but i didn't get the value from the view page..i tried var_dump($id)..it shows null
Controller Code to update:
public function update($id='')
{
$session_data = $this->session->userdata('logged_in');
$data['username'] = $session_data['username'];
$id=$this->input->post('update');
echo "<pre>";var_dump($id);
$dc=$this->input->post('dc');
if($dc=='c'){
$amount=$this->input->post('credit1');
}
else if ($dc=='d') {
$amount=$this->input->post('debit');
}
$data=array(
'date' =>$this->input->post('TDate'),
'code' =>$this->input->post('TName'),
'project' =>$this->input->post('TName1'),
'part' =>$this->input->post('part1'),
'part1' =>$this->input->post('part2'),
'dc'=>$this->input->post('dc'),
'amount'=>$amount,
);
$this->db->where('recno', $id);
$this->db->update('daybook', $data);
$this->session->set_flashdata('Add1', 'Updated Successfully');
redirect('BookKeeping/daybook','refresh');
}
calling update
<a href="<?=site_url('BookKeeping/update/'.$currentID)?>" class="btn btn-info btn-"><i class="icon-new position-left">
<input type="hidden" name="update" id="id" value="<?php echo $currentID?>">
</i>Update</a>
Help me to pass the currentvalue to the controller..Thanks in advance
you are sending value in url
change this
$id=$this->input->post('update');
To
$id=$this->uri->segment('3');
remove the input field. You can't pass any input data with
<i class="icon-new position-left"></i>Update
Try this
public function update($id=''){
$session_data = $this->session->userdata('logged_in');
$data['username'] = $session_data['username'];
$id=$id;
echo "<pre>";var_dump($id);
$dc=$this->input->post('dc');
if($dc=='c'){
$amount=$this->input->post('credit1');
}
else if ($dc=='d') {
$amount=$this->input->post('debit');
}
$data=array(
'date' =>$this->input->post('TDate'),
'code' =>$this->input->post('TName'),
'project' =>$this->input->post('TName1'),
'part' =>$this->input->post('part1'),
'part1' =>$this->input->post('part2'),
'dc'=>$this->input->post('dc'),
'amount'=>$amount,
);
$this->db->where('recno', $id);
$this->db->update('daybook', $data);
$this->session->set_flashdata('Add1', 'Updated Successfully');
redirect('BookKeeping/daybook','refresh');
}
In your code
As I see your controller code posted in question, you haven't passed any value in variable $currentID which might be getting undefined, so please first try to var_dump your $currentID variable and check its value.
Do a test
Please try assigning a static id for the sake of functionality. Your static value will be passed to the method as an argument. Once you sure about static value is working, you can go ahead with finding out where is the issue in $currentID variable.
$data['currentID'] = $someValueFromDB;
$this->load->view('some_view.php',$data);
this way your value will be passed to view, make sure value is correctly passing or getting generated on view.
You are passing data in right way at controller, no problem with that.
In my codeigniter controller function call $this->form_validation->run(), that return always false, and my validation_errors() not showing error, probably because not receive datas in post method...
my controller
class Reminder extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('reminder_model');
$this->load->helper('form');
$this->load->library('form_validation');
$this->load->helper('url');
$this->load->library('email');
$this->load->library('session');
if(!$this->session->auth_ok) {
redirect('auth/login');
}
}
public function index(){
$data['title'] = 'Reminder';
$data['section'] = 'reminder';
$data['reminders'] = $this->reminder_model->getReminders();
$data['operatori'] = $this->reminder_model->getOperators();
$this->form_validation->set_rules('selectUser','selectUser', '');
if($this->form_validation->run() === FALSE) {
$this->load->view('common/header2', $data);
$this->load->view('reminder/index', $data);
$this->load->view('common/footerReminder');
echo validation_errors();
}else{
echo "<pre>";
print_r($this->input->post());
die();
}
}
my view
<?php echo form_open('reminder/index'); ?>
<div class="form-group">
<label for="selectUser" style=" width: 30%">Utente: </label>
<select class="form-control" name="selectUser" id="selectUser" style="width: 30%">
<?php foreach($operatori as $operatore): ?>
<option value="<?php echo $operatore['ID']?>" <?php echo $r = ($operatore['ID']==$this->session->auth_user['ID']) ? 'selected' : '' ?>><?php echo $operatore['nome']." ".$operatore['cognome'] ?></option>
<?php endforeach; ?>
</select>
</div>
<button type="submit" class="btn btn-primary"><i class="fas fa-search"></i> View</button>
<?php echo form_close(); ?>
In order to get the entire $_POST array using CodeIgniters built-in methods, you have to set the first parameter as NULL and the second parameter as TRUE
Like this:
$this->input->post(NULL, TRUE);
Also, you have not set any rules for validation..
In CodeIgniter, you set rules in the third parameter of the set_rules method within the form_validation object.
Like this:
$this->form_validation->set_rules($FIELD_NAME, $FIELD_NAME(for error messages), $RULES);
You would substitute the first $FIELD_NAME with the value of the name attribute on the HTML element you are looking to validate.
You would substitute the second $FIELD_NAME with the name you would like to use for the field when displaying an error message to the user.
You would substitute $RULES with the validation rules such as: 'required|min_length[#]|max_length[#]'
Hope this helps!
If you are not setting rules (which makes it rather pointless to use $this->form_validation->set_rules()) the form validation will fail as it's missing a required parameter.
If you don't need to validate a field, don't set a rule.
Try updating your set_rules instruction to $this->form_validation->set_rules('selectUser','selectUser', 'required'); to see if it behaves correctly. You can verify by filling something in the form (validation will pass) or leaving the field blank (validation will fail)
Just remember, if you won't set at least one validation rule for a field, don't instantiate the set_rules method for that field
I am trying to insert a row to the db using codeigniter.
Model-post.php
class Post extends CI_Model{
function get_posts($num=20, $start=0){
$this->db->select()->from('posts')->where('active',1)->order_by('date_added','desc')->limit($num,$start);
$query=$this->db->get();
return $query->result_array();
}
function get_post($postid){
$this->db->select()->from('posts')->where(array('active' => 1, 'postID'=>$postid))->order_by('date_added','desc');
$query=$this->db->get();
return $query->first_row('array');
}
function insert_post($data){
$this->db->insert('posts',$data);
return $this->db->return_id();
}
Controller-posts.php
class Posts extends CI_Controller{
function __construct(){
parent::__construct();
$this->load->model('post');
}
function index(){
$data['posts'] = $this->post->get_posts();
$this->load->view('post_index', $data);
}
function post($postid){
$data['post']=$this->post->get_post($postid);
$this->load->view('post',$data);
}
function new_post(){
if($_POST){
$data =array(
'title'=>$_POST['title'],
'post'=>$_POST['post'],
'active'=>1
);
$this->post->insert_post($data);
redirect(base_url());
}
else{
$this->load->view('new_post');
}
}
View-new_post.php
<form action="<?php base_url(); ?>posts/new_post" method="action">
<p>Title: <input type="text" name="title"></p>
<p>Description: <input type="textarea" name="post"></p>
<input type="submit" value="Add post">
</form>
Index view-post_index.php
foreach ($posts as $post) { ?>
<div id-="container">
<div><h3><?php echo $post['title']; ?> </h3>
<?php echo $post['post']; ?>
</div>
</div>
<?php
}
The index page shows all the posts from db. On clicking the title it takes to post.php view to show the respective data. This part is fine.
While trying to add a new post in new_post.php it is not reflecting in the db nor showing any error. Also I used redirect_url to redirect to the index page after inserting. So it shows the same available posts. On clicking the title it keeps on adding posts/post to the url repeatedly. Clicking the title once after redirecting the url shows
http://localhost/Codeigniter/posts/posts/post/1
Again on clicking the title it adds
http://localhost/Codeigniter/posts/posts/post/post/1
Can anyone help me? Thanks!
There are numerous issues across the entire application. These are what I found:
Views
Two problems in your new_post view.
You are not echoing out your base_url . You need to replace your form's action attribute.
the method attribute should either have post or get. In this case it should be post
Change it like this:
From this:
<form action="<?php base_url(); ?>posts/new_post" method="action">
To this:
<form action="<?= base_url(); ?>posts/new_post" method="post">
alternatively you can do this:
<form action="<?php echo base_url(); ?>posts/new_post" method="post">
Controller
In your posts controller, your new_post() function should be like this:
function new_post() {
if ($this->input->post()) {
$data = array(
'title' => $this->input->post('title'),
'post' => $this->input->post('post'),
'active' => 1
);
$id = $this->post->insert_post($data);// this is the id return by your model.. dont know what you wann do with it
// maybe some conditionals checking if the $id is valid
redirect(base_url());
} else {
$this->load->view('new_post');
}
}
Model
function insert_post() should not have $this->db->return_id();, instead it should be $this->db->insert_id();
in your model
function insert_post($newpost){
$this->db->insert('posts',$newpost);
// check if the record was added
if ( $this->db->affected_rows() == '1' ) {
// return new id
return $this->db->insert_id();}
else {return FALSE;}
}
any user input must be validated. if you are using Codeigniter then use its form validation and use its input library like:
$this->input->post('title')
an example for blog posts are in the tutorial https://ellislab.com/codeIgniter/user-guide/tutorial/create_news_items.html
otherwise in your controller -- check if the new post id did not come back from the model -- if it did not come back then just go to an error method within the same controller so you don't lose the php error messages.
if ( ! $postid = $this->post->insert_post($newpost); ){
// passing the insert array so it can be examined for errors
$this->showInsertError($newpost) ; }
else {
// success now do something else ;
}
I am creating a search page in my CodeIgniter project.
On submit, the form calls the controller function, data is fetched via model function and the resulting array is passed to the view
The problem is that when I refresh the result page the form is resubmitting because the $_POST data is still there in the request headers.
How can I avoid that resubmit confirmation message
Following is the code for my form :
<!--form-->
<form id="find" action="<?php echo base_url()?>search/find" method="post">
<input type="text" name="search_key" class="tb4" id="search_key" placeholder="Search here"/>
<input type="button" value="search"/>
</form>
Following is the code for my controller:
/*
* function for fetching search results
* #param void
* #return void
*/
public function find()
{
$data['search_result']=$this->search_model->search($this->input->post('search_key'));
$this->load->view('template/header');
$this->load->view('pages/search_result',$data);
$this->load->view('template/footer');
}
Kindly help me with this.I can't use redirect instead of loading the view since I am bound to pass the result array $data to the view.
Try redirect to itself
public function find()
{
$data['search_result']=$this->search_model->search($this->input->post('search_key'));
if($this->input->post('search_key')) {
redirect('yourcontroller/find');
}
$this->load->view('template/header');
$this->load->view('pages/search_result',$data);
$this->load->view('template/footer');
}
Simple solution is to have a hidden timestamp field in the form.
<?php echo form_hidden( 'TS', time() ); ?>
When the form is processed, save this timestamp in the session,
$this->session->set_userdata( 'form_TS', $this->input->post( 'TS' ) );
Before processing the form check that two timestamps doesn't match
if ( $this->input->post( 'TS' ) != $this->session->userdata('form_TS') )
{...}
IF you want to avoid the resubmit then please after save redirect on same controller like this
It can be solved using session. If there is any POST form submit,
ie
if (count($_POST) > 0){
$this->session->set_userdata('post_data', $_POST );
redirect('same_controller');
}
else{
if($this->session->userdata('post_data')){
$_POST = $this->session->userdata('post_data');
$this->session->unset_userdata('post_data');
}
}
Kindly use this:
$post_data = $this->session->userdata('post_data');
if ($post_data == $_POST){
$this->session->unset_userdata('post_data');
redirect(current_url(), 'refresh');
}else{
$this->session->set_userdata('post_data', $_POST );
}
value of FORM INPUT Help!!
//this is just a refrence of $nm and $fid from test_model//
$data['fid']['value'] = 0;
$data['nm'] = array('name'=>'fname',
'id'=>'id');
say i have one form_view with
<?=form_label('Insert Your Name :')?>
<?=form_input($nm)?>
and a function to get single row
function get($id){
$query = $this->db->getwhere('test',array('id'=>$id));
return $query->row_array();
}
then in controller.. index($id = 0)
and somewhere in index
if((int)$id > 0)
{
$q = $this->test_model->get($id);
$data['fid']['value'] = $q['id'];
$data['nm']['value'] = $q['name'];
}
and mysql table has something like 1. victor, 2. visible etc. as a name value
but here its not taking the value of name and id from form_input and not showing it again in form_view in same input box as victor etc so to update and post it back to database...
anyone please help!!
and please be easy as I am new to CI!!
Based on your comment to my first answer, here is a sample of a Controller, Model and View to update a user entry pulled from a table in a database.
Controller
class Users extends Controller
{
function Users()
{
parent::Controller();
}
function browse()
{
}
function edit($id)
{
// Fetch user by id
$user = $this->user_model->get_user($id);
// Form validation
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'Name', 'required');
if ($this->form_validation->run())
{
// Update user
$user['name'] = $this->input->post('name', true);
$this->user_model->update_user($user);
// Redirect to some other page
redirect('users/browse');
}
else
{
// Load edit view
$this->load->view('users/edit', array('user' => $user));
}
}
}
Model
class User_model extends Model
{
function User_model()
{
parent::Model();
}
function get_user($user_id)
{
$sql = 'select * from users where user_id=?';
$query = $this->db->query($sql, array($user_id));
return $query->row();
}
function update_user($user)
{
$this->db->where(array('user_id' => $user['user_id']));
$this->db->update('users', $user);
}
}
View
<?php echo form_open('users/edit/' . $user['user_id']); ?>
<div>
<label for="name">Name:</label>
<input type="text" name="name" value="<?php echo set_value('name', $user['name']); ?>" />
</div>
<div>
<input type="submit" value="Update" />
</div>
<?php echo form_close(); ?>
It's hard to see the problem from your snippets of code, please try and give a little more information as to the structure of your app and where these code samples are placed.
Presume in the last code listing ('somewhere in index') you are getting $id from the form, but you define the ID of the form input box as 'id' array('name'=>'fname','id'=>'id') rather than an integer value so maybe this is where the problem lies.
Where does the $data array get passed to in the third code listing?
From your question I think you want to display a form to edit a person record in the database.
Controller code
// Normally data object is retrieved from the database
// This is just to simplify the code
$person = array('id' => 1, 'name' => 'stephenc');
// Pass to the view
$this->load->view('my_view_name', array('person' => $person));
View code
<?php echo form_label('Your name: ', 'name'); ?>
<?php echo form_input(array('name' => 'name', 'value' => $person['name'])); ?>
Don't forget to echo what is returned from form_label and form_input. This could be where you are going wrong.