anyone can help me, the id that I called could not be found , I'm new in codeigniter and php, and am trying to create crud (update) how to solve this? thanks in advance
Controller
public function editdata($id) ---------> LINE 41
{
$data['title'] = 'Edit Data Interview';
$data['user'] = $this->db->get_where('user', ['email' => $this->session->userdata('email')])->row_array();
$data['form1'] = $this->db->get_where('form1', ['id_form1' => $id])->row_array();
}
View
<form action="<?= site_url('datainterview/editdata/' . $m['id_form1']) ?>" method="post">
<input type="hidden" name="id_form1" value="<?= $m['id_form1'] ?>">
<button onclick="return confirm('Edit Data ?')" class="btn btn-primary btn-xs">Edit</button>
</form>
Error
Message: Too few arguments to function DataInterview::editdata(), 0 passed in C:\xampp\htdocs\MYNET\system\core\CodeIgniter.php on line 532 and exactly 1 expected
Filename: C:\xampp\htdocs\MYNET\application\controllers\DataInterview.php
Line Number: 41
Basically your url does not contain the id when you submit your data.
If that is a required param to perform your action that error is a good thing. If that is not a required param then you should give it a default value.
public function editdata($id = null)
{
$data['title'] = 'Edit Data Interview';
$data['user'] = $this->db->get_where('user', ['email' => $this->session->userdata('email')])->row_array();
$data['form1'] = $this->db->get_where('form1', ['id_form1' => $id])->row_array();
}
This way the id has the default value of null. So if you try to access that variable that would be the value you get when you access:
example.com/DataInterview/editdata
However when you access:
example.com/DataInterview/editdata/12
you get the value of 12.
You might even go a step forward and give a proper error when the id is not sent into the function. Something like:
public function editdata($id = null)
{
if (is_null($id)) {
show_404();
}
$data['title'] = 'Edit Data Interview';
$data['user'] = $this->db->get_where('user', ['email' => $this->session->userdata('email')])->row_array();
$data['form1'] = $this->db->get_where('form1', ['id_form1' => $id])->row_array();
}
Then you can get to that error flashdata and show proper errors to your user.
Related
I'm trying to send my validation errors to another method by using redirect
public function save()
{
//validasi input
if (!$this->validate([
'judul' => 'required|is_unique[komik.judul]'
])) {
return redirect()->to('/komik/create')->withInput();
}
this is the create() method
public function create()
{
session();
$data = [
'title' => 'Form Tambah Data Komik',
'validation' => \Config\Services::validation()
];
return view('komik/create', $data);
}
This is a snippet of my create.php view form where I'm trying to validate
<form action="/komik/save" method="post" enctype="multipart/form-data">
<?php d($validation) ?>
<?= $validation->listErrors();; ?>
this is the form
The problem is that the validation errors in save() is not sent to the create() method. But the validation errors exist in the save() method which I can prove by adding
$validation = \Config\Services::validation(); dd($validation);
in save(). This is what happens when I click "Tambah Data" button after I add the code
as you can see there is a validation error, it's just not sent to the create() method
I tried using return view(), this works but it creates another problem. I would like to use return redirect() instead.
This is my routes
$routes->get('/', 'Pages::index');
$routes->get('/komik/create', 'Komik::create');
$routes->get('/komik/edit/(:segment)', 'Komik::edit/$1');
$routes->post('/komik/save', 'Komik::save');
$routes->delete('/komik/(:num)', 'Komik::delete/$1');
$routes->get('/komik/(:any)', 'Komik::detail/$1');
What can I do to solve this problem? Thanks
A. Use Flashdata instead.
CodeIgniter supports “flashdata”, or session data that will only be
available for the next request, and is then automatically cleared.
I.e:
save() method.
public function save()
{
//validasi input
if (!$this->validate([
'judul' => 'required|is_unique[komik.judul]'
])) {
$validation = \Config\Services::validation();
return redirect()
->to('/komik/create')
->with("redirectedErrors", $validation->listErrors())
->with("redirectedInput", $this->request->getVar());
}
}
with()
Adds a key and message to the session as Flashdata.
public with(string $key, array<string|int, mixed>|string $message) : $this
B. Then, modify the create() method to pass on the flashed data to the View.
create() method.
public function create()
{
return view('komik/create', [
'title' => 'Form Tambah Data Komik',
'validation' => \Config\Services::validation(),
'redirectedErrors' => session()->getFlashdata("redirectedErrors") ?: "",
'redirectedInput' => session()->getFlashdata("redirectedInput") ?? [],
]);
}
C. Lastly, in your View file (create.php), you may access the passed-on data normally.
create.php View file.
<form action="/komik/save" method="post" enctype="multipart/form-data">
<?php echo empty($validation->getErrors()) ? $redirectedErrors : $validation->listErrors() ?>
<input id="first_name" name="first_name" type="text" value="<?php echo old('first_name', array_key_exists('first_name', $redirectedInput) ? $redirectedInput['first_name'] : '') ?>"/>
</form>
I found the solution, apparently there's a bug with redirect()->withInput() in CI. You need to use validation_errors(), validation_list_errors() and validation_show_error() to display validation error. Also you don't need to write $validation = \Config\Services::validation();.
Read https://codeigniter4.github.io/CodeIgniter4/installation/upgrade_430.html#redirect-withinput-and-validation-errors
there's an error appearing in my code for update. too few argument for function.
I searched the net and I'm not sure if I'm passing the id.
Controller:
public function update()
{
if($this->Admin_model->update($this->input->post(null, true))){
$this->session->set_flashdata('flash_msg', ['message' => 'User updated successfully', 'color' => 'green']);
} else {
$this->session->set_flashdata('flash_msg', ['message' => 'Error updating user.', 'color' => 'red']);
}
$this->admin_redirect('cms');
}
Model:
public function update($id, $data)
{
$data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
return $this->db->update($this->table, $data);
}
As #WILLIAM, stated in a comment, your update(...) method expects 2 parameters yet one is passed.
Change your update(...) method to this:
public function update($data)
{
$data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
$this->db->where('id', $data['id']);
return $this->db->update($this->table, $data);
}
This assumes that 'id' is part of your HTML form.i.e:
<input type="hidden" name="id" value="<?php echo $id ?>">
You need to call your model update function with 2 params in the controller code, but it seems you are calling it only with one parameter $data value is missing.
In below code:
if($this->Admin_model->update(**$this->input->post(null, true)**))
It should be called with 2 values first one should be an ID that identifies the record that you want to update in your model, and another should be the data that would be updated within that record.
Hope! you got the answer.
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.
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']
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.