Uploading image from one function - php

I have a edit function on my users codeigniter project, I would like to be able to use that one function for uploading images as well but user guide says to create a new function.
How am I able to make it with same edit() function.
function edit($user_id = 0) {
$this->load->model('users/model_user');
$data['title'] = "Users";
$data['base'] = config_item('HTTP_SERVER');
$data['isLogged'] = $this->user->isLogged();
$data['last_updated'] = $this->model_user->last_updated($user_id);
$data['user_id'] = $user_id;
if (!empty($this->input->post('username'))) {
$data['username'] = $this->input->post('username');
} else {
$data['username'] = $this->model_user->getUserByUsername($user_id);
}
if (!empty($this->input->post('firstname'))) {
$data['firstname'] = $this->input->post('firstname');
} else {
$data['firstname'] = $this->model_user->getUserByFirstname($user_id);
}
if (!empty($this->input->post('lastname'))) {
$data['lastname'] = $this->input->post('lastname');
} else {
$data['lastname'] = $this->model_user->getUserByLastname($user_id);
}
if (!empty($this->input->post('email'))) {
$data['email'] = $this->input->post('email');
} else {
$data['email'] = $this->model_user->getUserByEmail($user_id);
}
// User userfile
if(!empty($this->input->post('userfile'))) {
$data['userfile'] = $this->input->post('userfile');
} else {
$data['userfile'] = $this->model_user->getUserImage($user_id);
}
$config['upload_path'] = base_url('image/catalog/'); // base_url('image/catalog/');
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1000';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
if (!$this->upload->do_upload()) {
$data['error'] = $this->upload->display_errors();
$data['header'] = $this->load->view('template/common/header', $data, TRUE);
$data['footer'] = $this->load->view('template/common/footer', NULL, TRUE);
return $this->load->view('template/users/users_form', $data);
} else {
$data['upload_data'] = $this->upload->data();
$data['header'] = $this->load->view('template/common/header', $data, TRUE);
$data['footer'] = $this->load->view('template/common/footer', NULL, TRUE);
return $this->load->view('template/users/users_form', $data);
}
$this->load->library('password');
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Your Username');
$this->form_validation->set_rules('firstname', 'Your First Name');
$this->form_validation->set_rules('lastname', 'Your Last Name');
$this->form_validation->set_rules('email', 'Your Email');
if ($this->form_validation->run() == TRUE) {
$this->model_user->editUser($user_id, $data);
redirect('users');
} else {
$data['header'] = $this->load->view('template/common/header', $data, TRUE);
$data['footer'] = $this->load->view('template/common/footer', NULL, TRUE);
return $this->load->view('template/users/users_form', $data);
}
}
View File
<?php echo validation_errors('<div class="alert alert-danger">', '</div>'); ?>
<?php echo $error ;?>
<?php
$data = array(
'role' => "form",
'class' => 'form-horizontal'
);
echo form_open('users/edit/' . $user_id, $data);
?>
<div class="form-group">
<label for="input-username" class="col-sm-2 control-label">Username</label>
<div class="col-sm-10">
<input type="text" name="username" value="<?php echo $username;?>" class="form-control">
</div>
</div>
<div class="form-group">
<label for="input-firstname" class="col-sm-2 control-label">Firstname</label>
<div class="col-sm-10">
<input type="text" name="firstname" value="<?php echo $firstname;?>" class="form-control">
</div>
</div>
<div class="form-group">
<label for="input-lastname" class="col-sm-2 control-label">Lastname</label>
<div class="col-sm-10">
<input type="text" name="lastname" value="<?php echo $lastname;?>" class="form-control">
</div>
</div>
<div class="form-group">
<label for="input-email" class="col-sm-2 control-label">Email</label>
<div class="col-sm-10">
<input type="text" name="email" value="<?php echo $email;?>" class="form-control">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label" for="input-image"></label>
<div class="col-lg-3">
<div class="thumbnail">
<img src="<?php echo $userfile;?>">
</div>
</div>
</div>
<div class="form-group">
<label for="input-image" class="col-sm-2 control-label">Image</label>
<div class="col-sm-10">
<br>
<input type="file" name="userfile" value="<?php echo $userfile;?>" size="20">
</div>
</div>
<div class="form-group">
<div class="text-right">
<h2><a href="<?php echo base_url('users/edit_password/' . $user_id);?>">Change Your Password</h2>
<button type="submit" name="submit" class="btn btn-primary">Submit</button>
</div>
</div>
<?php echo form_close();?>

