CodeIgniter form validation radio button not working - codeigniter

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);
}

Related

Found 2 elements with non-unique id (#_ajax_nonce) and (#_wpnonce)

I am developing custom theme from scratch and creates a custom post type and getting this warning while editing custom post type. I also design custom Meta box with two input fields and using nonce in it. Any help removing these warning?
//Custom Metabox
function register_book_meta_box(){
add_meta_box('book_meta_box_id', 'Book Detail','design_book_meta_box','books','advanced','high');
}
add_action('add_meta_boxes','register_book_meta_box');
function design_book_meta_box($post){
wp_nonce_field(basename(__FILE__),'book_cpt_nonce')
?>
<div>
<label for="book-author">Author Name </label>
<input type="text" name="book-author" placeholder="Author Name" value="<?php echo get_post_meta( $post->ID, 'book-author-key', true );?>">
</div>
<div>
<label for="year">Published Year</label>
<input type="number" id="year" name="year" min="1455" max="2020" value="<?php echo get_post_meta( $post->ID, 'book-year-key', true );?>">
<span id="errorMsg" style="display:none;">Published Year Must be range from 1455 - 2020</span>
</div>
<?php
}
function save_book_meta_data($post_id)
{
if(!isset($_POST['book_cpt_nonce']) || !wp_verify_nonce($_POST['book_cpt_nonce'],basename(__FILE__))){
return $post_id;
}
if (array_key_exists('book-author', $_POST)) {
update_post_meta( $post_id,'book-author-key', $_POST['book-author']
);
}
if (array_key_exists('year', $_POST)) {
update_post_meta( $post_id,'book-year-key', $_POST['year']
);
}
}
add_action('save_post', 'save_book_meta_data');

Laravel - old() value of checkbox, in combination with the one loaded from the database

I have this checkbox code:
<div>
<input type="checkbox" id="allowfullscreen" name="allowfullscreen"
{{ $gallery->allowfullscreen == 1 ? 'checked' : '' }}>
</div>
This checks the checkbox based on the value taken from the database. Now, i would like to implement also the old data, in case of a failed submission.
For textboxes i do it like this:
<input id="galname"
type="text"
class="form-control #error('galname') is-invalid #enderror"
name="galname"
value="{{ old('galname') ?? $gallery->galname }}"
required autocomplete="galname" autofocus>
But it does not work this way for checkboxes since they need checked to be printed. The samples I found around here on SO only adress one of the two situations, but didnt find any that address both things for checkboxes.
How can this be done?
The second parameter you give the the old() function is used when the first value is null. So when you do old('name', "test") and no old value for 'name' is found, 'test' is used. So in your case, you could use:
<div>
<input type="checkbox" id="allowfullscreen" name="allowfullscreen"
{{ old('allowfullscreen', $gallery->allowfullscreen) == 1 ? 'checked' : '' }}>
</div>
This is ok even if you use all inputs in one blade template to use with create and update actions.
Will only work for POST request, obviously.
#if(old('published', (old('_token') ? false : ($slider->published ?? false)))) checked #endif
<div class="form-group">
<input class="form-check-input" type="checkbox" id="publish" name="published" value="1" #if(old('published', (old('_token') ? false : ($slider->published ?? false)))) checked #endif>
<label class="form-check-label" for="publish">{{ __('PubliƩ') }}</label>
#include('bo.modules.input-error', ['inputName'=>'published'])
</div>
Using this on request
/**
* Prepare the data for validation.
*
* #return void
*/
protected function prepareForValidation()
{
$this->merge([
'published' => $this->published ? true : false
]);
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'published' => 'required|boolean',
];
}

My model always give empty even I have data in database Laravel 5

