I want to validate a form to make sure a user entered something in the description field in this situation form validation is correct.
But,
Here , I pass value to function 2 by fetching values from function 1
When function 2 loads first time it fetch data and display the values (OK)
But When function 2 resubmit for validation and submision data these valitable get empoty and it throw the error Message: Undefined variable: query (ERROR)
I don't know how to do this, hehe. I'm just a newbie PHP programmer.
Here's what I have so far:
function 1
public function ask()
{
$this->load->model('MainM');
$this->load->library('form_validation');
$this->form_validation->set_rules('index', 'AL Index', 'trim|required|min_length[7]|max_length[7]');
if($this->form_validation->run() == FALSE) {
$this->load->view('enterindex');
}else{
$query = null; //emptying in case
$index = $this->input->post("index"); //getting from post value
$query = $this->db->get_where('tbl_reg', array('reg_index' => $index));
$count = $query->num_rows(); //counting result from query
if ($count == 1) {
$data['query'] = $this->MainM->getregdata($index);
$result = $this->load->view('submitques',$data);
}else{
$data = array();
$data['error'] = 'error';
$this->load->view('enterindex', $data);
}
}
function 2
public function submitq()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('yourq', 'Question', 'required|min_length[7]');
if($this->form_validation->run() == FALSE) {
$this->load->view('submitques',$data);
} else {
//insert the submitq form data into database
$data = array(
'reg_id' => $this->input->post('reg_id'),
'ques' => $this->input->post('yourq'),
'call' => "yes",
'status' => "New",
'date' => date('Y-m-d H:i:s')
);
if ($this->db->insert('tbl_ques', $data))
{
// success
$this->session->set_flashdata('success_msg', 'Your Submission is success');
redirect('main/submitq');
}
else
{
$this->load->view('submitques', $data);
}
}
}
Actully you have $data variable put in else part so thats why this error appeared you need to define before loop.
public function submitq()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('yourq', 'Question', 'required|min_length[7]');
// define here before check condtions
$data = array(
'reg_id' => $this->input->post('reg_id'),
'ques' => $this->input->post('yourq'),
'call' => "yes",
'status' => "New",
'date' => date('Y-m-d H:i:s')
);
if($this->form_validation->run() == FALSE) {
$this->load->view('submitques',$data);
} else {
//insert the submitq form data into database
if ($this->db->insert('tbl_ques', $data))
{
// success
$this->session->set_flashdata('success_msg', 'Your Submission is success');
redirect('main/submitq');
}
else
{
$this->load->view('submitques', $data);
}
}
}
If you wish to use the posted $data variable on false condition, you could moving it up outside the validation block :
public function submitq()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('yourq', 'Question', 'required|min_length[7]');
$data = array(
'reg_id' => $this->input->post('reg_id'),
'ques' => $this->input->post('yourq'),
'call' => "yes",
'status' => "New",
'date' => date('Y-m-d H:i:s')
);
if($this->form_validation->run() == FALSE) {
$this->load->view('submitques',$data);
} else {
//insert the submitq form data into database
if ($this->db->insert('tbl_ques', $data))
{
// success
$this->session->set_flashdata('success_msg', 'Your Submission is success');
redirect('main/submitq');
}
else
{
$this->load->view('submitques', $data);
}
}
}
Try with This Code:
First Add Form Library to config/autoload.php
$autoload['libraries'] = array('database','form_validation');
html Code
This is view file login.php
<?php echo form_open('action_controller_name', array('class' => '', 'enctype' => 'multipart/form-data', 'role' => 'form', 'name' => 'myform', 'id' => 'myform')); ?>
<div class="form-group">
<label class="control-label" for="mobile">Mobile-No</label>
<input type="text" name="mobile" value="" placeholder="Enter Mobile No" id="mobile" class="form-control" />
<label class="error"><?php echo form_error('mobile'); ?></label>
</div>
<div class="form-group">
<label class="control-label" for="password">Password</label>
<input type="password" name="password" value="" placeholder="Password" id="password" class="form-control" />
<label class="error"><?php echo form_error('mobile'); ?></label>
</div>
<input type="submit" value="Login" class="btn btn-gray" id="submit" />
<a class="forgotten" href="<?php echo base_url('login/forgot_password'); ?>" style="font-size: 13px;">Forgot Password</a>
<?php
echo form_close();
?>
My Action Controller
public function action_controller_name() {
$this->load->helper(array('form')); // Load Form Library
$this->load->library('form_validation'); // Load Form Validaton Library
$this->form_validation->set_rules('mobile', 'mobile', 'required', array('required' => 'Please Enter Mobile Number.'));
$this->form_validation->set_rules('password', 'Password', 'required', array('required' => 'Please Enter passsword.'));
if ($this->form_validation->run() === TRUE) { // Check validation Run
// Your Login code write here
} else {
$this->load->view('login', $this->data);
}
}
Try this code.You can keep variable value if validation fails in codeigniter successfully.
Related
I want to add variables to an array, what I'm trying to do is to check if there is an error from the view within the controller and the variable will be added to an array here is an example.
$error = array ();
if (input1 == null)
{
$errormessage1 = '*';
$error[] = $errormessage1;
}
if (input2 == null)
{
$errormessage2 = '*';
$error[] = $errormessage2;
}
if (input1 != null AND input2 != null)
{
//insert to database or something
}
else
$this->load->view("view", $error);
The problem is that the values are not being inserted to the array. And the array is not printing anything after I return it to the view.php
Here is an example of my view.php
echo form_label('User Name:', 'input1 ' );
$data= array(
'name' => 'input1 ',
'placeholder' => 'Please Enter User Name',
'class' => 'input_box'
);
echo form_input($data);
if(isset($errormessage1 ))
echo $errormessage1 ;
Thank you for any help that you can give me.
I see you are trying to tell the user that username is required. right? then why don't you utilize Codeigniter form_validation library? to display the errors you use form helper method validation_errors()
Your View
<?php echo validation_errors();
echo form_label('User Name:', 'input1 ' );
$data= array(
'name' => 'input1 ',
'placeholder' => 'Please Enter User Name',
'class' => 'input_box'
);
echo form_input($data);
Your Controller
public function your_method(){
$this->load->library('form_validation');
$this->form_validation->set_rules('input1','Username','required');
//and so on for other user inputs
if($this->form_validation->run()===TRUE){
//send to model may be
}else{
$this->load->view('view');
}
}
i have a problem in a controller file called "pages.php". After login via login page with correct credentials pages.php does not open dashboard. I doubt that probably the source of this problem may be found in this pages.php
<?php
class Pages extends MY_Controller
{
public function view($page = 'login')
{
if (!file_exists(APPPATH.'views/'.$page.'.php'))
{
// Whoops, we don't have a page for that!
show_404();
}
$data['title'] = ucfirst($page); // Capitalize the first letter
if($page == 'section' || $page == 'subject' || $page == 'student' || $page == 'marksheet' || $page == 'accounting') {
$this->load->model('model_classes');
$data['classData'] = $this->model_classes->fetchClassData();
$this->load->model('model_teacher');
$data['teacherData'] = $this->model_teacher->fetchTeacherData();
$this->load->model('model_accounting');
$data['totalIncome'] = $this->model_accounting->totalIncome();
$data['totalExpenses'] = $this->model_accounting->totalExpenses();
$data['totalBudget'] = $this->model_accounting->totalBudget();
}
if($page == 'setting') {
$this->load->model('model_users');
$this->load->library('session');
$userId = $this->session->userdata('id');
$data['userData'] = $this->model_users->fetchUserData($userId);
}
if($page == 'dashboard') {
$this->load->model('model_student');
$this->load->model('model_teacher');
$this->load->model('model_classes');
$this->load->model('model_marksheet');
$this->load->model('model_accounting');
$data['countTotalStudent'] = $this->model_student->countTotalStudent();
$data['countTotalTeacher'] = $this->model_teacher->countTotalTeacher();
$data['countTotalClasses'] = $this->model_classes->countTotalClass();
$data['countTotalMarksheet'] = $this->model_marksheet->countTotalMarksheet();
$data['totalIncome'] = $this->model_accounting->totalIncome();
$data['totalExpenses'] = $this->model_accounting->totalExpenses();
$data['totalBudget'] = $this->model_accounting->totalBudget();
}
if($page == 'login') {
$this->isLoggedIn();
$this->load->view($page, $data);
}
else{
$this->isNotLoggedIn();
$this->load->view('templates/header', $data);
$this->load->view($page, $data);
$this->load->view('templates/footer', $data);
}
}
}
Please anyone who can edit this code just help. Or if you think the problem is not in pages.php (above page) please advice me how the problem can be solved. I have mentioned more pages:-
This is rootes.php.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
$route['(:any)'] = 'pages/view/$1';
$route['default_controller'] = 'pages/view';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
This is MY_Controller.php in core folder
<?php
class MY_Controller extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
public function isLoggedIn()
{
$this->load->library('session');
if($this->session->userdata('logged_in') === true) {
redirect('../dashboard');
}
}
public function isNotLoggedIn()
{
$this->load->library('session');
if($this->session->userdata('logged_in') != true) {
redirect('../../');
}
}
}
This is Users.php in controllers folder
<?php
class Users extends MY_Controller
{
public function __construct()
{
parent::__construct();
// loading the users model
$this->load->model('model_users');
// loading the form validation library
$this->load->library('form_validation');
}
public function login()
{
$validator = array('success' => false, 'messages' => array());
$validate_data = array(
array(
'field' => 'username',
'label' => 'Username',
'rules' => 'required|callback_validate_username'
),
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'required'
)
);
$this->form_validation->set_rules($validate_data);
$this->form_validation->set_error_delimiters('<p class="text-danger">','</p>');
if($this->form_validation->run() === true) {
$username = $this->input->post('username');
$password = md5($this->input->post('password'));
$login = $this->model_users->login($username, $password);
if($login) {
$this->load->library('session');
$user_data = array(
'id' => $login,
'logged_in' => true
);
$this->session->set_userdata($user_data);
$validator['success'] = true;
$validator['messages'] = "index.php/dashboard";
}
else {
$validator['success'] = false;
$validator['messages'] = "Incorrect username/password combination";
} // /else
}
else {
$validator['success'] = false;
foreach ($_POST as $key => $value) {
$validator['messages'][$key] = form_error($key);
}
} // /else
echo json_encode($validator);
} // /lgoin function
public function validate_username()
{
$validate = $this->model_users->validate_username($this->input->post('username'));
if($validate === true) {
return true;
}
else {
$this->form_validation->set_message('validate_username', 'The {field} does not exists');
return false;
} // /else
} // /validate username function
public function logout()
{
$this->load->library('session');
$this->session->sess_destroy();
redirect('../../');
}
public function updateProfile()
{
$this->load->library('session');
$userId = $this->session->userdata('id');
$validator = array('success' => false, 'messages' => array());
$validate_data = array(
array(
'field' => 'username',
'label' => 'Username',
'rules' => 'required'
),
array(
'field' => 'fname',
'label' => 'First Name',
'rules' => 'required'
)
);
$this->form_validation->set_rules($validate_data);
$this->form_validation->set_error_delimiters('<p class="text-danger">','</p>');
if($this->form_validation->run() === true) {
$update = $this->model_users->updateProfile($userId);
if($update === true) {
$validator['success'] = true;
$validator['messages'] = "Successfully Update";
}
else {
$validator['success'] = false;
$validator['messages'] = "Error while inserting the information into the database";
}
}
else {
$validator['success'] = false;
foreach ($_POST as $key => $value) {
$validator['messages'][$key] = form_error($key);
}
} // /else
echo json_encode($validator);
}
public function changePassword()
{
$this->load->library('session');
$userId = $this->session->userdata('id');
$validator = array('success' => false, 'messages' => array());
$validate_data = array(
array(
'field' => 'currentPassword',
'label' => 'Current Password',
'rules' => 'required|callback_validate_current_password'
),
array(
'field' => 'newPassword',
'label' => 'Password',
'rules' => 'required|matches[confirmPassword]'
),
array(
'field' => 'confirmPassword',
'label' => 'Confirm Password',
'rules' => 'required'
)
);
$this->form_validation->set_rules($validate_data);
$this->form_validation->set_error_delimiters('<p class="text-danger">','</p>');
if($this->form_validation->run() === true) {
$update = $this->model_users->changePassword($userId);
if($update === true) {
$validator['success'] = true;
$validator['messages'] = "Successfully Update";
}
else {
$validator['success'] = false;
$validator['messages'] = "Error while inserting the information into the database";
}
}
else {
$validator['success'] = false;
foreach ($_POST as $key => $value) {
$validator['messages'][$key] = form_error($key);
}
} // /else
echo json_encode($validator);
}
public function validate_current_password()
{
$this->load->library('session');
$userId = $this->session->userdata('id');
$validate = $this->model_users->validate_current_password($this->input->post('currentPassword'), $userId);
if($validate === true) {
return true;
}
else {
$this->form_validation->set_message('validate_current_password', 'The {field} is incorrect');
return false;
} // /else
}
}
This is login.php in views folder
<!DOCTYPE html>
<html>
<head>
<title><?php echo $title; ?></title>
<!-- bootstrap css -->
<link rel="stylesheet" type="text/css"
href="assets/bootstrap/css/bootstrap.min.css">
<!-- boostrap theme -->
<link rel="stylesheet" type="text/css" href="assets/bootstrap/css/bootstrap-theme.min.css">
<!-- custom css -->
<link rel="stylesheet" type="text/css" href="custom/css/custom.css">
<!-- jquery -->
<script type="text/javascript" src="assets/jquery/jquery.min.js"></script>
<!-- boostrap js -->
<script type="text/javascript" src="assets/bootstrap/js/bootstrap.min.js">
</script>
</head>
<body>
<div class="col-md-6 col-md-offset-3 vertical-off-4">
<div class="panel panel-default login-form">
<div class="panel-body">
<form method="post" action="index.php/users/login" id="loginForm">
<fieldset>
<legend>
Login
</legend>
<div id="message"></div>
<div class="form-group">
<label for="username">Username</label>
<input type="text" class="form-control" id="username" name="username" placeholder="Username" autofocus>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" name="password" placeholder="Password">
</div>
<button type="submit" class="col-md-12 btn btn-primary login-button">Submit</button>
</fieldset>
</form>
</div>
</div>
</div>
<script type="text/javascript" src="custom/js/login.js"></script>
</body>
</html>
login.js
$(document).ready(function(){
$("#loginForm").unbind('submit').bind('submit', function() {
var form = $(this);
var url = form.attr('action');
var type = form.attr('method');
$.ajax({
url : url,
type : type,
data : form.serialize(),
dataType: 'json',
success:function(response) {
if(response.success === true) {
window.location = response.messages;
}
else {
if(response.messages instanceof Object) {
$("#message").html('');
$.each(response.messages, function(index, value) {
var key = $("#" + index);
key.closest('.form-group')
.removeClass('has-error')
.removeClass('has-success')
.addClass(value.length > 0 ? 'has-error' : 'has-success')
.find('.text-danger').remove();
key.after(value);
});
}
else {
$(".text-danger").remove();
$(".form-group").removeClass('has-error').removeClass('has-success');
$("#message").html('<div class="alert alert-warning alert-dismissible" role="alert">'+
'<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>'+
response.messages +
'</div>');
} // /else
} // /else
} // /if
});
return false;
});
});
Thanks to all, finally I have got a correct answer, the problem was due to the older version of codeignitor in php 7 server, for more info click
Codeigniter session data lost after redirect
Hi I was facing same issue. logs was showing nothing and my apache server got hanged. but in my case issue was with my controller. i did one mistake. i was printing array object in logs. instead of doing array to string conversion. i solved this and redirect function started working.
Just use refresh method, it works for me
$this->load->helper('url);
redirect('foo', 'refresh');
Here I have a validation with codeIgniter form_validation for customer name, which can prevent numerical digits as well as special characters and NULL.
And I have used a callback function which permit to stores only alphabetical characters within white spaces because name have always contains spaces.
Now the problem is, it can't be print their error message when validation goes false.
Here is my callback function
public function customAlpha($str)
{
if ( !preg_match('/^[a-z .,\-]+$/i',$str) )
{
$this->form_validation->set_message('customAlpha', 'The {field} field may only contain alphabetical characters.');
return false;
} else {
return True;
}
}
Here is my controller code
public function customer_upd()
{
$original_value = $this->db->query("SELECT customer_email FROM customer WHERE id = ".$_POST['ctmr_upd_id'])->row()->customer_email ;
if($_POST['cust_upd_email'] != $original_value) {
$this->session->set_flashdata('add_failed','Email id must be unique & valid email address.');
$is_unique = '|is_unique[customer.customer_email]';
} else {
$is_unique = '';
}
$original_value = $this->db->query("SELECT customer_mobile FROM customer WHERE id = ".$_POST['ctmr_upd_id'])->row()->customer_mobile ;
if($_POST['cust_upd_mobile'] != $original_value) {
$this->session->set_flashdata('add_failed','Mobile no must be unique & exact 10 digit numeric length. ');
$is_phoneunique = '|is_unique[customer.customer_mobile]';
} else {
$is_phoneunique = '';
}
$this->form_validation->set_rules('cust_upd_email', 'Email', 'required|valid_email|trim'.$is_unique);
$this->form_validation->set_rules('cust_upd_mobile', 'Mobile', 'required|exact_length[10]|is_natural|trim'.$is_phoneunique);
$this->form_validation->set_rules('cust_upd_name', 'Customer', 'trim|required|min_length[3]|callback_customAlpha');
if ($this->form_validation->run() ) {
$userdata = $this->session->userdata();
$userId = $userdata['id'];
if (!$userId):
redirect(site_url());
endif;
$data = array(
'customer_name' => ucwords($_POST['cust_upd_name']),
'birth_date' => $_POST['cust_upd_bd'],
'anniversery_date' => $_POST['cust_upd_dom'],
'customer_mobile' => $_POST['cust_upd_mobile'],
'customer_email' => $_POST['cust_upd_email'],
'status' => $_POST['cust_upd_status'],
'address' => $_POST['ctmr_address'],
'cat_type' => $_POST['file_cat']
);
$userdata = $this->session->userdata();
$userId = $userdata['id'];
$this->db->where('user_id', $userId);
$this->db->where('id', $_POST['file_cat']);
$this->db->where('cat_status', 'Enable');
$get_file = $this->db->get('category');
$res_file = $get_file->num_rows();
if($res_file >0){
$userdata = $this->session->userdata();
$userId = $userdata['id'];
$this->db->where('user_id', $userId);
$this->db->where('id', $_POST['ctmr_upd_id']);
$ctmr_upd = $this->db->update('customer', $data);
} else {
$this->session->set_flashdata('edit_failed','Something went wrong.');
redirect('customer/edit/'.$_POST['ctmr_upd_id']);
}
redirect(site_url() . '/customer');
} else {
redirect('customer/edit/'.$_POST['ctmr_upd_id']);
}
}
Here is my view code
<div class="item form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="name">Name <span
class="required">*</span>
</label>
<?php
foreach ($qry as $res_sel_qry){
?>
<div class="col-md-6 col-sm-6 col-xs-12">
<input id="onlyname" class="form-control col-md-7 col-xs-12" name="cust_upd_name"
placeholder="" value="<?php echo $res_sel_qry['customer_name']; ?>"
required="required" type="text">
</div>
<?php echo form_error('cust_upd_name'); ?>
</div>
There are many things that are going to validate and working fine expect customer name(doesn't showing there error message).
Please guide me, where I'm going wrong? Thanks.
Remove the redirect func
if ($this->form_validation->run() ) {
$userdata = $this->session->userdata();
$userId = $userdata['id'];
if (!$userId):
redirect(site_url());
endif;
$data = array(
'customer_name' => ucwords($_POST['cust_upd_name']),
'birth_date' => $_POST['cust_upd_bd'],
'anniversery_date' => $_POST['cust_upd_dom'],
'customer_mobile' => $_POST['cust_upd_mobile'],
'customer_email' => $_POST['cust_upd_email'],
'status' => $_POST['cust_upd_status'],
'address' => $_POST['ctmr_address'],
'cat_type' => $_POST['file_cat']
);
$userdata = $this->session->userdata();
$userId = $userdata['id'];
$this->db->where('user_id', $userId);
$this->db->where('id', $_POST['file_cat']);
$this->db->where('cat_status', 'Enable');
$get_file = $this->db->get('category');
$res_file = $get_file->num_rows();
if($res_file >0){
$userdata = $this->session->userdata();
$userId = $userdata['id'];
$this->db->where('user_id', $userId);
$this->db->where('id', $_POST['ctmr_upd_id']);
$ctmr_upd = $this->db->update('customer', $data);
} else {
$this->session->set_flashdata('edit_failed','Something went wrong.');
redirect('customer/edit/'.$_POST['ctmr_upd_id']);
}
redirect(site_url() . '/customer');
} else {
//redirect('customer/edit/'.$_POST['ctmr_upd_id']);
}
Replace this
<div class="col-md-6 col-sm-6 col-xs-12">
With
<div class="<?php if (form_error('cust_upd_name') != null) { echo ' has-error'; } ?>">
In your css
.has-error {
color : red;
}
I've got a really weird issue that I can't seem to figure out or understand. So essentially I have a to grab the ID passed through the Codeigniter URI, have it populate a hidden form, and then submitted. However when I submit the form as hidden, it comes back saying the data is NULL. I have tried and changed it to form_input and it works fine. Can anyone help me or explain to me why this is the case?
I have tried the following solutions.
URL
http://localhost/list/players/add/1/
where I want URI 3 ('1') to pass on to the form and submitted.
Solution 1 - Having the URI pass straight to data array
Controller
function add() {
if($this->form_validation->run() == FALSE) {
$data['view_file'] = 'add';
$this->load->module('template');
$this->template->cmslayout($data);
} else {
$league_id = $this->uri->segment(3);
$data = array(
'leagues_id' => $league_id,
);
if($this->_insert($data)){
return $query;
}
redirect ('/players/');
}
}
Solution 2 - Grabbing the URI and fill a hidden form
Controller
function add() {
$league_id = $this->uri->segment(3);
$this->load->module('leagues');
$data['leagues_list'] = $this->leagues->get_where($league_id);
if($this->form_validation->run() == FALSE) {
$data['view_file'] = 'add';
$this->load->module('template');
$this->template->cmslayout($data);
} else {
$data = array(
'leagues_id' => $this->input->post('leagues_id'),
);
if($this->_insert($data)){
return $query;
}
redirect ('/players/');
}
}
View
<?php
echo form_open('players/add/');
?>
<?php
echo "<br>";
echo "<br>";
echo "League Name";
echo "<br>";
foreach ($leagues_list->result() as $row) {
$league_id = $row->id;
$league_name = $row->league_name;
echo $league_name;
$data = array( 'name' => 'leagues_id',
'value' => $league_id,
);
echo form_hidden($data);
}
echo "<br>";
echo "<br>";
$data = array( 'value' => 'Set Player',
'name' => 'submit',
'class' => 'submit-btn',
);
echo form_submit($data);
echo form_close();
?>
In both scenarios, on submit it comes back with an error saying leagues_id is NULL. Now I have tried in Solution 2 to change from 'form_hidden' to 'form_input' and straight away clicking submit and it works fine.
Can anyone help me or advise why this is the case?
Many thanks.
If you want to add a parameter to your controller's function, you have to add it to: function func($parameter = 0) (= 0 is optional for default value).
In this case you can access the parameter by $parameter.
In your View file, you can open your form to post to the current url. For this you need to load the url helper in your controller: $this->load->helper('url'); (or you can autoload it in application/autoload.php).
Your form_hidden declaration was bad too. If you want to declare it with array(), then you have to use this syntax:
$data = array(
'name' => 'John Doe',
'email' => 'john#example.com'
);
echo form_hidden($data);
// Would produce:
<input type="hidden" name="name" value="John Doe" />
<input type="hidden" name="email" value="john#example.com" />
More information on Form helper: https://ellislab.com/codeigniter/user-guide/helpers/form_helper.html
For the right solution, try this:
Controller
function add($league_id = 0)
{
if($league_id != 0)
{
$this->load->module('leagues');
$data['leagues_list'] = $this->leagues->get_where($league_id);
if($this->form_validation->run() == FALSE)
{
$data['view_file'] = 'add';
$this->load->module('template');
$this->template->cmslayout($data);
}
else
{
$data = array(
'leagues_id' => $this->input->post('leagues_id'),
);
if($this->_insert($data))
{
return $query;
}
redirect ('/players/');
}
}
View
<?php
echo form_open(current_url());
echo "<br /><br />";
echo "League Name <br />";
foreach ($leagues_list->result() as $row)
{
$league_id = $row->id;
$league_name = $row->league_name;
echo $league_name;
echo form_hidden('leagues_id', $league_id);
}
echo "<br /><br />";
$data = array(
'value' => 'Set Player',
'name' => 'submit',
'class' => 'submit-btn'
);
echo form_submit($data);
echo form_close();
?>
I have a codeigniter form which allows the users to create dynamic fields .
I am able to store the data of the default fields in my database which I have given but how do I store the data dynamic fields which user generates into my database
html code:
<fieldset>
<h2 class="fs-title">Projects</h2>
<h3 class="fs-subtitle">Step 4</h3>
<div class="multi-field-wrapper">
<div class="multi-fields">
<div class="multi-field">
<?php echo validation_errors(); ?>
<input type="text" name="ptitle[]" id="ptitle" placeholder="Project Title" />
<input type="text" name="tech[]" id="tech" placeholder="Project Technology">
<textarea name="des" id="des[]" placeholder="Description" rows="10" cols="10"></textarea>
<button type="button" class="remove-field">Remove</button>
</div>
</div>
<button type="button" class="add-field">Add field</button>
</div>
<input type="button" name="previous" class="previous action-button" value="Previous" />
<input type="button" name="next" class="next action-button" value="Next" />
</fieldset>
controller code:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends CI_Controller {
public function index()
{
$this->load->view('register');
}
public function __construct(){
parent::__construct();
this->load->helper('form');
$this->load->library('session');
$this->load->library('form_validation');
$this->load->model('Register_model');
$this->load->helper(array('form', 'url'));
}
public function register()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('email','Email','required');
$this->form_validation->set_rules('rollno','Rollno','required');
$this->form_validation->set_rules('pass','Pass','required');
$this->form_validation->set_rules('cpass','Cpass','required');
$this->form_validation->set_rules('name','Name','required');
$this->form_validation->set_rules('branch','Branch','required');
$this->form_validation->set_rules('ypass','Ypass','required');
$this->form_validation->set_rules('phoneno','Phoneno','required');
$this->form_validation->set_rules('address','Address','required');
$this->form_validation->set_rules('year','Year','required');
$this->form_validation->set_rules('semester','Semester','required');
$this->form_validation->set_rules('percent','percent','required');
$this->form_validation->set_rules('ptitle','Ptitle','required');
$this->form_validation->set_rules('tech','Tech','required');
$this->form_validation->set_rules('des','des','required');
$this->form_validation->set_rules('achieve','achieve','required');
$this->form_validation->set_rules('skill','skill','required');
if($this->form_validation->run()==FALSE)
{
$this->load->view('register');
return false;
}
else
{
$data1 = array(
'email' => $this->input->post('email'),
'rollno' => $this->input->post('rollno'),
'password' => $this->input->post('pass'),
);
$data2 = array(
'name' => $this->input->post('name'),
'branch' => $this->input->post('branch'),
'ypass' => $this->input->post('ypass'),
'phoneno' => $this->input->post('phoneno'),
'address' => $this->input->post('address'),
'rollno' => $this->input->post('rollno'),
);
// $count = count($this->input->post('h'));
$yr = $this->input->post('year');
$sem = $this->input->post('semester');
$per = $this->input->post('percent');
$rol = $this->input->post('rollno');
/* for($i = 0;$i<$count;$i++)
{
*/
$data3 = array(
'year' => $yr,
'semester' => $sem,
'percent' => $per,
'rollno' => $rol,
/*'year' => $this->input->post('year'),
'semester' => $this->input->post('semester'),
'percent' => $this->input->post('percent'),
'rollno' => $this->input->post('rollno'),*/
);
// }
$data4 = array(
'ptitle' => $this->input->post('ptitle'),
'technology' => $this->input->post('tech'),
'description' => $this->input->post('des'),
'rollno' => $this->input->post('rollno'),
);
$data5 = array(
'achievement' => $this->input->post('achieve'),
'rollno' => $this->input->post('rollno'),
);
$data6 = array(
'skill' => $this->input->post('skill'),
'rollno' => $this->input->post('rollno'),
);
// }
$result = $this->Register_model->register($data1,$data2,$data3,$data4,$data5,$data6);
if($result == TRUE)
{
echo "your are registered successfully!";
}
else
{
// echo "unable to register,try again!";
$this->load->view('register');
}
}/*else */
} /*register*/
} //welcome
?>
model for above controller:
<?php
class Register_model extends CI_model
{
public function __construct()
{
parent::__construct();
}
public function register($data1,$data2,$data3,$data4,$data5,$data6)
{
$this->load->database();
$condition = "rollno =" . "'" . $data1['rollno'] . "'";
$this->db->select('*');
$this->db->from('signup');
$this->db->where($condition);
$this->db->limit(10);
$query = $this->db->get();
if ($query->num_rows() == 0) {
$this->db->insert('signup', $data1);
$this->db->insert('personaldetails', $data2);
$this->db->insert('academicdetails', $data3);
$this->db->insert('projects', $data4);
$this->db->insert('achievements', $data5);
$this->db->insert('skillset', $data6);
if ($this->db->affected_rows() > 0) {
return true;
}
}
else {
return false;
}
}
}
?>
You did not provided your html code and some more information, but let me give you an idea.
First, make the dynamic field as an array as i did below:
<textarea name="des[]" id="des" placeholder="Description" rows="10" cols="10"></textarea>
Now it does not matter how many new fields are added, it will have the same name as above.
When you get that field in your CI code, the des will be an array with all the values. Now you can apply validation to them using loop or what ever you want to do.
To save that fields data in database, it is good to save it in the form of json as below.
$des = $this->input->post('des');
$encoded = json_encode($des);
This way, it wont matter if you have a single dynamic field or hundred, it will be saved easily. And when you need that data, just fetch it from DB, json decode it as below and loop through it according to your purpose.
$dec = json_decode($value_from_db);
Hope it will help.