I have got it to work with out using codeigniter upload image helper easier this way.
controller function
function edit($user_id = 0) {
$this->load->model('users/model_user');
$data['title'] = "Users";
$data['base'] = config_item('HTTP_SERVER');
$data['isLogged'] = $this->user->isLogged();
$data['last_updated'] = $this->model_user->last_updated($user_id);
$data['user_id'] = $user_id;
if (!empty($this->input->post('username'))) {
$data['username'] = $this->input->post('username');
} else {
$data['username'] = $this->model_user->getUserByUsername($user_id);
}
if (!empty($this->input->post('firstname'))) {
$data['firstname'] = $this->input->post('firstname');
} else {
$data['firstname'] = $this->model_user->getUserByFirstname($user_id);
}
if (!empty($this->input->post('lastname'))) {
$data['lastname'] = $this->input->post('lastname');
} else {
$data['lastname'] = $this->model_user->getUserByLastname($user_id);
}
if (!empty($this->input->post('email'))) {
$data['email'] = $this->input->post('email');
} else {
$data['email'] = $this->model_user->getUserByEmail($user_id);
}
if(!empty($this->input->post('image'))) {
$data['image'] = $this->input->post('image');
} else {
$data['image'] = $this->model_user->getUserImage($user_id);
}
$data['image_path'] = config_item('HTTP_CATALOG') . '/image/catalog/';
$this->load->library('password');
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Your Username');
$this->form_validation->set_rules('firstname', 'Your First Name');
$this->form_validation->set_rules('lastname', 'Your Last Name');
$this->form_validation->set_rules('email', 'Your Email');
if ($this->form_validation->run() == TRUE) {
$this->model_user->editUser($user_id, $data);
redirect('users');
} else {
$data['header'] = $this->load->view('template/common/header', $data, TRUE);
$data['footer'] = $this->load->view('template/common/footer', NULL, TRUE);
return $this->load->view('template/users/users_form', $data);
}
}
View
<?php echo validation_errors('<div class="alert alert-danger">', '</div>'); ?>
<?php
$data = array(
'role' => "form",
'class' => 'form-horizontal'
);
echo form_open('users/edit/' . $user_id, $data);
?>
<div class="form-group">
<label for="input-username" class="col-sm-2 control-label">Username</label>
<div class="col-sm-10">
<input type="text" name="username" value="<?php echo $username;?>" class="form-control">
</div>
</div>
<div class="form-group">
<label for="input-firstname" class="col-sm-2 control-label">Firstname</label>
<div class="col-sm-10">
<input type="text" name="firstname" value="<?php echo $firstname;?>" class="form-control">
</div>
</div>
<div class="form-group">
<label for="input-lastname" class="col-sm-2 control-label">Lastname</label>
<div class="col-sm-10">
<input type="text" name="lastname" value="<?php echo $lastname;?>" class="form-control">
</div>
</div>
<div class="form-group">
<label for="input-email" class="col-sm-2 control-label">Email</label>
<div class="col-sm-10">
<input type="text" name="email" value="<?php echo $email;?>" class="form-control">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label" for="input-image"></label>
<div class="col-lg-3">
<div class="thumbnail">
<img src="<?php echo $image_path . $image; ?>" style=" width: 100%; height: 300px;">
</div>
</div>
</div>
<div class="form-group">
<label for="input-image" class="col-sm-2 control-label">Image</label>
<div class="col-sm-10">
<br>
<input type="file" name="image" value="<?php echo $image;?>" size="20">
</div>
</div>
<div class="form-group">
<div class="text-right">
<h2><a href="<?php echo base_url('users/edit_password/' . $user_id);?>">Change Your Password</h2>
<button type="submit" name="submit" class="btn btn-primary">Submit</button>
</div>
</div>
<?php echo form_close();?>

