codeigniter and form submit - php

I am trying to get used to Codeigniter. I am sorry if that is a trivial or dumb question but I have been struggling to have the "News Section" of Codeigniter's tutorial work.
There is this form (from here)
<h2><?php echo $title; ?></h2>
<?php echo validation_errors(); ?>
<?php echo form_open('news/create'); ?>
<label for="title">Title</label>
<input type="input" name="title" /><br />
<label for="text">Text</label>
<textarea name="text"></textarea><br />
<input type="submit" name="submit" value="Create news item" />
</form>
which, according to this controller:
<?php
class News extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('news_model');
$this->load->helper('url_helper');
}
public function index()
{
$data['news'] = $this->news_model->get_news();
$data['title'] = 'My News archive';
$this->load->view('templates/header', $data);
$this->load->view('news/index', $data);
$this->load->view('templates/footer');
}
public function view($slug = NULL)
{
$data['news_item'] = $this->news_model->get_news($slug);
if (empty($data['news_item']))
{
show_404();
}
$data['title'] = $data['news_item']['title'];
$this->load->view('templates/header', $data);
$this->load->view('news/', $data);
$this->load->view('templates/footer');
}
public function create()
{
$this->load->helper('form');
$this->load->library('form_validation');
$data['title'] = 'Create a news item';
$this->form_validation->set_rules('title', 'Title', 'required');
$this->form_validation->set_rules('text', 'Text', 'required');
if ($this->form_validation->run() === FALSE)
{
$this->load->view('templates/header', $data);
$this->load->view('news/create');
$this->load->view('templates/footer');
}
else
{
$this->news_model->set_news();
$this->load->view('news/success');
}
}
}
should, I think, if the validation returns ok, go ahead and insert the data into the db. Now, my problem is that the pages run under:
http://localhost/codeigniter/index.php/news/
The submit button, however, returns me to:
http://localhost/codeigniter/index.php/news/localhost/codeigniter/index.php/news/create
The routes.php file contains the following code:
$route['news/create'] = 'news/create';
$route['news/(:any)'] = 'news/view/$1';
$route['news'] = 'news';
$route['(:any)'] = 'news/view/$1';
$route['default_controller'] = 'news';
I don't know why this is happening. Thank you for any help.

Did you set your base_url config in application/config/config.php ?

Related

Too few arguments to function Admin::edit(),

I'm new in codeigniter and php,
and am trying to create crud (update)
how to solve this?
thanks in advance
Model :
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Role_model extends CI_Model
{
public function DeleteRole($id)
{
$this->db->where('id', $id);
$this->db->delete('user_role');
}
public function GetId($id)
{
return $this->db->get_where('user_role', ['id' => $id])->row_array();
}
public function EditRole()
{
$data = [
"role" => $this->input->post('role' , true)
];
$this->db->where('id', $this->input->post('id'));
$this->db->update('user_role', $data);
}
}
controller :
public function __construct()
{
parent::__construct();
is_logged_in();
$this->load->model('Role_model');
}
public function edit($id)
{
$data['title'] = 'Role';
$data['user'] = $this->db->get_where('user', ['email' => $this->session->userdata('email')])->row_array();
$data['user_role'] = $this->Role_model->GetId($id);
$this->form_validation->set_rules('role', 'Role', 'required');
if ($this->form_validation->run() == false) {
$this->load->view('templates/header', $data);
$this->load->view('templates/sidebar', $data);
$this->load->view('templates/topbar', $data);
$this->load->view('admin/edit', $data);
$this->load->view('templates/footer');
} else {
$this->Role_model->EditRole();
$this->session->set_flashdata('message', '<div class="alert alert-success" role="alert">Role Edited!</div>');
redirect('admin/role');
}
}
view :
<div class="card-body">
<?= $this->session->flashdata('message'); ?>
<form action="<?= base_url('admin/edit/');?>" method="post">
<input type="hidden" name="id" value="<?= $user_role['id']; ?>">
<div class="form-group text-gray-900">
<label for="role">Edit Role</label>
<input type="text" class="form-control" id="role" name="Role" value="<?= $user_role['role']; ?>">
<?= form_error('role', ' <small class="text-danger pl-3">', '</small>'); ?>
</div>
</div>
and it display like this
An uncaught Exception was encountered
Type: ArgumentCountError
Message: Too few arguments to function Admin::edit(), 0 passed in
C:\xampp\htdocs\KingflowWP2\system\core\CodeIgniter.php on line 532 and exactly 1 expected
Let me explain to you.
Edit function needs one parameter (i.e. id). In your form, you are submitting the form without id.
You just need to add the id at the end of the URL like below. Suppose id is 2 then you have to add 2.
base_url('admin/edit/2')
<form action="<?= base_url('admin/edit/2');?>" method="post">
You are only passing $id in
$this->usermodel->Role_model($get['id']);
You have to change your function if you want to post value in hidden input. Oner more thing you have to use default argument if you are not sure about the data is present or not. Always check step by step that data is present or not than do anything.
Write echo here so you get the value in hidden field
<input type="hidden" name="id" value="<?php echo $user_role['id']; ?>">
After that change in the function:
public function edit()
{
$id = $this->input->post('id');
$data['title'] = 'Role';
$data['user'] = $this->db->get_where('user', ['email' => $this->session->userdata('email')])->row_array();
if(!empty($id)):
$data['user_role'] = $this->Role_model->GetId($id);
else:
//some error message
endif;
$this->form_validation->set_rules('role', 'Role', 'required');
if ($this->form_validation->run() == false) {
$this->load->view('templates/header', $data);
$this->load->view('templates/sidebar', $data);
$this->load->view('templates/topbar', $data);
$this->load->view('admin/edit', $data);
$this->load->view('templates/footer');
} else {
$this->Role_model->EditRole();
$this->session->set_flashdata('message', '<div class="alert alert-success" role="alert">Role Edited!</div>');
redirect('admin/role');
}
}

