How to get validation errors in codeigniter? - php

Hello I am inserting data in database. When I insert both category and description then data in inserting but when I don't insert in the category and description input and click on create then no error showing with blank page admin/category/ register_category, I want to show that category and description field should not be empty.
category.php view page is below :
<?php if(isset($_SESSION['success'])){ ?>
<div class="alert alert-success"><?php echo $_SESSION['success']; ?>
</div>
<?php } ?>
<?php echo validation_errors('<div class="alert alert-danger">','</div>'); ?>
<form class="form" action="<?php echo site_url('admin/category/register_category') ?>" method="POST">
<label for="contactinput5">Category Name</label>
<input class="form-control border-primary" type="text" placeholder="category" name="category" id="contactinput5">
<label for="contactinput5">Discription</label>
<textarea class="form-control border-primary" type="text" placeholder="discription" name="discription" id="contactemail5"></textarea>
<button type="submit" name="create" class="btn btn-primary">
and my controller Category.php page is:
<?php
class Category extends CI_Controller {
function index() {
$this->load->view('admin/category');
}
function register_category() {
$this->form_validation->set_rules('category', 'Category', 'required');
$this->form_validation->set_rules('discription', 'Discription', 'required');
if($this->form_validation->run() == TRUE){
echo "form validate";
$this->load->model('categories');
$insert_category = $this->categories->validate();
if($insert_category){
$this->session->set_flashdata("success","Your data has been added");
redirect("admin/category","refresh");
}
else{
redirect('admin/category');
}
}
}
}
?>
model categories page:
<?php
class Categories extends CI_Model
{
function validate()
{
$arr['categoryname'] = $this->input->post('category');
$arr['discription'] = $this->input->post('discription');
return $this->db->insert('category',$arr);
}
}
?>

If validation result is not true, you can get errors from $this->form_validation->error_array(), loop the return array and show the error to the user.
Hope this help.

hey guys thanks and i got my answer just by putting this code
if($this->form_validation->run() == FALSE)
{
$this->index();
}

Hello Please update your function in the controller. There is issue in validation condition Changes TURE to FALSE. Check below code.
function register_category()
{
$this->form_validation->set_rules('category', 'Category', 'required');
$this->form_validation->set_rules('discription', 'Discription', 'required');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('category');
}
else
{
$this->load->model('categories');
$insert_category = $this->categories->validate();
if($insert_category)
{
$this->session->set_flashdata("success","Your data has been added");
redirect("admin/category","refresh");
}
else
{
redirect('admin/category');
}
}
}

Get all post validation errors in controller :
echo validation_errors();
If you want to show at the end of textbox use this following method :
<label for="contactinput5">Category Name</label>
<input class="form-control border-primary" type="text" placeholder="category" name="category" id="contactinput5">
<?php echo form_error('category', '<div class="error">', '</div>'); ?>

FYI your solution only worked because validation_errors() only applies to the current instance. When you redirect that information is lost. You would have to store it in session variable or this is common (change form action to self or leave blank):
function index() {
if ($_POST) {
$this->form_validation->set_rules('category', 'Category', 'required');
$this->form_validation->set_rules('discription', 'Discription', 'required');
if($this->form_validation->run() == TRUE){
$this->load->model('categories');
$insert_category = $this->categories->validate();
if($insert_category){
$this->session->set_flashdata("success","Your data has been added");
}
}
}
$this->load->view('admin/category');
}
Of course your way works too if you are ok with the url changing.

Related

ArgumentCountError Codeigniter