Related

How to update the image name in SQL table and store it in the directory?

I wanted to update the image "name" to SQL and store the new image file in the directory, But I'm not able to find a good way to do it and my existing code is not working as well for the file upload.
.PHP file
<?PHP
$base_url = "https://example.com/"; // Current page path URL: https://example.com/settings#/edit-profile
$uniqueid = $_SESSION['uniqueid']; // Current user unique id.
// For Extension
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
?>
<?php
if(!empty($uniqueid))
{
$edituserid = $uniqueid;
$query_result=mysqli_query($con,"SELECT * FROM tbl_admin WHERE uniqueid='$edituserid'");
$numrows=mysqli_num_rows($query_result);
if(!$numrows)
{
$_SESSION['error'] = "Somthing went wrong!";
header('Location:'.$base_url.'settings#/edit-profile');
}
else
{
$Query = mysqli_query($con,"SELECT * FROM tbl_admin WHERE uniqueid='$edituserid'");
$editRow = mysqli_fetch_array($Query);
$edituserid = $editRow['uniqueid'];
$previousimage = $editRow['profile_image'];
}
}
?>
<?php
if(isset($_POST['update_user_info']))
{
$first_name = mysqli_real_escape_string($con,$_POST['first_name']);
$last_name = mysqli_real_escape_string($con,$_POST['last_name']);
$uniqueid1 = mysqli_real_escape_string($con,$_POST['uniqueid']);
// Image preparation
$profile_image = $_FILES['profile_image']['name'];
if($profile_image)
{
$profile_image_original = ($_FILES['profile_image']['name']);
$profile_image = ($uniqueid);
$profile_image_extension = getExtension($profile_image_original);
$extension = strtolower($profile_image_extension);
$dot = ".";
$profile_image_type = $_FILES['profile_image']['type'];
$profile_image_size = $_FILES['profile_image']['size'];
$image_file_name = "assets/user_images/".$profile_image.=$dot.=$extension;
move_uploaded_file($_FILES['profile_image']['tmp_name'], $image_file_name);
}
else
{
$profile_image = $previousimage;
}
if(!empty($_FILES['profile_image']['name']))
{
$sql2 = "UPDATE `tbl_admin` SET `first_name`='$first_name', `last_name`='$last_name', `uniqueid`='$uniqueid1', `profile_image`='$profile_image' WHERE uniqueid='$edituserid'";
}
else
{
$sql2 = "UPDATE `tbl_admin` SET `first_name`='$first_name', `last_name`='$last_name', `uniqueid`='$uniqueid1' WHERE uniqueid='$edituserid'";
}
//var_dump($sql); exit();
$result2 = mysqli_query($con, $sql2);
if($result2)
{
$_SESSION['success'] = "Update successful!";
header('Location:'.$base_url.'settings#/edit-profile');
} else {
$error="Something went wrong !";
}
$first_name = '';
$last_name = '';
$uniqueid1 = '';
}
?>
HTML form
<form method="POST" enctype="multipart/form-data">
<div class="row">
<div class="col-md-4 col-sm-12">
<div class="container">
<div class="avatar-upload">
<div class="avatar-edit">
<input type="file" id="imageUpload" name="profile_image" accept="image/*" />
<label for="imageUpload"></label>
</div>
<div class="avatar-preview">
</div>
</div>
</div>
</div>
<div class="form-group row">
<label for="staticEmail" class="col-sm-4 col-form-label">Email</label>
<div class="col-sm-8">
<input type="text" readonly class="form-control" id="staticEmail" value="<?php if(!empty($editRow)){ echo $editRow['email']; } ?>">
</div>
</div>
<div class="form-group row">
<label for="inputFirstName" class="col-sm-4 col-form-label">First Name</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="inputFirstName" name="first_name" value="<?php if(!empty($editRow)){ echo $editRow['first_name']; } ?>">
</div>
</div>
<div class="form-group row">
<label for="inputLastName" class="col-sm-4 col-form-label">Last Name</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="inputLastName" name="last_name" value="<?php if(!empty($editRow)){ echo $editRow['last_name']; } ?>">
</div>
</div>
<div class="form-group row">
<label for="inputSxID" class="col-sm-4 col-form-label">ID</label>
<div class="col-sm-8">
<input type="text" readonly class="form-control" id="inputSxID" name="uniqueid" value="<?php if(!empty($editRow)){ echo $editRow['uniqueid']; } ?>">
</div>
</div>
<button type="submit" class="btn btn-primary" name="update_user_info">Update</button>
</div>
</div>
</form>
It handles This table
id
first_name
last_name
email
profile_image
1
Joe
Dilon
abc#mail.com
abc.jpg
To // after success post update
id
first_name
last_name
email
profile_image
1
Changed
Changed
abc#mail.com
abc.jpg //No Response
And also there is no image file transfer into the targeted directory path. I'm not able to figure what's wrong or best way to do it correctly.