Codeigniter validation errors are not displaying

My codeigniter validation errors are not displaying someone can help?
my code is
public function addProduct(){
$this->load->view('header', $this->data);
$this->load->view('product/addProduct');
$this->load->view('footer');
$this->form_validation->set_rules('productName', 'Product Name', 'required|trim');
$this->form_validation->set_rules('productPrice', 'Product Price', 'required|trim');
if (!$this->form_validation->run() == FALSE)
{
// some stuff on validation success
}
else{
$this->load->view('product/addProduct');
}
}
and i have added
echo validation_errors(); in my view and action of the form is product/addProduct.
Try this it's work for you.
form_error() function return your form error.
$post_fields = $this->input->post();
$data['msg'] = '<ul>';
foreach ($post_fields as $k => $v) {
if (form_error($k))
$data['msg'] .= "<li>" . strip_tags(form_error($k)) . "</li>\n";
}
$data['msg'].='</ul>';
$this->load->view('product/addProduct',$data);
OR
echo validation_errors();//this function also return form error.
On view example
<?php echo validation_errors('<div class="error">', '</div>'); ?>
<!-- lower case for the controller name on form open -->
<?php echo form_open_multipart('product/addProduct');?>
<h5>productName</h5>
<input type="text" name="productName" value="<?php echo set_value('productName'); ?>" size="50" />
<h5>productPrice</h5>
<input type="text" name="productPrice" value="<?php echo set_value('productPrice'); ?>" size="50" />
<div><input type="submit" value="Submit" /></div>
<?php echo form_close();?>
Controller
Make sure your file name and class name is something like this below where first letter only upper case
Guide
Filename: Product.php
<?php
class Product extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->library('form_validation');
$this->load->helper('form');
$this->load->helper('url');
}
public function addProduct(){
// You can get data from here also
$this->data['some'] = 'Blah';
$this->form_validation->set_rules('productName', 'Product Name', 'required|trim');
$this->form_validation->set_rules('productPrice', 'Product Price', 'required|trim');
// remove your !
if ($this->form_validation->run() == FALSE){
// You can just display view in this area you do not have to load it multiple times
$this->load->view('header', $this->data);
$this->load->view('product/addProduct');
$this->load->view('footer');
} else {
// some stuff on validation success
}
}
}
Also check you have set your base url in config.php is required now in CI3 versions.

Codeigniter form validation is not showing errors