I am trying to target an edit on the standardId property of the DB. For now I am manually typing the ID value into the Input field for standard ID but ideally I will have the property as not visible eventually.
When attempting to edit existing properties in DB I receive the following error:
Type: Argument Count Error
Message: Too few arguments to function Standards::edit(), 0 passed in D:\xamp\htdocs\myisogo\system\core\CodeIgniter.php on line 532 and exactly 1 expected
Filename: D:\xamp\htdocs\myisogo\application\controllers\Standards.php
Line Number: 39
Model:
public function edit_standard()
{
$this->load->helper('url');
$data = array(
'standardid' => $this->input->post('standardId'),
'standardcode' => $this->input->post('standardCode'),
'standardname' => $this->input->post('standardName')
);
return $this->db->insert('isostandard', $data);
}
Controller:
$this->load->helper('form');
$this->load->library('form_validation');
$data['standard'] = $this->standard_model->get_standard_byId($standard_id);
$this->form_validation->set_rules('standardId', 'standardid', 'required');
$this->form_validation->set_rules('standardCode', 'standardcode', 'required');
$this->form_validation->set_rules('standardName', 'standardname', 'required');
if ($this->form_validation->run() === FALSE)
{
$this->load->view('templates/header');
$this->load->view('templates/navbar');
$this->load->view('standards/edit', $data);
$this->load->view('templates/footer');
}
else
{
$this->standard_model->edit_standard();
$this->load->view('standards/success');
}
View:
<?php echo form_open('standards/edit'); ?>
<h1>Amend Existing standard </h1>
<h2><?php echo $standard['standardId']; ?></h2>
<label for = "title"> Standard ID </label>
<input type="input" name = "standardId"/><br />
<label for="title">Standard Code</label>
<input type="input" name="standardCode" /><br />
<label for="text">Standard Title</label>
<textarea name="standardName"></textarea><br />
<input type="submit" name="submit" value="Create new standard" />
</form>
I am assuming that your method from Standards::edit is:
public function edit($standard_id)
$this->load->helper('form');
$this->load->library('form_validation');
$data['standard'] = $this->standard_model->get_standard_byId($standard_id);
$this->form_validation->set_rules('standardId', 'standardid', 'required');
$this->form_validation->set_rules('standardCode', 'standardcode', 'required');
$this->form_validation->set_rules('standardName', 'standardname', 'required');
if ($this->form_validation->run() === FALSE)
{
$this->load->view('templates/header');
$this->load->view('templates/navbar');
$this->load->view('standards/edit', $data);
$this->load->view('templates/footer');
}
else
{
$this->standard_model->edit_standard();
$this->load->view('standards/success');
}
}
In this case $standard_id is always required. Right?
But the problem is your form_open. You are passing an URL without the id.
<?php echo form_open('standards/edit'); ?>
With this, when you submit the form, you'll submit to //localhost/standards/edit, but COdeIgniter only accepts //localhost/standards/edit/<some_id_here>.
You have two choices
Do not pass url to form_open, since you are not posting to other endpoint.
<?php echo form_open(); ?>
Edit your form_open and concat the id
<?php echo form_open("standards/edit/{$standard['standardId']}"); ?>
I stick with the first one.
If you want to make a parameter optional you need to assign the default value public function edit($standard_id=null)

Insert into DB with codeigniter 3