Codeigniter form_open_multipart didn't respond

Been trying out codeigniter and wanted to create a form with file upload using the upload class. However when i try to save the form, it didn't respond and just show the same page. I've been looking around, but I can't seem to find out how to make this work.
This is the controller Product.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
Class Product extends CI_Controller{
function __construct(){
parent::__construct();
check_not_login();
$this->load->model('product_m');
}
public function index(){
$data['row'] = $this->product_m->get();
$this->template->load('template', 'product/data/product_data', $data);
}
public function add(){
$product = new stdClass();
$product->product_id = null;
$product->product_name = null;
$product->customer_name = null;
$product->supplier_name = null;
$product->weight = null;
$product->product_date = null;
$product->expired_date = null;
$product->image = null;
$product->barcode = null;
$data = array(
'page' => 'add',
'row' => $product
);
$this->template->load('template', 'product/data/product_form', $data);
}
public function edit($id){
$query = $this->product_m->get($id);
if($query->num_rows()>0){
$product = $query->row();
$data = array(
'page' => 'edit',
'row' => $product
);
$this->template->load('template', 'product/data/product_form', $data);
}else{
echo "<script>alert('Data not found');";
echo "window.location='".site_url('product')."';</script>";
}
}
public function process(){
$post = $this->input->post(null, TRUE);
if(isset($_POST['add'])){
$config['upload_path'] = './uploads/product';
$config['allowed_types'] = 'jpeg|pdf|jpg|png|doc|docs|xls|xlsx';
$config['max_size'] = 5120;
$config['file_name'] = 'product-'.date('ymd').'-'.substr(md5(rand()),0,10);
$this->load->library('upload', $config);
if(#$_FILES['image']['name'] !=null){
if($this->upload->do_upload('image')){
$post['image'] = $this->upload->data('file_name');
$this->product_m->add($post);
if($this->db->affected_rows() > 0){
$this->session->set_flashdata('success', 'Data saved successfully');
}
redirect('product');
}else{
$error = $this->upload->display_errors();
$this->session->set_flashdata('error', $error);
redirect('product/add');
}
}
else{
$post['image'] = null;
$this->product_m->add($post);
if($this->db->affected_rows() > 0){
$this->session->set_flashdata('success', 'Data saved successfully');
}
redirect('product');
}
}else if(isset($_POST['edit'])){
$this->product_m->edit($post);
}
}
public function del($id){
$this->product_m->del($id);
if($this->db->affected_rows() > 0){
$this->session->set_flashdata('Success', 'Data successfully deleted');
}
redirect('product');
}
}
Script for the form product_form.php
<section class="content-header">
<h1>
Product
<small>Add product</small>
</h1>
</section>
<section class ="content">
<div class="box">
<div class="box-header">
<h3 class="box-title"> product</h3>
<div class="pull-right">
<a href="<?=site_url('product')?>" class="btn btn-warning btn-flat">
<i class="fa fa-undo"></i> Back
</a>
</div>
</div>
<div class="box-body">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<?php echo form_open_multipart('product/process');?>
<div class="form-group">
<label>Product Name *</label>
<input type="hidden" name="id" value="<?=$row->product_id?>">
<input type="text" name="product_name" value="<?=$row->product_name?>" class="form-control" required>
</div>
<div class="form-group">
<label>Customer Name *</label>
<input type="text" name="customer_name" value="<?=$row->customer_name?>" class="form-control" required>
</div>
<div class="form-group">
<label>Supplier Name *</label>
<input type="text" name="supplier_name" value="<?=$row->supplier_name?>" class="form-control" required>
</div>
<div class="form-group">
<label>Weight(kg) *</label>
<input type="number" name="weight" value="<?=$row->weight?>" class="form-control" required>
</div>
<div class="form-group">
<label>Product Date(dd/mm/yyyy) *</label>
<input type="text" name="product_date" value="<?=$row->product_date?>" class="form-control" required>
</div>
<div class="form-group">
<label>Expired Date(dd/mm/yyyy) *</label>
<input type="text" name="expired_date" value="<?=$row->expired_date?>" class="form-control" required>
</div>
<div class="form-group">
<label>Technical Data</label>
<input type="file" name="image" class="form-control" >
</div>
<!-- FORM BARCODE -->
<div class="form-group">
<label>Barcode</label>
<input name="barcode" class="form-control" value="
<?php
$angka = rand(1000000,9999999);
$random = rand(0,25);
$random1 = rand(0,25);
$random2 = rand(0,25);
$name = array("A", "B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q",
"R","S","T","U","V","W","X","Y","Z");
echo $name[$random],$name[$random1],$name[$random2],$angka;
$row->barcode
?>" readonly>
</div>
<div class="form-group">
<button type="submit" name="<?=$page?>" class="btn btn-success btn-flat">
<i class="fa fa-paper-plane"> Save</i>
</button>
<button type="Reset" class="btn btn-flat"> Reset</button>
</div>
<!-- </form> -->
<?php echo form_close();?>
</div>
</div>
</div>
</div>
</section>
Load the form helper.
function __construct(){
parent::__construct();
check_not_login();
$this->load->model('product_m');
$this->load->helper('form');
}