I'm new to Codegniter so go easy on me. I'm building a simple login form and I have successfully redirected to a page when the login credentials are correct. However, if I submit an empty form I get no error messages. I'm also using set_value in the form field and codeigniter does not refill what the user inputted once the form is submitted. Somehow that data is being cleared. Here are a few things i've done for clarity sake.
Auto-loaded the form_validation library
Auto-loaded form helper
Echoed validation_errors above form
account.php (controller)
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Account extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('User_model', 'user');
}
public function index() {
$this->load->view('home');
}
public function validate() {
$this->form_validation->set_rules('username', 'username', 'xss_clean|required');
$this->form_validation->set_rules('password', 'password', 'xss_clean|required|md5');
$user_data = array(
'username' => $this->input->post('username'),
'password' => MD5($this->input->post('password'))
);
if ($this->form_validation->run() == FALSE)
{
$data['title'] = "Login Fool";
$this->load->view('templates/header', $data);
$data['contents'] = $this->load->view('login_view', $data, TRUE);
$this->load->view('page', $data);
$this->load->view('templates/footer');
}
else
{
$validated = $this->user->validate($user_data['username'], $user_data['password']);
if($validated){
redirect(base_url() . 'account');
}
else{
$this->session->set_flashdata('LoginError', 'Sorry, your credentials are incorrect.');
redirect(base_url() . 'account/login');
}
}
}
public function login() {
$data['title'] = "Login Fool";
$this->load->view('templates/header', $data);
$data['contents'] = $this->load->view('login_view', NULL, TRUE);
$this->load->view('page', $data);
$this->load->view('templates/footer');
}
}
login_view.php (view)
<h1>Login Now</h1>
<?php
if(validation_errors() != false) {
echo "<div id='errors'>" . validation_errors() . "</div>" ;
}
?>
<?= ($this->session->flashdata('LoginError')) ? '<p class="LoginError">' . $this->session->flashdata('LoginError') . '</p>' : NULL ?>
<?php echo form_open('account/validate'); ?>
<label for="username">Username:</label>
<input type="text" size="20" id="username" name="username" value="<?php echo set_value('username'); ?>"/>
<br/>
<label for="password">Password:</label>
<input type="password" size="20" id="passowrd" name="password" value="<?php echo set_value('password'); ?>"/>
<br/>
<input type="submit" value="Login"/>
</form>
Any ideas why the errors won't show above the form?
Turns out my model was the culprit. It was extending CI_Controller not CI_Model. Thanks to everyone who took a look at this. This code works.

CodeIgniter update record

Controler
//class News
public function update($slug)
{
$this->load->helper('form');
$this->load->library('form_validation');
$data['news_item']=$this->news_model->get_news($slug);
if (empty($data['news_item']))
{
show_404();
}
$data['title'] = $data['news_item']['title'];
$this->load->view('templates/header', $data);
$this->load->view('news/update', $data);
//$this->load->view('save',$save);
$this->load->view('templates/footer');
}
Model new_model.php
//class News_model
public function get_news($slug = FALSE)
{
if($slug === FALSE)
{
$query = $this->db->get('news');
return $query->result_array();
}
$query = $this->db->get_where('news',array('slug'=>$slug));
return $query->row_array();
}
public function update_news($slug)
{
$query=$this->db->where('slug', $slug);
$this->db->update('news' ,$query);
return $query->row_array();
}
in update.php view file code given below..
view update.php file
<h2>Update New Item</h2>
<?php echo form_open('news/update') ?>
<label for="title">Title</label>
<input type="input" name="title" value="<?php echo $news_item['title']; ?>" readonly/><br>
<label for="text">Text</label>
<textarea name="text" cols="35" rows="16"><?php echo $news_item['text'];?></textarea><br>
save
</form>
data will be fetch but problemb is that when i click on "save" link page not found error generatos why?
how can call this view save.php file..
Change
save
to
<input type="submit" value="save" />
Here you have used link in-place of submit button.
When you use submit button it will post/get data on url that is there in the form action.
Here you can use :
<?php echo form_submit('mysubmit', 'Submit Post!'); ?>
It will produce...
<input type="submit" name="mysubmit" value="Submit Post!" />
For more details : Form Helper

insert and update in single form in CodeIgniter