im trying to add new post into my db. I have Model, Controller and View created. Actualy im using rest api for this, but now I want to do it with pure php powerd.
But After form validation is nothing. So when I try to post, nothuing happens.
Here is my code.
Model:
// Create
function create($data) {
// Insert data into DB
$this->db->insert('blog', $data);
return $this->db->insert_id();
}
Controller:
public function add() {
if ($this->ion_auth->is_admin()) {
// Validation rules
$this->form_validation->set_rules('title', 'Titel', 'required');
$this->form_validation->set_rules('teaser', 'Teaser', 'required');
$this->form_validation->set_rules('full', 'Volltext', 'required');
if (($this->form_validation->run() == FALSE)) {
$this->load->view('templates/backend/header', $this->data);
$this->load->view('pages/backend/blog/add', $this->data);
$this->load->view('templates/backend/footer');
} else {
if($this->input->post()) {
$data = array(
'title' => $this->input->post('title'),
'teaser' => $this->input->post('teaser'),
'full' => $this->input->post('full')
);
$this->blog_model->create($data);
redirect(base_url().'blog/');
}
}
} else {
redirect('login');
}
}
And at least my view:
<div class="uk-margin-top">
<?php $attributes = array("class" => "uk-panel uk-panel-box uk-form uk-margin-lage-bottom", "id" => "add-form", "method" => "post");
echo form_open("/backend/blog/add", $attributes); ?>
<div class="uk-form-row">
<label class="uk-form-label" for="title">Title</label>
<input id="title" class="uk-width-1-1 uk-form-large title redactor-box" name="title" placeholder="Beitragstitel" type="text"
value="<?php echo set_value('title'); ?>"/>
<span class="uk-text-danger"><?php echo form_error('title'); ?></span>
</div>
<div class="uk-form-row">
<label class="uk-form-label" for="teaser">Teaser</label>
<textarea id="teaser" class="uk-width-1-1 uk-form-large teaser redactor-box" name="teaser" data-uk-htmleditor></textarea>
<span class="uk-text-danger"><?php echo form_error('teaser'); ?></span>
</div>
<div class="uk-form-row">
<label class="uk-form-label" for="body">Body</label>
<textarea id="full" name="full" rows="4" placeholder="Ihre Nachricht"
value="<?php echo set_value('full'); ?>"></textarea>
<span class="uk-text-danger"><?php echo form_error('full'); ?></span>
</div>
<div class="uk-form-row">
<a class="uk-button uk-button-success" data-action="add-post">Submit</a>
</div>
<?php echo form_close(); ?>
</div>
So my problem is, when I click on my submit button - nothing. Maybe you can show me where my problem is.
Thank you!
For your controller, I think you are missing the form helper and validation library. I have included other comments in the code, but try this:
public function add() {
// you need to load these in:
$this->load->helper('form');
$this->load->library('form_validation');
// I am assuming ion_auth is working, however, I would try this code without
// this conditional statement
if ($this->ion_auth->is_admin()) {
// Validation rules
// Make sure the second parameter is right. I think Titel should be Title.
$this->form_validation->set_rules('title', 'Titel', 'required');
$this->form_validation->set_rules('teaser', 'Teaser', 'required');
$this->form_validation->set_rules('full', 'Volltext', 'required');
// added a triple === instead of == for stricter type checking
if (($this->form_validation->run() === FALSE)) {
// I am assuming $this->data is a property of your controller class
$this->load->view('templates/backend/header', $this->data);
$this->load->view('pages/backend/blog/add', $this->data);
$this->load->view('templates/backend/footer');
} else {
// Check if the form was submitted via $_POST method
if($this->input->post()) {
// I removed your $data array and created it in the model.
// I added a condition here to check if the data was successfully inserted
if ($this->blog_model->create()) {
redirect(base_url().'blog/');
} else {
// output an error message or redirect
}
}
}
} else {
redirect('login');
}
}
For your model, I think you were not passing any data to your model. Try the following for your model:
public function create()
{
// you need to pass an array of data or an object
// the array key corresponds to your db table column
// the array value corresponds to your views input field names
$data = array(
'name' => $this->input->post('title'),
'teaser' => $this->input->post('teaser'),
'full' => $this->input->post('full')
);
// returns true or false
return $this->db->insert('blog', $data);
}

Form Validation & Re-Populating Field Values After Redirect Error; Validation Works, But Values Doesn't (CodeIgniter 3)