Image uploading in codeigniter in database

I have a problem with uploading images in the database in codeigniter. When I upload image in the database, it shows this type of error like:
The upload path does not appear to be valid. So what's the problem in this code. I cannot figure out, so please help me.
I tried base_url() method also but error is not solved...!
My Htmlcode:-
<?php echo form_open_multipart('student/insertstudent') ?>
<form>
<div class="panel panel-primary" >
<div class="panel-heading" >
<p class="label" style="font-size: 15px">Student Registration Form</p>
</div>
<div class="panel-body">
<fieldset>
<div class="form-group">
<label for="exampleInputEmail1">First Name</label>
<input type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter First Name" name="fname" value="<?php echo set_value('fname'); ?>">
<div class="row-lg-6">
<?php echo form_error('fname'); ?>
</div>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Last Name</label>
<input type="text" class="form-control" id="exampleInputPassword1" placeholder="Enter Last Name" name="lname" value="<?php echo set_value('lname'); ?>">
<div class="row-lg-6">
<?php echo form_error('lname'); ?>
</div>
</div>
<div class="form-group">
<label for="exampleTextarea">Address</label>
<textarea class="form-control" id="exampleTextarea" rows="2" placeholder="Enter Address" name="add"><?php echo set_value('add'); ?></textarea>
<div class="row-lg-6">
<?php echo form_error('add'); ?>
</div>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Contact Number</label>
<input type="text" class="form-control" id="exampleInputPassword1" placeholder="Enter Contact Number" name="cno" value="<?php echo set_value('cno'); ?>">
<div class="row-lg-6">
<?php echo form_error('cno'); ?>
</div>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Emaid ID</label>
<input type="text" class="form-control" id="exampleInputPassword1" placeholder="Enter your email" name="email" value="<?php echo set_value('email'); ?>">
<div class="row-lg-6">
<?php echo form_error('email'); ?>
</div>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Enter Course</label>
<input type="text" class="form-control" id="exampleInputPassword1" placeholder="Enter Course Name" name="cname" value="<?php echo set_value('cname'); ?>">
<div class="row-lg-6">
<?php echo form_error('cname'); ?>
</div>
</div>
<!-- <div class="form-group">
<label for="exampleInputPassword1">Select Student Photo</label>
<input type="file" class="form-control" id="exampleInputPassword1" placeholder="Enter Course Name" name="photo">
<div class="row-lg-6">
<?php echo form_error('photo'); ?>
</div>
</div> -->
<div class="form-group">
<label for="exampleInputPassword1">Select Image</label>
<?php echo form_upload(['name' => 'userfile','class'=>'form-control']); ?>
<div class="row-lg-6">
<?php if(isset($upload_error))
{
echo $upload_error;
} ?>
</div>
</div>
<h4 align="center" style="margin-left: -150px"><button type="submit" class="btn btn-primary">Register</button></h4>
<h4 align="center" style="margin-top: -43px;margin-left: 200px"><button type="reset" class="btn btn-primary">Reset</button></h4>
</fieldset>
</div>
</div>
my controller file:-
public function insertstudent()
{
$this->form_validation->set_rules('fname', 'FirstName', 'required|alpha');
$this->form_validation->set_rules('lname', 'lastName', 'required|alpha');
$this->form_validation->set_rules('add', 'Address', 'required');
$this->form_validation->set_rules('cno', 'Contact Number', 'required|numeric');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
$this->form_validation->set_rules('cname', 'Course Name', 'required');
// $this->form_validation->set_rules('userfile', 'Student Photo', 'required');
$this->form_validation->set_error_delimiters("<p class='text-danger'>", "</p>");
$config['upload_path'] = base_url('asset/uploads/');
$config['allowed_types'] = 'gif|jpg|png';
$this->upload->initialize($config);
$this->load->library('upload',$config);
if ($this->form_validation->run() == TRUE && $this->upload->do_upload('userfile')) {
$post = $this->input->post();
$data = $this->upload->data();
$image_path = base_url("upload/".$data['raw_name'].$data['file_ext']);
$post['image_path'] = $image_path;
$this->load->model('useradd');
if($this->useradd->addstudent($post)){
$this->session->set_flashdata('success', 'Record Successfully Inserted');
return redirect('admin');
}else {
$this->load->view('addstudent');
}
// $data = array(
// 'firstname' => $this->input->post('fname'),
// 'lastname' => $this->input->post('lname'),
// 'address' => $this->input->post('add'),
// 'phone' => $this->input->post('cno'),
// 'email' => $this->input->post('email'),
// 'course' => $this->input->post('cname'),
// 'photo' => $image_path,
// );
// // $this->load->library('upload', $data);
// if ($result == true) {
// $this->session->set_flashdata('success', 'Record Successfully Inserted');
// return redirect('admin');
// } else {
// $this->load->view('addstudent');
// }
} else {
$upload_error = $this->upload->display_errors();
$this->load->view('addstudent',compact('upload_error'));
}
}
my Model:-
class useradd extends CI_Model
{
function addstudent($data)
{
$result = $this->db->insert('add_student', $data);
}
}
My error is:
The upload path does not appear to be valid.
Try This Code To Upload Image.and remove form tag in your view file and you didn't define form_close method at the end of the form of your view file
$file = $_FILES['filename']['name'];
$config['upload_path'] = './images/';
$config['allowed_types'] = 'gif|jpg|png';
$this->load->library('upload', $config);
$this->upload->do_upload();
$allData = $this->upload->data();