Here I have controller news.php:
<?php
class News extends CI_Controller{
public function __construct(){
parent::__construct();
$this->load->model('news_model');
$this->load->helper('url_helper');
}
public function index(){
$data['news'] = $this->news_model->get_news();
$data['title'] = 'News archive';
$this->load->view('templates/header', $data);
$this->load->view('news/index', $data);
$this->load->view('templates/footer');
}
public function view($slug = NULL)
{
$data['news_item'] = $this->news_model->get_news($slug);
if (empty($data['news_item']))
{
show_404();
}
$data['title'] = "News in Detail(s)";
$this->load->view('templates/header', $data);
$this->load->view('news/view', $data);
$this->load->view('templates/footer');
}
public function create()
{
$this->load->helper('form');
$this->load->library('form_validation');
$data['title'] = 'Create a news item 22';
$this->form_validation->set_rules('title', 'Title', 'required');
$this->form_validation->set_rules('text', 'Text', 'required');
$data['updateid'] = '' ;
if ($this->form_validation->run() === FALSE)
{
$this->load->view('templates/header', $data);
$this->load->view('news/create');
$this->load->view('templates/footer');
}
else
{
$this->news_model->set_news();
if($update == 1){
redirect('/news', 'location');
}
}
}
public function update($id){
$this->load->helper('form');
$this->load->library('form_validation');
$data['updateid'] = $id;
$data['title'] = "Update News in Detail(s)";
$data['update'] = $this->news_model->edit_load_data($id);
$this->load->view('news/create',$data);
if ($this->input->post('submit')) {
$update = $this->news_model->update_news($id);
if($update == 1){
redirect('/news', 'location');
}
}
}
}
?>
Here my model file news_model.php:
<?php
class News_model extends CI_Model{
public function __construct(){
$this->load->database();
}
public function get_news($slug= false){
if($slug == false){
$query= $this->db->get('news');
return $query->result_array();
}
$query = $this->db->get_where('news', array('slug' => $slug));
return $query->row_array();
}
public function set_news(){
$this->load->helper('url');
$slug = url_title($this->input->post('title'), 'dash', TRUE);
$data = array(
'title' => $this->input->post('title'),
'slug' => $slug,
//'text' => $this->input->post('text')
'text' => $this->input->post('select')
);
return $this->db->insert('news', $data);
}
public function edit_load_data($id){
$query = $this->db->get_where('news', array('id' => $id));
return $query->row_array();
}
public function update_news($id){
$this->load->helper('url');
$slug = url_title($this->input->post('title'), 'dash', TRUE);
$data = array(
'title' => $this->input->post('title'),
'slug' => $slug,
//'text' => $this->input->post('text')
'text' => $this->input->post('select')
);
$this->db->where('id', $id);
return $this->db->update('news', $data);
}
}
?>
Here my form create.php file:
<?php echo validation_errors();
echo $updateid;
?>
<?php if($updateid == ''){ ?>
<?php echo form_open('news/create'); ?>
<?php } else { ?>
<?php echo form_open('news/update/'.$updateid); ?>
<?php } ?>
<label for="title">Title</label>
<input type="input" name="title" value="<?php echo $update['title']; ?>" /><br />
<label for="text">Text</label>
<textarea name="text" ><?php echo set_value('text'); ?></textarea><br />
<label for="text">Select</label>
<select name="select">
<option <?php if($update['text']=='text1'){ echo "selected";} ?> value="text1">text1</option>
<option <?php if( $update['text']=='text2'){ echo "selected";} ?> value="text2">text2</option>
</select>
<br />
<input type="submit" name="submit" value="Create news item" />
</form>
Here when I am going news/create in gives error:
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: update
Filename: news/create.php
Line Number: 15
Backtrace:
File: C:\xampp\htdocs\mylab\application\views\news\create.php Line: 15
Function: _error_handler
File: C:\xampp\htdocs\mylab\application\controllers\News.php Line: 54
Function: view
File: C:\xampp\htdocs\mylab\index.php Line: 315 Function: require_once
" />
What can I do for that? I want add and edit for same file create.php
is it possible there?
I don't know that this will produce the outcome you want but it will prevent the use of undefined variables.
<?php
echo validation_errors();
$updateid = isset($updateid) ? $updateid : '';
echo $updateid;
if($updateid == '')
{
echo form_open('news/create');
}
else
{
echo form_open('news/update/'.$updateid);
}
if(!isset($update))
{
$update['title'] = NULL;
$update['slug'] = NULL;
$update['text'] = NULL;
}
?>
<label for="title">Title</label>
<input type="input" name="title" value="<?php echo $update['title']; ?>" /><br />
<label for="text">Text</label>
<textarea name="text" ><?php echo set_value('text'); ?></textarea><br />
<label for="text">Select</label>
<select name="select">
<option <?php
if($update['text'] == 'text1')
{
echo "selected";
}
?> value="text1">text1</option>
<option <?php
if($update['text'] == 'text2')
{
echo "selected";
}
?> value="text2">text2</option>
</select>
<br />
<input type="submit" name="submit" value="Create news item" />
</form>
You should probably modify your model so that it returns a default array if/when the inputs are not present. I am not able to identify where you are sending $update to the view either.
I think you're not returning $update['title'], $update['text'], etc.. You are returning $title, $text...
Try changing $update['title'] to $title in create.php to see what
happens

Categories