Codeigniter validation required show event when the field is not empty.
UPDATE:
I using ajax and jquery to get the data. So I solve the problem by using this
$('#form_post_topic').submit(function(event){
event.preventDefault();
var value = CKEDITOR.instances['content'].getData();
$.ajax({
url: 'write_validation',
type: 'post',
data: {
name: $('#name').val(),
category: $('#category').val(),
content: value,
tags: $('#tags').val()
},
you need to have this
view.php
<form action ="validate_form" mehotd="post">
<label>Topic Name</label>
<input type="text" name="tname" value="<?= set_value('tname');?>"><br>
<label>Select Category</label>
<select name="category">
<option value="1" <?php echo set_select('myselect', 'one', TRUE); ?> >category 1</option>
</select><br>
<label>Content</label>
<textarea name="content" placeholder="write some content"><?= set_value('content');?></textarea><br>
</form>
controller.php
function validate_form(){
$this->form_validation->set_rules('tname', 'Topic Name', 'trim|required|xss_clean');
$this->form_validation->set_rules('category', 'Category', 'trim|required|xss_clean');
$this->form_validation->set_rules('content', 'Content', 'trim|required|xss_clean');
if ($this->form_validation->run() === FALSE){
$this->load->view('myform');
}
else{
$this->load->view('formsuccess');
}
}
The important thing is the name in textarea
Yes, I am also getting data with use of this code.
var value = CKEDITOR.instances['content'].getData();
Related
Problem is in my edit page the one dropdown value is selected but the other dropdown who called with first dropdown value is not show hear the code is
$(document).ready(function() {
// alert('onload');
// alert($('#company_name').val())
$('#company_name').change(function() {
var id = $('#company_name').val();
if (id != '') {
$.ajax({
url: BaseURL + 'admin/campaign/fetch_template',
type: 'POST',
data: {
id: id,
},
success: function(data) {
$('#template').html(data);
}
});
} else {
$('#template').html('<option value="selected">Select Template</option>');
}
});
});
I want to add this a selected value of dropdown.....
<select onchange='getTemplate(this.value);' class="form-control" id="template" name="template" data-placeholder="Select a option">
<option value="">Select Template</option>
</select>
this is the dropdown which i want to get selected value &
<select class="form-control" name="company" class="form-control " data-placeholder="Select a option" id="company_name">
<option value="1">Select Company</option>
<?php foreach ($company as $con) { ?>
<option value="<?php echo $con->company_id ?>" <?php echo $edit['id'] == $con->company_id ? 'selected' : '' ?>><?= $con->name; ?>
</option>
<?php } ?>
</select>
and this is where i call a company name to select the templeate each company
I have a form with 3 radio buttons. The IDs are unique in the form, and all three have the same name, namely "vehicle_type". The radio buttons are generated correctly when I do source view
<input type="radio" name="vehicle_type" id="type_vehicle" value="1">
<input type="radio" name="vehicle_type" id="type_trailer" value="2" checked>
<input type="radio" name="vehicle_type" id="type_plant" value="3">
I have no validation rule set for the radio group, yet my form complains that the field is required.
I can confirm that there is no validation rule by running:
echo $this->form_validation->has_rule('vehicle_type');
It indicates no validation. Using that call on another field, i.e., client_name, returns "boolean: 1"
Why would the field try to validate if there is no validation rule set?
EDIT
I am using Wiredesignz HMVC in my project, so the Form_validation class is extended.
if ($this->form_validation->run($this)) {
$test = do_file_upload($post_data);
} else {
var_dump(validation_errors());
// echos "The Vehicle type field is required"
}
This problem only occurs with radio buttons:
All other forms without radio buttons validate correctly using the same check: ($this->form_validation->run($this)
My form validation is set with this function:
public function set_form_validation_rules($data)
{
foreach ($data as $field) {
if (!empty($field['validation']['rules'])) {
if (!is_array($field['validation']['rules'])) {
$this->form_validation->set_rules($field['name'], $field['label'], $field['validation']['rules']);
} else {
foreach ($field['validation']['rules'] as $fv) {
$this->form_validation->set_rules($field['name'], $field['label'], $fv);
}
}
}
}
}
And the radio button is defined as:
$data['fields']['type_plant'] = [
'name' => 'vehicle_type',
'id' => 'type_plant',
'input_class' => 'input-group width-100',
'color' => 'red',
'value' => 3,
'validation' => '',
'checked' => ($posts['vehicle_type'] == 3)
];
The other two radio buttons in the group are the same, just have different values and IDs.
Use this,
$this->form_validation->set_rules('vehicle_type', 'Vehicle type', 'required');
Load library for form validation and other helpers in application/config/autoload.php
$autoload['libraries'] = array('form_validation');
$autoload['helper'] = array('form', 'url');
In your controller file :
$this->form_validation->set_rules('vehicle_type', 'Vehicle Type', 'required');
In your view file use below code for printing validation errors
<?php echo validation_errors(); ?>
The answers given above tells me how to use form validation. It is not what I requested. I am far beyond that - as they all worked, except for radio buttons. As it turns out, passing the validation array incorrectly to the function in the $data array. Once I passed the data correctly, the form validation also worked.
Hey Bro Try this maybe it can help
This method is very simple
In form
<div class="form-group">
<label for="vehicle_type" class="col-sm-3 control-label">vehicle</label>
<div class="col-sm-9">
<div class="col-md-3">
<label><input type="radio" name="vehicle_type" id="vehicle_type" value="1"> ONE </label>
</div>
<div class="col-md-3">
<label><input type="radio" name="vehicle_type" value="2"> TWO </label>
</div>
<div class="col-md-3">
<label><input type="radio" name="vehicle_type" value="3"> THREE </label>
</div>
<small class="info help-block"></small>
</div>
</div>
Set Your Controller
public function add_save(){
if ($this->input->post('vehicle_type') == "1"){
}else if($this->input->post('vehicle_type') == "2"){
}else if($this->input->post('vehicle_type') == "3"){
}else{
$this->form_validation->set_rules('vehicle_type', 'Vehicle', 'required');
}
if ($this->form_validation->run()) {
$save = [
'vehicle_type' => $this->input->post('vehicle_type')
];
$this->model_yourmoderl->add($save);
} else {
$this->data['errors'] = $this->form_validation->error_array();
}
$this->response($this->data);
}
This is the structure of my table "task"
projectname
employee
clientname
task
Dependencies are as follows
One project has multiple task
One project has multiple employees
I need to create a dropdown list when user selects a particular project tasks relevant to them will automatically load to the next dropdown list. In this situation I do not need primary and foriegn key relationship. Any help would be really appreciated
This is my controller
public function Task(){
$data['cname'] = $this->welcome4->show_students3();
$data['projects'] = $this->welcome4->show_students();
$data['employee'] = $this->welcome4->show_students2();
$this->load->view('template/navigation');
$this->load->view('template/sideNav');
$this->load->view('template/header');
$this->load->view('Task',$data);
$this->load->view('template/footer');
}
This is my model
function show_students2(){
$query = $this->db->get('employee');
$query_result = $query->result();
return $query_result;
}
function show_students3(){
$query = $this->db->get('clientdetails');
$query_result = $query->result();
return $query_result;
}
function show_students4(){
$query = $this->db->get('task');
$query_result = $query->result();
return $query_result;
}
This is my view
<div class="form-group">
<label>Select Project</label>
</div>
<div class="form-group">
<select name="projectname" class="input form-control">
<option value="none" selected="selected">Select Project</option>
<?php foreach($projects as $s):?>
<option value="<?php echo $s->projectname?>"><?php echo $s->projectname?></option>
<?php endforeach;?>
</select>
</div>
<div class="form-group">
<label>Select Client</label>
<select name="cname" class="input form-control">
<option value="none" selected="selected">Select client</option>
<?php foreach($cname as $s):?>
<option value="<?php echo $s->cname?>"><?php echo $s->cname?></option>
<?php endforeach;?>
</select>
</div>
<div class="form-group">
<label>Select Employee</label>
</div>
<div class="form-group">
<select name="employee" class="input form-control">
<option value="none" selected="selected">Select Employee</option>
<?php foreach($employee as $s):?>
<option value="<?php echo $s->employee?>"><?php echo $s->employee?></option>
<?php endforeach;?>
</select>
</div>
This loads all projects, clients, employee in the database.But now I want when project is selected in the first drodown, second dropdown should show only relevant clients and employees to it. Not all of them
Lets consider this will be your Projects select box, in which you are loading data dynamically on page load with php.
<select name="projectname" id="projectname"></select>
Tasks select box.
<select name="tasks" id="tasks"></select>
Inside your controller add below mentioned code. This function will be used for get data from ajax call.
public function getTasks() {
$Id = $this->input->post('project_id');
if ($Id):
$this->load->model('Task_model', 'Tasks', TRUE);
$data = $this->Tasks->getProjectTasks($Id);
if ($data):
$result['status'] = true;
$result['records'] = $data;
endif;
else:
$result['status'] = false;
endif;
echo json_encode($fdata);
}
Inside model please add this function. Which will fetch data from DB
ans pass it to controller back.
public function getProjectTasks($id = null) {
if ($id):
$this->db->select('id,task');
$this->db->where('project_id', $id);
$this->db->where('status', TRUE);
$query = $this->db->get('tasks');
$records = $query->result();
if ($records):
return $records;
else:
return false;
endif;
else:
return false;
endif;
}
And finally in you View file please add below function.
$(document).on('#projectname', 'change', function() {
var projectId = $(this).val();
$.ajax({
type: 'POST',
url: 'URL',
data: {project_id: projectId},
dataType: "json",
beforeSend: function() {
$('#tasks')
.empty()
.append('<option selected="selected">Select Task</option>');
},
success: function(data) {
if (data.status) {
$.each(data.records, function(i, item) {
$('#tasks').append($('<option>', {
value: item.value,
text: item.text
}
));
});
} else {
$('#tasks')
.empty()
.append('<option selected="selected">No Task available</option>');
}
}
});
});
Is it possible to make codeigniter not to redirect after a failed login attempt and show a message on the same login box.
My login box is a popup type, which appears after I have clicked on the login button and disappears after clicking on the background.
Controllers
public function login_validation() {
$this->load->library('form_validation');
$this->form_validation->set_rules('email','Email','required|trim|callback_validate_credentials');
$this->form_validation->set_rules('password','Password','required|md5');
if($this->form_validation->run()){
$data=array(
'email' => $this->input->post('email'),
'is_logged_in' => 1
);
$this->session->set_userdata($data);
redirect('site/members');
}else {
$this->main();
}
}
public function validate_credentials(){
$this->load->model('model_users');
if($this->model_users->can_log_in()){
echo 'success';
} else {
echo 'failed';
}
}
I was trying to change elses with error messages but it still redirected to another page.
Html:
<div id="login-box" class="login-popup">
<input id="username" name="email" value="" type="text" autocomplete="on" placeholder="Username">
<input id="password" name="password" value="" type="password" placeholder="Password">
<button name="login_submit" class="submitbutton" onclick="checkFormData()">Login</button>
</div>
<script>
function checkFormData(){
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>site/validate_credentials",
data: {
email: $("#email").val(),
password: $("#password").val()
},
success: function(response) {
if(response == 'success'){
location.href = 'site/members';
} else {
$("#errors").show();
}
}
});
}
</script>
If you want to have the alert in the modal, you'll want to check the data with ajax (javascript or jquery). For example you'd have something like this:
function checkFormData(){
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>your_controller/validate_credentials",
data: {
email: $("#email").val(),
password: $("#password).val()
},
success: function(response) {
if(response == 'success'){
location.href = <where you want to send them>;
} else {
$("#errors").show();
}
}
});
}
And your HTML would look something like:
<div class="hide" id="errors">Incorrect username/password.</div>
<input type="email" id="email" />
<input type="password" id="password" />
The class="hide" is meant to be something CSS related where you would have something like "display: none;".
Then in your controller you'd check like this:
if($this->model_users->can_log_in()){
echo 'success';
} else {
echo 'failed';
}
The echoed response is what will be sent to your ajax success function.
Edit:
You need to not use the form submission for the above to work, because with that method we don't want to submit the form, we want to pass the data from it.
<div id="login-box" class="login-popup">
<input id="username" name="email" value="" type="text" autocomplete="on" placeholder="Username">
<input id="password" name="password" value="" type="password" placeholder="Password">
<button name="login_submit" class="submitbutton" onclick="checkFormData()">Login</button>
</div>
I've also changed the javascript function above to be viewed as a function.
use
window.location.href = '/redirectpage'
The problem is that when i use submit, codeigniter process the script cleanly. But when I passed the data thru ajax. script works fine. It even outputs the array when i use print_r. Its just that it doesn't update the database. everything is fine until the activerecord script.
Here is my controller script. (I just simplified it).
What I did was there is a script that would create an empty row. Thus, it will retrieve the Article id which will be used to save the article.
Here is the save article function.
Controller:
function saveArticle(){
$this->userarticle_model->trial();
}
Model:
function trial(){
$userid = $this->session->userdata('userid');
$articleId = $this->input->post('article_id');
$articleData = array(
'sfc_articleAuthor' =>$userid ,
'sfc_articleTitle' => $this->input->post('article_title'),
'sfc_articleContent' => $this->input->post('article_content'),
'sfc_articleStatus' => 'saved',
'sfc_articleTag' =>$this->input->post('article_tag'),
'sfc_articleCategory' => $this->input->post('article_category')
);
$this->db->where('sfc_articleId', $articleId);
$this->db->update('sfc_articles', $articleData);
}
AJAX:
(Sorry, I just copied this from a tutoral.)
$(document).ready(function(){
$('.save').click(function() {
$('#article_form').hide(0);
$('#message').hide(0);
var article_title = $('#article_title').val();
var article_tag = $('#article_tag').val();
var article_id = $('#articleId').val();
var article_category = $('#article_category').val();
var article_content = $('#article_form').find('.nicEdit-main').text();
var article_status = 'saved';
var dataString = 'article_title='+ article_title + '&article_tag=' + article_tag + '&article_category=' + article_category + '&article_content=' + article_content + '&article_status=' + article_status;
$.ajax({
type : 'POST',
url : 'http://localhost/ci_usage/index.php/article/saveArticle',
dataType : 'json',
data: dataString,
success : function(data){
$('#waiting').hide(500);
if (data.error === false)
$('#article_form').show(10);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
$('#article_form').hide(10);
$('#article_form').show(3);
}
});
return false;
});
});
View:
<?php echo form_open('article/processArticle',array('id'=>'article_form'));?>
<?php echo validation_errors(); ?>
<div id="sidebar_options">
<div class="sidebar_title">Article Settings</div>
<ul>
<li>
<label>Tags</label><br />
<input type="text" name="article_tag" size="15" value="<?php echo set_value('article_tag');?>" id="article_tag"/>
</li>
<li>
<label>Category</label><br />
<select name="article_category" id="article_category">
<option value="1">Test Category 1</option>
<option value="">Test Category 2</option>
<option value="">Test Category 3</option>
<option value="">Test Category 4</option>
</select>
</li>
<li>PDF version</li>
</ul>
</div>
<div id="option_panel">
<input type="text" name="article_title" size="30" placeholder="Title" value="<?php echo set_value('article_title');?>" id="article_title"/>
<input type="submit" value="Publish" name="publish" />
<input type="button" value="Preview" class="save"/>
<input type="button" value="Save" class="see"/>
</div>
<div id="write_panel" style="width:700px; margin-left:50px; width:800px;"></div>
<div id="write_area">
<textarea name="article_content" id="article_content" style="height:690px; width:800px;" ></textarea>
<input type="hidden" value="<?php echo $articleId;?>" name="article_id" id="articleId"/>
</div>
</div>
<?php echo form_close();?>
I really scratched my head on this.
Just got the answer. Forgot to add to put the last variable into the datastring in the ajax file.