Error updating unique data in CodeIgniter

I'm using CodeIgniter. I can't update data, because I make the database field is unique.
My controller:
function simpanadditional(){
$this->form_validation->set_rules('nama','Nama Additional','trim|required');
$this->form_validation->set_rules('harga','Harga Additional','required');
if($this->form_validation->run() == FALSE){
redirect('tambah-additional','refresh');
}else{
$cek = $this->my_model->ceknamadditional($this->input->post('nama'));
if(count($cek) > 0){
$this->session->set_flashdata('message','nama tidak boleh sama');
redirect('tambah-additional','refresh');
}else{
$this->my_model->simpanadditional();
redirect('admin/tabel_additional','refresh');
}
}
}
function editadditional($id){
if($this->session->userdata('logged_in'))
{
$session_data = $this->session->userdata('logged_in');
$data['username'] = $session_data['username'];
$data['title'] = 'Edit Additional';
$data['main'] = 'admin/additional/form_edit_additional';
$data ['getdata'] = $this->my_model->editadditional($id);
$data['getgroup'] = $this->my_model->editgroup($session_data['username']);
$this->load->view('admin/index',$data);
} else {
redirect('admin/login', 'refresh');
}
}
My model:
function simpanadditional(){
$data = array(
'nama_additional' => $this->input->post('nama'),
'harga_additional' => $this->input->post('harga'),
);
if($this->input->post('id')){
// ini untuk update nya
$this->db->where('id_additional',$id);
$this->db->update('additional',$data);
}else{
// ini untuk insert nya
$this->db->insert('additional',$data);
}
}
function editadditional($id){
$data = array();
$this->db->select('*');
$this->db->from('additional');
$this->db->where('id_additional',$id);
$hasil = $this->db->get();
if($hasil->num_rows() > 0){
$data = $hasil->result();
}
$hasil->free_result();
return $data;
}
This is views of form additional:
<div class="item form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="name">Nama <span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input id="name" class="form-control col-md-7 col-xs-12" data-validate-length-range="6" data-validate-words="2" name="nama" value="<?php echo $data->nama_additional ?>" type="text">
<input type="hidden" name="id" value="<?php echo $data->id_additional ?>">
</div>
</div>
<div class="item form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="name">Harga <span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input id="icon" class="form-control col-md-7 col-xs-12" data-validate-length-range="6" data-validate-words="2"
name="harga" value="<?php echo $data->harga_additional ?>" type="text" onkeypress="return isNumberKey(event)">
</div>
</div>
Can anyone help?