UPDATE
I just found the problem here, it is typo at $instID = $request->insititution;
It should be $instID = $request->institution;
Thanks for all your helps..
UPDATE
I trying to insert to CRConfigDetail Model / table, but first I need to get my CRConfigID from CRConfig Model / Table with specific rules. So I can get the CRConfigID and put it to CRConfigDetail column.
But every time I trying to retrieve, it always give empty data even I already have data at my database. In other Controller I can retrieve data with similar rules.
Am I do something wrong with logic? Because I don't see any errors.
Here is my HTML / form:
<form action="doInsertSCC" method="POST" enctype="multipart/form-data" id="scheduleDetailForm">
{{csrf_field()}}
<div class="form-group">
<label for="institution">Institution</label>
<select name="institution" class="form-control" id="institution">
</select>
</div>
<div class="form-group">
<label for="acadCareer">Academic Career</label>
<select name="acadCareer" class="form-control" id="acadCareer">
</select>
</div>
<div class="form-group">
<label for="period">Period</label>
<select name="period" class="form-control" id="period">
</select>
</div>
<div class="form-group">
<label for="department">Department</label>
<select name="department" class="form-control" id="department">
</select>
</div>
<div class="form-group">
<label for="fos">Field of Study</label>
<select name="fos" class="form-control" id="fos">
</select>
</div>
<div class="form-group">
<label for="scc">Lecturer's ID - Name</label>
<select name="scc" class="form-control" id="scc">
</select>
</div>
<button type="submit" class="btn btn-default">Assign SCC</button>
<div id="search" class="btn btn-default">Search</div>
</form>
Here is my Route to access my Controller
Route::post('/doInsertSCC', "ScheduleController#insertSCC");
And here is my ScheduleController
public function insertSCC(Request $request){
$this->validate($request, [
'scc' => 'required'
]);
$instID = $request->insititution;
$acadID = $request->acadCareer;
$termID = $request->period;
$depID = $request->department;
$rule = ['institutionID' => $instID, 'acadCareerID' => $acadID, 'termID' => $termID, 'departmentID' => $depID];
$crConfig = CRConfig::where($rule)->first();
if( !empty($crConfig) ){
foreach ($crConfig as $cr) {
$crConfigID = $cr->CRConfigID;
}
$schedule = new CRConfigDetail;
$schedule->status = 'Pending';
$schedule->numRevision = 0;
$schedule->FOSID = $request->fos;
$schedule->SCC = $request->scc;
$schedule->CRConfigID = $crConfigID;
$schedule->save();
return redirect("AssignSCC")->with('status', 'Add SCC success!');
}else{
return redirect("AssignSCC")->with('status', 'Add schedule first!');
}
}
I already check my rules data are match with my CRConfig table's data (using console.log()
Everytime I submit this form, I will do the "else" and redirect with "Add schedule first!" message.
Actually, it does accept an array, but the array should be formatted as such..
$rule = [
['institutionID', '=', $instID],
['acadCareerID', '=', $acadID],
['termID', '=', $termID],
['departmentID', '=', $depID]
];
Source: https://laravel.com/docs/5.4/queries#where-clauses
use the below one
$crConfig = CRConfig::where('institutionID' , $instID)
->where('acadCareerID' , $acadID)
->where('termID', $termID)
->where('departmentID', $depID)
->first();
instead of
$rule = ['institutionID' => $instID, 'acadCareerID' => $acadID, 'termID' => $termID, 'departmentID' => $depID];
$crConfig = CRConfig::where($rule)->first();
You can check the query built at the backend by getting the query log, for this you have to enable the query log before the query gets built and get the query log after the query gets built both query log methods belongs to DB facade
\DB::enableQueryLog();
\DB::getQueryLog();

Trying to load checkbox results into iFrame in CodeIgniter

I am attempting to learn CodeIgniter. I want to send checkbox values from my view (index.php), via my controller (also called index.php confusingly, but that is what it is called at my company i work at, is this a good idea?), to an iFrame (which has a file called results.php) within my view. So far I get an array on view but only keys being shown - no values from checkboxes - like this:
Array ( [resultsAreaCode] => [resultsNumberType] => [resultsOrder] => [fred] => DAVE [sheep] => cow ) TEST
Here is my view with checkboxes and target iframe, note that one checkbox is populated by PHP/SQL:
<form id="numberOrderForm" action="index/localNumberResults" method="post" enctype='multipart/form-data'>
<div class="wrappers" id="multi-select1Wrapper">
<h2>Area Code</h2>
<select class="dropDownMenus" id="multi-select1" name="multi_select1[]" multiple="multiple">
<?php
//The query asking from our database
$areaCodeSQL = "SELECT ac.Number AS `AreaCode`, ac.Name AS `AreaName`
FROM `AreaCodes` ac"; //SQL query: From the table 'AreaCodes' select 'Number' and put into 'AreaCode', select Name and put into 'AreaName'
$areaCodeResults = $conn->query($areaCodeSQL); // put results of SQL query into this variable
if ($areaCodeResults->num_rows > 0) { // if num_rows(from $results) is greater than 0, then do this:
// output data of each row
foreach($areaCodeResults as $areaCodeResult) //for each item in $areCodeResults do this:
{
$areaNameAndCode = $areaCodeResult['AreaCode'] ." ". $areaCodeResult['AreaName']; //get AreaCode and AreaName from query result and concat them
$areaName = $areaCodeResult['AreaName']; // get AreaName
$areaCode = $areaCodeResult['AreaCode']; //get AreaCode
?><option class="menuoption1" name="menuAreaCode" value="<?php echo $areaCode ?>" ><?php echo $areaNameAndCode; ?></option><?php //Create this option element populated with query result variables
}
}
?>
</select>
</div>
<div class="wrappers" id="multi-select2Wrapper">
<h2>Number Type</h2>
<select class="dropDownMenus" id="multi-select2" name="multi_select2[]" multiple="multiple">
<option class="menuoption2" name="package" value="gold">Gold</option>
<option class="menuoption2" name="package" value="silver">Silver</option>
<option class="menuoption2" name="package" value="bronze">Bronze</option>
</select>
</div>
<div class="wrappers" id="multi-select3Wrapper">
<h2>Order</h2>
<select class="dropDownMenus" id="multi-select3" name="multi_select3[]" >
<option class="menuoption3" name="order" value="sequential">Sequential</option>
<option class="menuoption3" name="order" value="random">Random</option>
</select>
</div>
<input type="submit" value="Submit">
</form>
<div id="resultsTableWrapper">
<iframe id="resultsTable" src="http://my-company.com/localNumberResults" width="100%"></iframe>
</div>
This is within my controller (this I have been told by my tutor is correct though):
class Index extends CI_Controller { // this is my controller!
public function localNumberResults()
{
$data['formdata']= array(
'resultsAreaCode' => $this->input->post("menuAreaCode"),
'resultsNumberType' => $this->input->post("package"),
'resultsOrder' => $this->input->post("order"),
'fred' => 'DAVE',
'sheep' => 'cow'
);
$data['contentlocation'] = 'system/results';
$this->load->view('system/template', $data);
}
}
Can anyone point me in the right direction where i am going wrong? :-)

