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? :-)
Related
I have select2 field input. After using select2 its will showing new column and data from this input selected.
I have referenced like this link. So after I using select2, this value will show in a new column. But I don't know how to catch this data. I am using Laravel and this is my controller and view:
Controller
$collection = Alat::get(['nama_alat','no_inventaris','status_alat','id']);
foreach ($collection as $item) {
$inven[$item->id] = $item->no_inventaris.'-'.$item->nama_alat;
}
This is will shown in columns no_inventaris and nama_alat in the select2. But in the $collection, I have status_alat, this data is what I need to display in another column.
This is my view:
// This is form Select2
<div class="form-group">
<label>Pilih Inventaris</label>
<select class="form-control select2bs4" name="alat_id" id="alat_id" style="width: 100%;" aria-hidden="true" onchange="Show()">
<option value=""></option>
#foreach($inven as $id => $item )
<option value="{{ $id }}">{{ $item }} </option>
#endforeach
</select>
</div>
// This is form what i need to show another value
<div class="form-group" id="divid" style="display:none">
<label class="control-label" for="title">Kondisi Alat Sekarang:</label>
<input type="text" name="" class="form-control" id="value" data-error="Please enter title." readonly />
<div class="help-block with-errors"></div>
</div>
Here's my Javascript:
<script>
function Show()
{
var fieldValue = $('#alat_id').val();
if(fieldValue == "")
{
document.getElementById("divid").style.display = 'none';
}
else{
document.getElementById("divid").style.display = 'inline'
}
}
</script>
This data I need to catch in the controller $collection as status_alat. How can I catch this data after input the select2 and showing in the new column? This column is shown, but I don't know how to catch this data. Sorry for my bad English
The best solution should be using ajax, it is quite complicated to access a PHP collection variable inside a javascript. If it were me, I would create a function that fetch the selected select2 data by its id. This is my example code :
<script>
function select2Changed()
{
var alat_id = $('#alat_id').val();
if(fieldValue == ""){
document.getElementById("divid").style.display = 'none';
} else{
document.getElementById("divid").style.display = 'inline';
$.ajax({url: "[url]/get-alat-status/"+alat_id, success: function(result){
document.getElementById("value").value = result;
}});
}
}
</script>
Hi guys new to laravel here! i am using selected option drop down list The First Select contains the countries and the second one has the states, now When i try to store the in database i am not getting the proper selected state instead i am always getting the first state in the second select Option!! i am using query Builder.
This is How i am retrieving Countries and states
public function store(Request $request)
{
$country = DB::table("countries")->where("id",$request->daira);
$state = DB::table("states")->where("country_id",$request->daira);
$daira = $country->get()->first()->name;
$impact = $state->get()->first()->commune;
dd($impact);
}
Note: dd($impact); Should be retrieving the selected state, instead it's retrieving the first value on the Selection List
So my Question is How do i get it to retrieve The proper Selected state !? Hope my question is clear Thanks in Advance.
Updated:
In the First Select option I have Countries name and in the second option i have
states each country has maximum 3 states, let's say Country A has 3 States A1,A2 and A3 And i want to select State A2 from the select option Value and instead of getting A1 by default like my case in the Question
Updated: I Am using VueJs
This is The form code
<template>
<div class="modal-body">
<div class="form-group">
<select name="direction" class="form-control">
<option value="">Selctionner Direction</option>
<option value="ENERGIE">ENERGIE</option>
<option value="HYDRAULIQUE">HYDRAULIQUE</option>
<option value="ENVIRONNEMENT"> ENVIRONNEMENT</option>
<option value="AMENAGEMENT">AMENAGEMENT</option>
<option value="P.T.T">P.T.T</option>
<option value="TOURISME">TOURISME</option>
<option value="TRANSPORT">TRANSPORT</option>
<option value="TRAVAUX PUBLICS">TRAVAUX PUBLICS</option>
<option value="EDUCATION">EDUCATION</option>
<option value="ENSEIGNEMENT SUPERIEUR">ENSEIGNEMENT SUPERIEUR</option>
<option value="URBANISME">URBANISME</option>
<option value="FORMATION PROFESSIONNELLE">FORMATION PROFESSIONNELLE</option>
<option value="SANTE">SANTE</option>
<option value="JEUNESSE-SPORTS CULTURE">JEUNESSE-SPORTS CULTURE</option>
<option value="PROTECTION SOCIALE">PROTECTION SOCIALE</option>
<option value="INFRASTRUCTURES ADMINISTRATIVES">INFRASTRUCTURES ADMINISTRATIVES</option>
<option value="HABITAT">HABITAT</option>
<option value="COMMERCE">COMMERCE</option>
<option value="LOGEMENT">LOGEMENT</option>
<option value="LOCAUX A USAGE PROFESSIONNELE">LOCAUX A USAGE PROFESSIONNELE</option>
<option value="FORET">FORET</option>
</select>
</div>
<div class="form-group">
<label>Selctionner Daira:</label>
<select name="daira" class='form-control' v-model='country' #change='getStates()'>
<option value='0' >Select Country</option>
<option v-for='data in countries' :value='data.id'>{{ data.name }}</option>
</select>
</div>
<div class="form-group">
<label>Selctionner Commune:</label>
<select name="impact" class='form-control' v-model='state'>
<option value='0' >Select State</option>
<option v-for='data in states' :value='data.id'>{{ data.commune }}</option>
</select>
</div>
<div class="form-group">
<label >Intitule :</label>
<input type="text" class="form-control" name="intitule" required>
</div>
</div>
</template>
And this is My Script
<script>
export default {
mounted() {
console.log('Component mounted.')
},
data(){
return {
country: 0,
countries: [],
state: 0,
states: []
}
},
methods:{
getCountries: function(){
axios.get('/api/getCountries')
.then(function (response) {
this.countries = response.data;
}.bind(this));
},
getStates: function() {
axios.get('/api/getStates',{
params: {
country_id: this.country
}
}).then(function(response){
this.states = response.data;
}.bind(this));
}
},
created: function(){
this.getCountries()
}
}
</script>
can you post the result of dd($request->all()) ?
assuming your select name is daira and impact, you should be able to get the posted value with this:
public function store(Request $request)
{
$daira = $request->daira;
$impact = $request->impact;
}
I understand your issue first state returns because of when you passed country id it returns all the state related this country.
So that you need to pass state Id from state drop-down.
<select name="impact">
<option value="id">{{ STATE NAME }} </option>
</select>
And then you need to pass that state id in controller.
$state = DB::table("states")->where("id",$request->impact);
Hope you understand your queries
I assume $request->daira is country ID
public function store(Request $request)
{
//here you selected a country with provided country ID
//this returns Query Builder object
$country = DB::table("countries")->where("id",$request->daira);
//here you are returning all the states where the country_id is
//the provided country ID
//Note that this returns all the states (Query Builder object)
$state = DB::table("states")->where("country_id",$request->daira);
//You return `Illuminate\Support\Collection` then you got the first item
//from collection
$daira = $country->get()->first()->name;
//You returned all the states `Illuminate\Support\Collection`
//and you picked the first state from the collection,
//which is likely the first item in your
//form select field options
$impact = $state->get()->first()->commune;
dd($impact);
}
Because you didn't specify state_id, you will always get lists of all the states under the given country.
I assume table relationship is Country -> hasMany -> State
You need to add state_id as constraint, so only one state is picked
$state_id = $request->state
I assume you have state in your form
$state = DB::table("states")
->where("country_id",$request->daira)
->where('id', $state_id)
->first();
$impact = $state->commune
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);
}
I am stuck for 2 days, do you know how to show old data of select element in Laravel?
<select name="sexe" id="sexe" class="form-control">
<option value="">Choice</option>
<option>Women</option>
<option>Man</option>
</select>
I have tried this but without success:
<select class="form-control" name="sexe">
<option value="male" #if (old('sexe') == 'male') selected="selected" #endif>male</option>
<option value="female" #if (old('sexe') == 'female') selected="selected" #endif>female</option>
</select>
My Controller
public function edit($id)
{
//
$candidats = Candidat::find($id);
$permis = Permis::all();
return view('admin.candidats.edit', compact('candidats', 'permis'));
}
public function update(Request $request, $id)
{
$request->validate([
'sexe' => 'required|string',
'fk_permis' => 'required'
]);
$candidats = Candidat::find($id);
$candidats->sexe = $request->get('sexe');
$candidats->fk_permis = $request->get('fk_permis');
$candidats->save();
return redirect()->route('candidats.index')
->with('success', 'mise à jour effectuée');
}
Edit:
1) index.blade.php
2) edit.blade.php
In your update function put withInput():
return redirect()->route('candidats.index')
->with('success', 'mise à jour effectuée')->withInput();
In your select you can do this:
<select class="form-control" name="sexe">
<option value="male" #if (old('sexe') == 'male') selected="selected" #elseif($candidats->sexe == 'male') selected="selected"
#endif>male</option>
<option value="female" #if (old('sexe') == 'female') selected="selected" #elseif($candidats->sexe == 'female') selected="selected"
#endif>female</option>
</select>
I loaded the selected option from your model here
#elseif($candidats->sexe == 'male') selected="selected"
So, if you saved 'male' in your sexe attribute this option will be selected.
Take a look here for more info:
If the old data was stored as a model, which I assume it was since this is a Laravel question and not a javascript question, you can use form-model binding to easily load the old data the next time you go to the page.
So, when you open your form, bind the model:
{{ Form::model($yourModel, array('route' => array('yourModel.update', $yourModel->id))) }}
And then within the select method, laravel (collective) can automatically make the old data the selected value. Using the Laravel helper it might look like this:
{!! Form::select('sexe', $listOfYourNameAndIdForYourSelectItem, null, ['class'=>'form-control', 'id'=>'sexe']) !!}
By making the third argument null, as above, Laravel will make the model's old data the selected element.
Check the docs on the Laravel forms package for more info.
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();