So I have made a form where staff members can post activities like soccer or tennis with a form. So I have 2 dates which they can select. The first date is the start date of the activity and the second date is the end date of the activity. I don't want it to be able to select an end date earlier than a selected startdate. So for example I want to fill in an activity like bowling and it in the form I put at the start date 03-04-2018 and the end date 02-02-2018, I don't want that to be possible.
This is how my form looks:
<?php echo form_open('index.php/Jongeren_activiteiten/Add_activiteit'); ?>
<br>
<center>Naam van activiteit:</center>
<div class="form-group">
<input class="form-control" name="activiteit" id="activiteit" type="text">
</div>
<center>Begindatum:</center>
<div class="form-group">
<input class="form-control" name="begindatum" id="begindatum" placeholder="Startdatum cursus" type="date">
</div>
<center>Einddatum:</center>
<div class="form-group">
<input class="form-control" name="einddatum" id="einddatum" placeholder="einddatum cursus" type="date">
</div>
<div>
<button class="btn btn-primary" name="Add_activiteit" >Toevoegen</button>
</div>
</form>
And this is the controller function of the form:
public function Add_activiteit()
{
if (isset($_POST['Add_activiteit'])) {
$this->form_validation->set_rules('activiteit', 'Activiteit', 'required');
$this->form_validation->set_rules('begindatum', 'Begindatum', 'required');
$this->form_validation->set_rules('einddatum', 'Einddatum', 'required');
//If form validation true
if ($this->form_validation->run() == TRUE) {
// echo 'form validated';
$data = array (
'activiteit'=>$_POST['activiteit'],
'begindatum'=>$_POST['begindatum'],
'einddatum'=>$_POST['einddatum'],
);
$this->db->insert('activiteit',$data);
$this->session->set_flashdata("success", "u heeft een nieuwe activiteit toegevoegd");
redirect("index.php/Jongeren_activiteiten", "refresh");
}
}
}
begindatum means start date and einddatum means end date. So how do I fix it so you can only select an end date later than a startdate?
I also don't want people to being able select a day in the past.
Any kind of help is appreciated
You should use a callback function..
The way you would do this is by creating a function like this:
function checkDate($start, $end){
if($start > $end){
$this->form_validation->set_message('checkDate', 'The end date must be later than the start date.');
return FALSE;
}else{
return TRUE;
}
}
Then you would add it to your form validation rules(I would do it for the end date), but prefix it with 'callback_'
So it would look like this:
$this->form_validation->set_rules('einddatum', 'Einddatum', 'required|callback_checkDate');
A further explanation provided by CodeIgniter can be found here: https://www.codeigniter.com/user_guide/libraries/form_validation.html
Related
I need a help for avoid duplication entries on my database table using CodeIgniter.
I have a table called “user_course_tbl” with 3 columns as mentioned below.
Id
staff_name
course_code
I need to enter staff name and course code without duplications.
As mentioned in table, same person can add more different course codes. But same person couldn’t add same course code more than 1.
Ex: Smith has more different courses for the table. It will be ok. But Ann has same course more than 1. This should be avoiding. should not have same value for staff_name and course_code columns both together.
I wrote coding for the above matter. But I couldn’t understand to validate this matter.
View
<?php echo form_open_multipart('Course/insert_courses_for_users');?>
<div class="box-body">
<div class="col-md-6">
<div class="form-group">
<label>User</label>
<select id="user" class="form-control" name="user" required>
<option value="">Select</option>
<?php
if(isset($user))
{
foreach($user as $cnt)
{
print "<option value='".$cnt['staff_name']."'>".$cnt['staff_name']."</option>";
}
}
?>
</select>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>Course Code</label>
<select id="CourseCode" class="form-control" name="courscode" onchange="getcoursename(this.value)" required>
<option value="">Select</option>
<?php
if(isset($coursecode))
{
foreach($coursecode as $cnt)
{
print "<option value='".$cnt['course_code']."'>".$cnt['course_code']."</option>";
}
}
?>
</select>
</div>
</div>
Controller
function insert_courses_for_users()
{
$this->form_validation->set_rules('user', 'User', 'required');
$this->form_validation->set_rules('courscode', 'Course Code', 'required');
$id=$this->input->post('txtid');
$user=$this->input->post('user');
$coursecode=$this->input->post('courscode');
$data=$this->Course_model->insert_courses_for_user(array('id'=>$id,'staff_name'=>$user,'course_code'=>$coursecode));
if($data==true)
{
$this->session->set_flashdata('success', "New Course added for user Succesfully");
}else
{
$this->session->set_flashdata('error', "Sorry, New Course added for user is Failed.");
}
redirect($_SERVER['HTTP_REFERER']);
}
Model
function insert_courses_for_user($data)
{
$this->db->insert("user_course_tbl",$data);
return $this->db->insert_id();
}
Could you please help to solve this matter?
(1)Method:-
In Controller:-
When you define the form validation , add a validator for is_unique
$this->form_validation->set_rules('staff_name', 'Staff Name', 'required|is_unique[user_course_tbl.staff_name]');
(2)Method:-
Search in the database ,the course_code & staff_name before insertion they exsists or not.
Solution 1
$courscode=$this->db->query('select * from user_course_tbl where
courscode='.$this->input->post('courscode'));
if(isset($courscode) && !empty($courscode)) { $is_unique =
'|is_unique[user_course_tbl.courscode]' } else { $is_unique = ''
}
$this->form_validation->set_rules('courscode', 'Course Code',
'required|trim|xs0s_clean'.$is_unique);
$this->form_validation->set_message('is_unique', 'The %s is already
taken, Please use another %s'); // add message for the is_unique
note :use same for staff name.
Solution 2:
$this->form_validation->set_rules('courscode', 'Source Code', 'required|is_unique[user_course_tbl.courscode');
good day,
I new in laravel Framework and I face this two problems : -
first one
I want to redirect to my page after 2 seconds automatically.
the second one
I make custom function call (is exist )
if this function returns true data I want to print "name exist before " but the problem here is form was rested when this function returns true and print message.
how to prevent form resetting from inputs value?
here is my code
controller code
enter code here
public function add(Request $request)
{
// start add
if($request->isMethod('post'))
{
if(isset($_POST['add']))
{
// start validatio array
$validationarray=$this->validate($request,[
//'name' =>'required|max:25|min:1|unique:mysql2.products,name|alpha',
'name' =>'required|alpha',
'price' =>'required|numeric',
]);
// check name is exist
if(true !=dBHelper::isExist('mysql2','products','`status`=? AND `deleted` =? AND `name`=?',array(1,1,$validationarray['name'])))
{
$product=new productModel();
// start add
$product->name=$request->input('name');
$product->save();
$add=$product->id;
$poducten=new productEnModel();
$poducten->id_product=$add;
$poducten->name=$request->input('name');
$poducten->price=$request->input('price');
$poducten->save();
$dataview['message']='data addes';
}else{
$dataview['message']='name is exist before';
}
}
}
$dataview['pagetitle']="add product geka";
return view('productss.add',$dataview);
}
this is my routes
Route::get('/products/add',"produtController#add");
Route::post('/products/add',"produtController#add");
this is my view
#extends('layout.header')
#section('content')
#if(isset($message))
{{$message}}
#endif
#if(count($errors)>0)
<div class="alert alert-danger">
<ul>
#foreach($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
</div>
#endif
<form role="form" action="add" method="post" enctype="multipart/form-data">
{{csrf_field()}}
<div class="box-body">
<div class="form-group{{$errors->has('name')?'has-error':''}}">
<label for="exampleInputEmail1">Employee Name</label>
<input type="text" name="name" value="{{Request::old('name')}}" class="form-control" id="" placeholder="Enter Employee Name">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email Address</label>
<input type="text" name="price" value="{{Request::old('price')}}" class="form-control" id="" placeholder="Enter Employee Email Address">
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" name="add" class="btn btn-primary">Add</button>
</div>
</form>
#endsection
I hope that I understood your question.
Instead of using {{ Request::old('price') }} use {{ old('price') }}
This should retrieve the form data after page was reloaded.
Try the below the code for error display in view page
$validator = Validator::make($params, $req_params);
if ($validator->fails()) {
$errors = $validator->errors()->toArray();
return Redirect::to($web_view_path)->with('errors', $errors);
}
You want to automatically redirect to another page submit the form using ajax and use below the settimeout menthod.
setTimeout(function(){ // Here mentioned the redirect query }, 3000);
//use $request instead of $_POST
if($request->isMethod('post'))
{
if(isset($request['add']))
{
// start validatio array
$validationarray=$this->validate($request,[
//'name' =>'required|max:25|min:1|unique:mysql2.products,name|alpha',
'name' =>'required|alpha',
'price' =>'required|numeric',
]);
// check name is exist
Hi I have a form to add members with their birth date. The input field for birth date is:
<div class="form-group">
<label for="data_nascita" class="col-sm-3 control-label">Birth Date</label>
<div class="col-sm-9">
<input name="data_nascita" type="date" class="form-control" id="data_nascita" placeholder="gg/mm/aaaa" />
</div>
</div>
Data are correctly uploaded to MYSQL and date format is
$data_nascita = ($_POST['data_nascita']);
var_dump($data_nascita); => string(10) "2003-04-15"
In the database is stored correctly, and it appears as
2018-12-14 18:50:48
I want to have the possibility to edit the information about the person (i.e. changing the birth date), and I created an edit file where all the database information is retrieved and appears in form fields that can be edited and updated in MYSQL.
Everything works fine except for dates, which appears as gg/mm/aaaa
The code I used for retrieving data is as usual:
<?php
$query = "SELECT data_nascita FROM volontari WHERE id_volontari = '$id'";
$res = $mysqli ->query($query);
$row = $res->fetch_array (MYSQLI_ASSOC);
$data_nascita = gira_data_db($row['data_nascita']);
function gira_data_db($data)
{
$array = explode( "-" , $data);
$array2 = array($array[2], $array[1], $array[0]);
$testo = implode( "/" , $array2);
return $testo;
}
?>
<div class="form-group">
<label for="data_nascita" class="col-sm-3 control-label">Birth Date</label>
<div class="col-sm-9">
<input name="data_nascita" type="date" class="form-control" id="data_nascita" value="<?php echo $data_nascita ?>" />
</div>
</div>
The date retrieved is
var_dump(gira_data_db($row['data_nascita']);) => string(10) "15/04/2003"
However in my form field the data appears as 00/00/0000. If I echo the date in an input field type=text, it appears correct.
Am I doing something wrong?
The problem is when you explode by '-' array[2] is '14 18:50:48' and it's not valid value for input with date type.
simply change gira_data_db function as follows:
function gira_data_db($data)
{
return date("YYYY-MM-DD", strtotime($data));
}
I hope it would help you
So I have this form where i can fill in companies but right now I am being able to insert multiple companies with the same name but I don't want that.. I want the name of the company to be unique or else if I put in the same name thats already in the database it should give me an error.
How can I do that?
This is my form in my view html:
<br>
<center> <h3> Instituut toevoegen </h3> </center>
<br>
<?php echo form_open('index.php/Instituut/Add_instituut'); ?>
<div class="form-group">
<label>Instituut:</label>
<input class="form-control" name="instituut" id="instituut" type="text">
</div>
<div class="form-group">
<label>Telefoonnummer van instituut:</label>
<input class="form-control" name="instituuttelefoon" id="instituuttelefoon" type="text">
</div>
<div>
<button class="btn btn-primary" name="Add_instituut" >Toevoegen</button>
</div>
</form>
</div>
This is the controller function:
public function Add_instituut()
{
if (isset($_POST['Add_instituut'])) {
$this->form_validation->set_rules('instituut', 'Instituut', 'required');
$this->form_validation->set_rules('instituuttelefoon', 'instituuttelefoon', 'required');
//If form validation true
if ($this->form_validation->run() == TRUE) {
//voeg werknemer toe in database
$data = array (
'instituut'=>$_POST['instituut'],
'instituuttelefoon'=>$_POST['instituuttelefoon'],
);
$this->db->insert('instituut',$data);
$this->session->set_flashdata("success", "u heeft een nieuw instituut toegevoegd");
redirect("index.php/Instituut", "refresh");
}
}
}
I probably should add something in the form validation rules?
instituut means company name
Thanks
any kind of help is appreciated
You can add is_unique in form validation rules
$this->form_validation->set_rules('instituut', 'Instituut', 'required|is_unique[your_table_name.instituut]');
check tutorial. for unique value:
https://www.codeigniter.com/userguide3/libraries/form_validation.html#rule-reference
I have all my callback functions in My_Controller so that they are not repeated throughout the website. This works fine but for some reason one of my functions is not working when I am posting information using AJAX but is working on other pages. The message I get back when I use the callback is:
Unable to access an error message corresponding to your field name.
But then I've created a message for it using set_message() and it works fine on the other page without AJAX.
If you were interested in the log, here is the relevant output when entering an invalid date:
ERROR - 2013-05-24 16:03:08 --> -----Valid date format called, 223013-05-15
ERROR - 2013-05-24 16:03:08 --> -----Should be okay = , 223013-05-15
ERROR - 2013-05-24 16:03:08 --> -----Valid date format = false, 223013-05-15
And with a valid date:
ERROR - 2013-05-24 16:06:00 --> -----Valid date format called, 2013-05-24
ERROR - 2013-05-24 16:06:00 --> -----Should be okay = , 2013-05-24
ERROR - 2013-05-24 16:06:00 --> -----Valid date format = true, 05,24,2013
Here is the callback:
class MY_Controller extends CI_Controller
{
var $options;
public function __construct()
{
parent::__construct();
date_default_timezone_set('Europe/London');
$this->options->calendar = FALSE;
}
//Check date format aggainst mysql format, valid dates only, no 30-2-2010.
function _Valid_Date_Format($date)
{
log_message('error', '-----Valid date format called, '.$date);
if( empty($date) )
{
$this->form_validation->set_message('_Valid_Date_Format', 'This date is required.');
return FALSE;
}
else
{
log_message('error', '-----Should be okay = , '.$date);
}
$parsed = explode('-',$date);
if( checkdate($parsed[1],$parsed[2],$parsed[0]) )
{
log_message('error', '-----Valid date format = true, '.$parsed[1].','.$parsed[2].','.$parsed[0]);
return TRUE;
}
log_message('error', '-----Valid date format = false, '.$date );
$this->form_validation->set_message('_Valid_Date_Format', 'The Date entered is invalid.');
return FALSE;
}
}
Here is the AJAX Code:
//Submit time feature
$("#submit_time").click(function()
{
var cct = $.cookie('csrf_simple_cookie');//Overcome ajax limitation with csrf function, see below:
$.ajax({
url: folder,
type:"POST",
context: document.body,
data: {t_id:$('#t_id').val(),
time_for:$('#time_for').val(),
hrs_spent:$('#hrs_spent').val(),
mins_spent:$('#mins_spent').val(),
timer_description:$('#timer_description').val(),
date_worked:$('#date_worked').val(),
csrf_simple_collab:cct},
dataType: "json",
error: function(XMLHttpRequest,error)
{
if(error=='parsererror')//Not logged in.
{
window.location.replace(loginFolder)//redirect to login page
}
},
success: function(data)
{
if(data.success)
{
var message=$('#message-box').html('<span>Time data added successfully.</span>').hide();
message.fadeIn("slow");
javascript:location.reload(true);
}
else
{
if(data.validation)
{
//var message=$('#message-box').html("<span>Database error</span>");
var message=$('#message-box').html(data.error);
}
else
{
var message=$('#message-box').html(data.error);
$('#time-for-error').html(data.time_for);
$('#date-worked-error').html(data.date_worked);
$('#mins-spent-error').html(data.mins_spent);
$('#hrs-spent-error').html(data.hrs_spent);
$('#timer-description-error').html(data.timer_description);
}
}
}
});
return false;
});
Here is the view:
<?
//If we are an admin we can alter the user the information is added for.
if($this->session->userdata('userType')=='admin'): ?>
<div class="form_row">
<div class="form_field">
<label for="time_for">User:</label>
</div>
<div class="form_field name_element" id="time-for-container">
<select name="time_for" id="time_for">
<?
foreach($users as $key => $u):
if($u->userId==$this->session->userdata('userId')):
?>
<option selected="selected" value="<?=$u->userId?>"><?=$u->userName?></option> <?='\n'?>
<?
else:
?>
<option value="<?=$u->userId?>"><?=$u->userName?></option> <?='\n'?>
<?
endif;
endforeach;
?>
</select>
<p id="time-for-error"></p>
</div>
</div>
<? else: ?>
<input type="hidden" id="time_for" name="time_for" value="<?=$this->session->userdata('userId')?>">
<? endif; ?>
<div class="form_row">
<div class="form_field">
<label for="hrs_spent">Hours and minutes spent:</label>
</div>
<div class="form_field name_element" id="mins-spent-container">
<input type="text" maxlength="6" name="hrs_spent" id="hrs_spent" value="" />
<span id="min-separator">:</span>
<input type="text" maxlength="6" name="mins_spent" id="mins_spent" value="" />
<p id="mins-spent-error"></p>
<p id="hrs-spent-error"></p>
</div>
</div>
<div class="form_row">
<div class="form_field">
<label for="date_worked">Date Worked:</label>
</div>
<div class="form_field name_element" id="date-picker-container">
<input type="text" name="date_worked" id="date_worked" />
<p id="date-worked-error"></p>
</div>
</div>
<div class="form_row">
<div class="form_field">
<label for="timer_description">Description:</label>
</div>
<div class="form_field name_element" id="description-container">
<textarea name="timer_description" id="timer_description" value=""></textarea>
<p id="timer-description-error"></p>
</div>
</div>
<input type="hidden" id="c_id" name="c_id" value="<?=$task->c_id ?>" />
<input type="hidden" id="p_id" name="p_id" value="<?=$task->p_id ?>" />
<input type="hidden" id="t_id" name="t_id" value="<?=$task->t_id ?>" />
<input type="hidden" name="login-folder" id="login-folder" value="<?=base_url()?>login" />
<input type="hidden" name="submit-folder" id="submit-folder" value="<?=base_url()?>times/submit_time" />
<div class="form_row">
<div id="message-box"></div>
<input type="button" name="submit" id="submit_time" class="button-styles button-three" value="Add time" />
</div>
</div>
Controller method:
class Times extends MY_Controller
{
var $options;
//Ajax function used to submit the time information from task page form.
function submit_time()
{
$options=array();
$this->form_validation->set_rules("time_for","Time for","trim|required|is_natural_no_zero");
$this->form_validation->set_rules("hrs_spent","Hrs spent","trim|required|is_natural|min_length[1]|max_length[5]");
$this->form_validation->set_rules("mins_spent","Mins spent","trim|required|is_natural|min_length[1]|max_length[2]|less_than[60]");
$this->form_validation->set_rules("timer_description","Description","trim|min_length[5]|max_length[1000]");
$this->form_validation->set_rules("date_worked","Date Worked","trim|required|callback__valid_date_format");
//$json->data=array('success'=>0,'validation'=>1,'error'=> validation_errors() );
//$this->load->view('data/json_encode',$json);
if($this->form_validation->run())
{
$options['hrs_spent'] = $this->input->post('hrs_spent');
$options['mins_spent'] = $this->input->post('mins_spent');
$options['timer_description'] = $this->input->post('timer_description');
$options['date_worked'] = $this->input->post('date_worked');
$options['t_id'] = $this->input->post('t_id');
$options['u_id'] = $this->input->post('time_for');//Notice time for field here.
$add = $this->time_model->add_time($options);
if(!$add):
$json->data=array('success'=>0,'validation'=>1,'error'=>'Database error');
else:
$json->data=array('success'=>1,'validation'=>1);
$this->log_model->add_log_entry( array('log_id'=>1,'item'=>'Time record "'.reduce_string($options['timer_description'],50).'" was added for user '.$options['u_id'].'.') );
endif;
$this->load->view('data/json_encode',$json);
}
else
{
$json->data = array(
'time_for' => form_error('time_for'),
'hrs_spent' => form_error('hrs_spent'),
'mins_spent' => form_error('mins_spent'),
'timer_description' => form_error('timer_description'),
'date_worked' => form_error('date_worked'),
'success'=>0,
'validation'=>0,
'error'=>'There are errors in the form.'
);
$this->load->view('data/json_encode',$json);
}
}
}
The problem is the capitalization used in the callback method name. The method name, and all subsequent references to it as a validation rule, should be all lowercase.
To explain, this is the relevant part of the Form Validation library that causes the message:
if ( ! isset($this->_error_messages[$rule]))
{
if (FALSE === ($line = $this->CI->lang->line($rule)))
{
$line = 'Unable to access an error message corresponding to your field name.';
}
}
else
{
$line = $this->_error_messages[$rule];
}
All of your set_message() calls name the rule as _Valid_Date_Format, which is the array key that exists in $this->_error_messages.
Because your rule is defined as _valid_date_format, and because PHP is case-sensitive most of the time, the isset() rule fails, and you clearly don't have a language line defined for it, so it goes to the default.
In general, using capitalization in your controller methods will cause problems. So it's best to avoid doing so.