Unable to access an error message - Callback validation in CodeIgniter

I have simple code thats not working. I made validation for checkbox and I get error:
Unable to access an error message corresponding to your field name accept_terms_checkbox.(accept_terms)
This is my code:
Controller:
public function formularz2()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$data['szkolenia'] = $this->Szkolenie_m->pobierz();
//VALIDATION!!
$this->form_validation->set_rules('imie', 'Imię', 'required');
$this->form_validation->set_message('required', 'Błąd: wypełnij powyższe pole');
$this->form_validation->set_rules('accept_terms_checkbox', 'checkbox', 'callback_accept_terms');
//CALLBACK FUNCTION!!
function accept_terms()
{
if ($this->input->post('accept_terms_checkbox'))
{
return TRUE;
}
else
{
$error = 'Please read and accept our terms and conditions.';
$this->form_validation->set_message('accept_terms', $error);
return FALSE;
}
}
//Po przesłaniu danych
if (!empty($_POST))
{
$konsultant = $this->uri->segment(3);
$dane = array(
'email1' => $this->input->post('email'),
'imie' => $this->input->post('imie'),
'nazwisko' => $this->input->post('nazwisko'),
'nazwa_firmy' => $this->input->post('firma'),
'konsultant_id' => $konsultant,
);
//Trzeba jeszcze tutaj ogarnąć wrzucanie pivotów zaznaczonych checkboxów
$boxes = $_POST['formChecks'];
$N = count($boxes);
$ostatni_id = $this->Osoby_m->ostatni_id();
for($i=0; $i < $N; $i++)
{
$this->Osoby_m->nowy_wpis_formularz($boxes[$i]);
}
//Pobrać id dodanej osoby = policzyć ile osób w bazie +1
$this->Osoby_m->nowa_osoba($dane);
}
if ($this->form_validation->run() == FALSE)
{
$this->load->view('formularz', $data);
}
else
{
$this->load->view('wyslano_formularz');
}
}
My View:
<?php echo form_open(); ?>
<div class="form-group">
<label for="email" class="col-sm-2 control-label">Email:</label>
<div class="col-sm-10">
<input type="email" class="form-control" id="email" name="email" placeholder="Email" value="<?php echo set_value('email'); ?>">
<p class="help-block"><?php echo form_error('email'); ?></p>
</div>
</div>
<div class="form-group">
<label for="imie" class="col-sm-2 control-label">Imię:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="imie" name="imie" placeholder="Imię" value="<?php echo set_value('imie'); ?>">
<p class="help-block"><?php echo form_error('imie'); ?></p>
</div>
</div>
<div class="form-group">
<label for="nazwisko" class="col-sm-2 control-label">Nazwisko: </label>
<div class="col-sm-10">
<input type="text" class="form-control" id="nazwisko" name="nazwisko" placeholder="Nazwisko" value="<?php echo set_value('nazwisko'); ?>">
<p class="help-block"><?php echo form_error('nazwisko'); ?></p>
</div>
</div>
<div class="form-group">
<label for="firma" class="col-sm-2 control-label">Firma:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="firma" name="firma" placeholder="Firma" value="<?php echo set_value('firma'); ?>">
<p class="help-block"><?php echo form_error('firma'); ?></p>
</div>
</div>
<div class="col-sm-12" style="margin-bottom: 30px; margin-top: 30px;"> <h3>Wybierz interesujące Cię szkolenia</h3></div>
<div class="form-group">
<label class="col-sm-2 control-label">Szkolenia:</label>
<div class="col-sm-10">
<?php foreach ($szkolenia as $szkolenie): ?>
<div class="checkbox">
<label><input id="szkolenie<?php echo $szkolenie->id; ?>" type="checkbox" name="formChecks[]" value="<?php echo $szkolenie->id; ?>"> <?php echo $szkolenie->nazwa_szkolenia; ?></label>
<br>
</div>
<?php endforeach; ?>
</div>
</div>
//CALLBACK CHECKBOX
<div class="form-group">
<div class="col-sm-12" style="margin-top: 50px;">
<input type="checkbox" name="accept_terms_checkbox" value="1"/> Zgadzam się na otrzymywanie maili od firmy Gamma<br>
<p><?php echo form_error('accept_terms_checkbox') ?></p>
</div>
</div>
<button type="submit" class="btn btn-lg btn-success" style="margin-top: 50px;">Odbierz Voucher</button>
<?php echo form_close(); ?>
In order to use your own callback method with codeigniter's validation class, you must declare the method. IN your case ( add this to your controller or a helper etc...):
public function accept_terms($user_input){
if($user_input != ""){
return True;
}else{
$this->form_validation->set_message('accept_terms_checkbo', 'The %s field can not be empty"');
return False;
}
I fixed this error by simple validation without callback function. I figure out that I don't need callback function for Terms of Services checkbox.
$this->form_validation->set_rules('accept_terms_checkbox', 'Checkbox', 'required');
$this->form_validation->set_message('required', 'You need to accept Terms of Services');

Categories