I am trying to keep field values after validation errors on redirect. Validation error shows fine but I keep loosing field values
Form:
<form>
<input name="v_item_title" placeholder="Property Title Goes Here.." value="<?php echo set_value('v_item_title'); ?>" />
<input type="submit" value="Submit">
</form>
Controller:
$this->load->helper('security');
$this->load->library('form_validation');
$this->form_validation->set_rules('v_item_title', 'Property title', 'trim|required|xss_clean|max_length[100]');
if($this->form_validation->run() == FALSE)
{
$this->session->set_userdata('validation_errors', validation_errors());
$this->session->mark_as_flash('validation_errors'); // data will automatically delete themselves after redirect
$this->session->set_flashdata('v_item_title', $this->input->post());
$this->session->flashdata('v_item_title');
redirect('user/dashboard#new');
} else {
Redirects to
public function dashboard()
{
if($this->session->userdata('is_logged_in')){
$data['validation_errors'] = $this->session->userdata('validation_errors');
$data['v_item_title'] = $this->session->userdata('v_item_title');
$data['homepage'] = '../../templates/vacations/users/dashboard';
$this->load->view('template_users',$data);
}else{
You have form validation wrong on controller you have your success info on false area it should be in true area like
http://www.codeigniter.com/user_guide/libraries/form_validation.html
Not sure what your controller name is so I named example login
application > controllers > Login.php
<?php
class Login extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper('form');
$this->load->helper('url');
$this->load->helper('security');
$this->load->library('session');
$this->load->library('form_validation');
}
public function index() {
$data['title'] = 'Login';
$this->form_validation->set_rules('name_check_box', '', 'trim|required|callback_checkbox');
$this->form_validation->set_rules('v_item_title', 'Property title', 'trim|required|xss_clean|max_length[100]');
if($this->form_validation->run() == FALSE) {
// Load the view
$this->load->view('header', $data);
$this->load->view('login', $data);
$this->load->view('footer');
} else {
$data = array(
'is_logged_in' => true,
'validation_errors' => validation_errors(),
'v_item_title' => $this->input->post('v_item_title')
);
$this->session->set_userdata($data);
// data will automatically delete themselves after redirect
$this->session->mark_as_flash('validation_errors');
// You could set the title in session like above for example
$this->session->set_flashdata('v_item_title', $this->input->post('v_item_title'));
// Echo flash data on view file?
// $this->session->flashdata('v_item_title');
// Dashboard will be a separate controller
// application > controllers > user > Dashboard.php
redirect('user/dashboard');
}
public function checkbox() {
if (isset($_POST['name_check_box']) {
return true;
} else {
$this->form_validation->set_message('checkbox', 'Check box needs to be checked');
return false;
}
}
}
View
http://www.codeigniter.com/user_guide/helpers/form_helper.html
<?php echo form_open('login');?>
<input name="v_item_title" placeholder="Property Title Goes Here.." value="<?php echo set_value('v_item_title'); ?>" />
<input type="checkbox" name="name_check_box"> Something <br>
<input type="submit" value="Submit">
<?php echo form_close();?>
Note: you may need to set custom routes in application > config >
routes.php
http://www.codeigniter.com/user_guide/general/routing.html
Try this
VIEW
<form>
<input name="v_item_title" placeholder="Property Title Goes Here.." value="<?php echo $this->session->flashdata('v_item_title'); ?>" />
<input type="submit" value="Submit">
</form>
Make sure that you load the session library and form helper
i have same issue. i applied this logic and its works for me
Change your add and edit method like this...
public function add(){
$college = $this->session->flashdata('data');
$this->load->view("college_add", compact('college'));
}
public function edit(){
$college_id = $this->uri->segment(3);
if($college_id)
{
$college = $this->session->flashdata('data');
if(empty($college))
$college = $this->college->get_college_details_secure($college_id);
$this->load->view('college_add', compact('college'));
}
else
redirect('college/add');
}
And Your save method redirect like this..
if ($this->form_validation->run() != TRUE)
{
$this->set_flashdata("message","Ooopps... form validation failed.".validation_errors());
$this->session->set_flashdata('data', $this->input->post());
if($college_id == '')
redirect("college/add");
else
redirect("college/edit/$college_id");
}

codeigniter form not submitting data

I have tried everything I can think of but whenever I click submit the form passes on a null value, I dont know if it is the problem with the form or the controller or even the view. I changed this->input->post to posted data and i get an error of undefined variable posted data, please help.
Controller:
public function addmenu(){
$this->load->model('organizer_model');
$data = array(
'menu_name' => $this->input->post('menu name'),
'price' => $this->input->post('price'),
'email' => $this->session->userdata('email')
);
if($this->organizer_model->insertmenu($data)) {
$this->session->set_flashdata('message', 'Your menu has been added');
redirect('/menu/index', 'refresh');
} else {
$this->session->set_flashdata('message', 'Your menu was not added, please try again');
redirect('/menu/index', 'refresh');
}
View:
<form action="<?php echo site_url('Organizer/addmenu'); ?>" method="post" class="form-horizontal no-margin">
<div class="control-group">
<label class="control-label" for="menuname">
Menu Name
</label>
<div class="controls controls-row">
<input class="span3" name="data[menuname]" type="text" placeholder="Enter menu Name">
</div>
</div>
<div class="control-group">
<label class="control-label" for="price">
Price
</label>
<div class="controls controls-row">
<input class="span3" name="data[price]" type="text" placeholder="">
</div>
</div>
<div class="form-actions no-margin">
<button type="submit" name="submit" class="btn btn-info pull-right">
Add menu
</button>
<div class="clearfix">
</div>
</div>
</form>
Model:
public function insertmenu($data) {
$condition = "email = '" . $data['email'] . "'";
$this->db->select('organizer_id');
$this->db->from('organizer');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() > 0){
array_pop($data); //will remove email from data
$row = $query->row();
$data['organizer_id'] = $row->organizer_id;
$this->db->insert('menu', $data);
if ($this->db->affected_rows() > 0) {
return true;
} else {
return false;
}
} else {
return false;
}
}
I notice same question here codeigniter- insert data into db not working
Checks
Make sure you load your form helper and url helper.
Make sure you use form validation when submitting form in codeigniter on controller.
From this php user guide here http://php.net/manual/en/reserved.variables.post.php
Example on your input would be like person[0][first_name]
<form action="" method="">
<input type="text" name="data_posts[0][menu_name]" placeholder="Enter menu Name">
<input type="text" name="data_posts[0][price]" placeholder="">
</form>
Model
<?php
class Model_something extends CI_Model {
public function add_menu() {
$data_posts = $this->input->post('data_posts');
foreach ($data_posts as $data_post) {
$data = array(
'email' => $this->session->userdata('email'),
'menu_name' => $data_post['menu_name'],
'price' => $data_post['price']
);
$this->db->insert('tablename', $data);
}
}
}
Controller
<?php
class Add_menu extends CI_Controller {
public function index() {
$this->load->helper('form');
$this->load->helper('url');
$this->load->library('form_validation');
$data_posts = $this->input->post('data_posts');
foreach ($data_posts as $data_post) {
$this->form_validation->set_rules('data_posts['.$data_post.'][menu_name]', 'Menu Name', 'required');
$this->form_validation->set_rules('data_posts['.$data_post.'][price]', 'Price', 'required');
}
if ($this->form_validation->run() == FALSE) {
$this->load->view('some_view');
} else {
$this->load->model('model_something');
$this->model_something->add_menu();
redirect('to_success_page');
}
}
}
You could also check if has been inserted by using callback function
Codeigniter 3 user guide form validation http://www.codeigniter.com/user_guide/libraries/form_validation.html
Codeigniter 2 user guide form validation http://www.codeigniter.com/userguide2/libraries/form_validation.html
Also you should upgrade to the new bootstrap I see your using old version.

CodeIgniter form validation helper always false

I am working with Codeigniter and on top of it I have Bonefire (could this be the problem?), problem is everytime I want to validate the form with the use of Codeigniters helpers first condition of my conditional runns (FALSE) and on top of that function validation_errors() isn't ran... It is like my libraries for this helper aren't even loaded, despite doing everything by the book:
if ($this->form_validation->run() == FALSE)
{
echo $msg = validation_errors();
}
else
{
$this->load->user_model->insert($data);
echo $msg = "Registration successfull";
}
Let me post my form first (I ommited inline styles and classes by purpose):
<div class="" style="">
<h1 id="header" class="">Login/Register</h1>
<form action="/public/index.php/users/sportappregister" >
<div style=""><input id="email" type="text" name="email" value="email" style=""></div>
<div style=""><input id="pass" type="text" name="password" value="password" style=""></div>
<div style="" class=""><img class="" style="" src="<?php echo img_path(); ?>ikone/fb_login_icon.png" />Login with Facebook</div>
<div id="send" style="" class=""><input type="submit"> Submit </div>
<div id="cancel" style="" class=""> Cancel </div>
</form>
</div>
And as you can read from form action my controller is located in file "users" under public class "sportappregister", class Users extends Front_Controller as usuall and in this class at the end I make my own function to handle form like so:
public function sportappregister(){
$email= ($this->input->get("email"));
$pass = ($this->input->get("password"));
$data = array(
"email" => $email,
"password" => $pass );
// here I load my helper
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
// rules for my form
$this->form_validation->set_rules('email', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if ($this->form_validation->run() == FALSE)
{
echo $msg = validation_errors();
}
else
{
$this->load->user_model->insert($data);
echo $msg = "Registration successfull";
}
}
You are using `GET` method. codeigniter form validation works with `POST` method only.
use CI form tags such as form_open() form_close() etc. to build form.
you can check This link
using get for login form will make your app insecure.
rest of your code seems ok to me.
just change this
$email= ($this->input->post("email")); //changed get to post in both
$pass = ($this->input->post("password"));
There's a few things I would change. Read the comments in the amended function below;
public function sportappregister()
{
// Load these first
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
// Now set the rules
$this->form_validation->set_rules('email', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if ( $this->form_validation->run() == false )
{
echo validation_errors();
}
else
{
// Build the array after the form validation
$data = array(
'email' => $this->input->post('email'), // POST, not GET
'password' => $this->input->post('password')
);
// Load your model
$this->load->model('users_model');
if ( $this->users_model->insert($data) )
{
echo 'Registration successful';
}
else
{
echo 'Registration failed';
}
}
}
You have also loaded the form helper, but you're not using it. It makes building forms much, much easier.
http://ellislab.com/codeigniter/user-guide/helpers/form_helper.html
<?php echo form_open('users/sportappregister'); ?>

Categories