Weird behaviour of CI after a redirect()

I have a strange bug during the password recovery process.
When a user loses his pwd, the app send an email with a token inside the recovery link ( http://localhost/reset-password/f38fd00aa975b28c70f54d948d20de40 for exemple ) This token is an unique key inside the user table.
In the routes.php, i have :
$route['reset-password/(:any)'] = "/user/reset_password_form/$1";// new password form
$route['reset-password'] = "/register/reset_password"; //simple email form
then, reset_password_form generates a form with the token as hidden input :
public function reset_password_form($hash = NULL) { //create form to change password, with user validation hash inside
$user_id = $this->user_model->get_id_by_confirmation_code(strip_tags($hash));
if (isset($user_id)) {
$this->data['validation_code'] = $hash;
$this->data['title'] = $this->lang->line('user_title_password_edit', FALSE);
$this->template->load('default', 'register/reset_password_form', $this->data);
}
else{
$this->session->set_flashdata('error', $this->lang->line('user_error_reset_password', FALSE));
redirect('reset-password');
}
the view:
<?php $attributes = array('class' => '');
echo form_open('user/edit_password', $attributes) ?>
<input type="hidden" id="validate" name="validate" value="<?=$validation_code?>">
<div class="form-group">
<input type="password" id="password" name="password" placeholder="Password" class="form-control" value="<?php echo set_value('password'); ?>">
</div>
<div class="form-group">
<input type="password" id="password_confirm" name="password_confirm" placeholder="Password confirmation" class="form-control">
</div>
<button type="submit" name="submit" class="btn btn-success">Change password</button>
</form>
Finally, the user/edit_password function changes the user password with a new one.
public function edit_password() { //get new password and change it
$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[6]');
$this->form_validation->set_rules('password_confirm', 'Confirm Password', 'trim|required|matches[password]');
$this->form_validation->set_rules('validate', 'Validate', 'trim|alpha_numeric|required');
if ($this->form_validation->run() === false) {
//STRANGE BUG
$URL = '/reset-password/'.$this->input->post('validate');
$this->session->set_flashdata('error', validation_errors());
redirect($URL);
}
else {
//change pssword
}
}
The bug happen when the form validation fail : i'm suposed to be redirected to the previous form ( /reset-password/hash) with a flashdata error message, but the error message dont display.
Much more weird : even if i'm on the right form ( but without error message) if i decides to click on another menu item (for exemple /home) , it immediately displays the /reset-password form ( /register/reset_password in the routes) with the error message i was supposed to get previously.
As if the full php instruction was kept in stamp and launched after whatever action.
PS : as edit_password() and reset_password_form() are in the same controller, i could have used $this->reset_password_form($hash) instead of redirect() but it has exactly the same effect !
ps2: here is the register/reset_password:
public function reset_password() {
//display forgotten password form page
$this->data['title'] = 'Forgotten password';
$this->template->load('default', 'register/reset_password', $this->data);
}
you recovery link http://localhost/reset-password/f38fd00aa975b28c70f54d948d20de40 is not finding controller. CI is looking for your token number as controller

Resources