I want to check either the countries exist in countries and the checkbox will be displayed. The values is directly from the database. I can't set the value at the input since it is array/multiple values. So, I want to check every array so that it will be a checkbox.
Controller :
public function edit($id)
{
$region = Region::find($id);
$countries = Country::all();
$country_region = DB::table('regions')
->select('countries.id', 'countries.name')
->join('country_region', 'regions.id', '=', 'country_region.region_id')
->join('countries', 'country_region.country_id', '=', 'countries.id')
->where('regions.id', '=', $id)
->get();
$items = array(
'region' => $region,
'countries' => $countries,
'country_region' => $country_region,
);
return view('admin.region.edit')->with($items);
}
blade
<div class="form-group">
<label>Choose Country</label>
<select id="test" type="checkbox" name="country_id[]">
#foreach ($countries as $item)
<option value="{{$item->id}}" selected #if (in_array($item->id, array_keys($country_region))) checked="checked"
#endif>{{$item->name}}
</option>
#endforeach
</select>
</div>
As you can see, I put php statement inside the blade to check either $country_region is exist in the countries or not. I got errors that related to the array such below :
array_keys() expects parameter 1 to be array, object given
Database :
Country Region Table :
Region Table :
Country Table :
Use pluck instead of select in the query.
$country_region = DB::table('regions')
->join('country_region', 'regions.id', '=', 'country_region.region_id')
->join('countries', 'country_region.country_id', '=', 'countries.id')
->where('regions.id', '=', $id)
->get()
->pluck('countries.name', 'countries.id');
I don't think you need array function there like in_array since you are already looping each country, simple if should work, also please show the content of tables you are trying to compare.
<div class="form-group">
<label>Choose Country</label>
<select id="test" type="checkbox" name="country_id[]">
#foreach ($countries as $item)
<option value="{{$item->id}}" selected #if ($item->id == $country_region.country.id) checked="checked"
#endif>{{$item->name}}
</option>
#endforeach
</select>
</div>
$country_region is not an array in your controller. It's an Eloquent collection. To change it to array you simply use toArray() on it.
In your controller, replace this:
$items = array(
'region' => $region,
'countries' => $countries,
'country_region' => $country_region,
);
with this:
$items = array(
'region' => $region,
'countries' => $countries,
'country_region' => $country_region->toArray(),
);
Use pluck to get all country's id in an array
$country_region = DB::table('regions')
->join('country_region', 'regions.id', '=', 'country_region.region_id')
->join('countries', 'country_region.country_id', '=', 'countries.id')
->where('regions.id', '=', $id)
->pluck('country_region.id')
->toArray();
Then don't use array_keys() anymore. Modify your HTML like this
<option value="{{$item->id}}" selected #if (in_array($item->id, $country_region)) checked="checked"
#endif>{{$item->name}}
</option>
make sure that $country_region is an array
Related
A select element with a pre-selected value does not render correctly, if I do not add wire:model to the element, it works well and shows the selected value in the select element.
But I need to add wire:model to save user-updated data
<div class="m-widget4">
#foreach ($this->result as $data)
<div>{{$data->id}}</div>
<select wire:model="list_session_picker.{{ $data->id }}" wire:key="{{ $data->id }}">
<option value="" disabled hidden>Select Session</option>
#foreach ($sessionData as $session)
<option value="{{ $session->id }}">{{ $data->user_session_id == $session->id ? 'selected' : '' }} {{ $session->session }}</option>
#endforeach
</select>
#endforeach
</div>
Componenet.php
public $result = [], $list_session_picker = [];
public $search_picker;
public function render()
{
$data['sessionData'] = Session::all('id', 'session');
$data['sectionData'] = Section::all('id', 'section');
return view('livewire.promote', $data);
}
public function search()
{
$search = ScCompany::query();
if (!empty($this->search_picker)) {
$search->where('session_id', $this->search_picker);
return
$this->result = $search
->whereNull('date_of_enter')
->with(['session:id,session', 'section:id,name'])
->get();
}
}
It works if I remove wire:model, so how could I show the selected value while using wire:model or is there any other way ?
Note** here i set wire:model="list_session_picker.{{ $data->id }}" so the list comes from for each loop can't update each other (on changing the option of one select will not uodate another select element in the list) .
I found this and this solutions, but how to apply them in my case, not much clear to me
You should set the selected element in the livewire component and not in the view. The view will reflect the state of the component thanks to the wire model.
At present you have conflicting views of which element should be selected and they will always be at odds with each other.
Just wire model. If you have an existing item selected, then set it state at the component.
I am using Selectize.js to create a tagging like experience, for adding users to jobs, using the current users of the system.
In my view
Following the documentation, I have a select box with the multiple attribute which I populate with the users on the system. I have also declared that this input is an array by adding square braces.
<select name="job_administrator[]" multiple id="selectize" class="form-control{{ $errors->has('job_administrator') ? ' is-invalid' : '' }}">
<option value="">Select a user </option>
#foreach($users as $user)
<option value="{{ $user->id }}">{{ $user->full_name }} - {{ $user->access_level }}</option>
#endforeach
</select>
Then, I initialize the plugin
$('#selectize').selectize({
placeholder: 'Select user',
plugins: ['remove_button'],
delimiter: ',',
persist: false,
})
In my Controller
/**
* Handle adding job administrators to jobs
*
* #param Array $data
* #return void
*/
public function addAdministrators(Array $data, int $id)
{
$vacancy = JobPost::where('id', $id)->first();
if(!empty($data['job_administrator'])){
$jobAdmins = $data['job_administrator'];
// Grab the IDs for the tags in the array
$admins = Admin::whereIn('id', $jobAdmins)->get()->pluck('id');
$vacancy->administrators()->sync($admins);
} else {
// If there were no tags, remove them from this model instance
$vacancy->administrators()->sync(array());
}
}
My question is: on the editing screen is it possible to prefill the selected items when using Selectize?
Yes you can, just add the selected attribute to the option. You can do something like this.
<option value="{{ $user->id }}" {{$selected->contains($user->id) ? 'selected' : ''}}>{{ $user->full_name }} - {{ $user->access_level }}</option>
The $selected is then a collection of ids.
I'm trying to store the text and value of the select box i have into my database. I can properly store the value by requesting it from the select box name itself but I'm having troubles with storing the text. I have 2 tables namely Item and ItemOrder.
Item Table
id | name
ItemOrder Table
id | item_id(fk from item table) | item_name
HTML
<select name="item" class="form-control select2" id ="item">
<option value="0" selected="true" disabled="true">Select Item</option>
#foreach($items as $key => $i)
<option value="{!!$key!!}">{!!$i!!}</option>
#endforeach
</select>
ItemController
public function itemList()
{
$items = Item::lists('name', 'id');
return view('employee.itemList', compact('items'));
}
public function storeItem(Request $request){
$info = array( 'item_name'=>$i,
'item_id'=>$request['item'],
DB::table('itemOrder')->insert($info);
return redirect()->route('dashboard');
}
Routes
Route::get('itemList', ['as' => 'itemList',
'uses' => 'ItemController#itemLIst']);
Route::post('storeItem', ['as' => 'storeItem',
'uses' => 'ItemController#storeItem']);
JS
$('select[name="item"]').on('change', function () {
var e = document.getElementById("item");
var itemText = e.options[e.selectedIndex].text;
console.log(itemText);
});
I can store the item_id value on my database cause i set item_name to nullable for the meantime. I tried to get the text through javascript and i can display it with console.log. Can anyone help me with storing the selected text as well? Or is there a way to get the text through javascript or jquery?
Did you tried to use
"<option value="
to hold each option's text? That way you can retrieve selected option text instead of some numeric code.
Follow my code.
$(document).ready(function ()
{
$('select[name="item"]').on('change', function ()
{
alert('Value change to ' +$(this).attr('value')+$(this).text());
});
});
I am not sure if this is the correct method, but I have created a form with some options to use as triggers for filtering the Wordpress loop. I do not have it set up to save any form information.
<form id="options" method="POST">
<p>Date Started</p>
<select name="date-started">
<option value="any-date">Any Date</option>
<option value="2015">2015</option>
<option value="2014">2014</option>
<option value="2013">2013</option>
<option value="2012">2012</option>
</select>
</form>
I want to use the selections to filter the Wordpress loop by meta data. I have a working snippet that does the filtering.
/* Filters the loop by custom meta data
https://codex.wordpress.org/Class_Reference/WP_Query#Parameters
*/
function comic_start_date( $query ) {
if ( $query->is_archive){
$query->query_vars["meta_key"] = 'date-started';
$query->query_vars["meta_value"] = '2015';
}
}
add_action( 'pre_get_posts', 'comic_start_date', 1 );
But, I do not know how to connect this to the option selected.
I have seen statements such as:
<?php if ($(("option[value='completed']")){//do something}?>
<?php if($ceg==1){//do something} ?>
<?php if($(this).value == 'volvo'){//do something} ?>
However, I have not been able to make these function together. Maybe I am using them in the wrong way.
As a bonus I would like the filter function vars to be taken from the option value and select name. I'm not sure if this is possible. I'll settle for a working if statement.
I found the answer
This is the working if statement:
This uses the name from the select tag and the value of the option you want to target.
if ($_POST["date-started"] === '2008') {}
And this is it shown around my filter:
function date_started_2008( $query ) {
if ( $query->is_archive){
$query->query_vars["meta_key"] = 'date_started';
$query->query_vars["meta_value"] = '2008';
}
}
if ($_POST["date-started"] === '2008') {
add_action( 'pre_get_posts', 'date_started_2008', 1 ); }
A dropdown select box is populated from a database and the selected option is matched against a variable $comp_cntry currently on the page:
<select name="country">
<option value="--" disabled>Please Select...</option>
<option value="--" disabled>- - - - -</option>
<?php
// Populate Country Dropdown
$country_query = mysql_query("SELECT country_name FROM ukipdata.ukip_countries
ORDER BY country_name ASC");
while ($cq = mysql_fetch_assoc($country_query)) {
$country = $cq['country_name'];
// Select Current Country
if ($country == $comp_cntry) {
?>
<option value"<?=$country?>" selected><?=$country?></option>
<?php
}
else {
?>
<option value"<?=$country?>"><?=$country?></option>
<?php
}
}
?>
</select>
Then later on a telephone prefix (dialling code) box is populated from the same database, matching the dialling code to the country:
<?php
// Get Dialling Codes
$telephone_query = mysql_query("SELECT country_name, dialling_code FROM ukipdata.ukip_countries
ORDER BY country_name ASC");
while ($tq = mysql_fetch_assoc($telephone_query)) {
$country = $tq['country_name'];
// Show Prefix
if ($country == $comp_cntry) {
$prefix = $tq['dialling_code'];
}
}
?>
<input type="text" name="telephone_prefix" value="+<?=$prefix?>" readonly>
How, using JavaScript, can I get the telephone prefix to automatically change on page when a new option is chosen from the country dropdown? I have no real knowledge of JavaScript at all, unfortunately, but assume I would need to somehow convert my PHP associated array in to JSON so that I can use it?
I know I haven't provided any JavaScript code to show that I've made a start on this part of the problem, but if someone could point me in the right direction that would be swell.
Disclaimer: please ignore my terrible use of the mysql_ extension
I would add a data attribute (here it might be called data-prefix) to the element, like
<option value='country' data-prefix='+44'/>
and get this when the onChange event is fired for the select. In jQuery you could do something like
$('[name="country"]').change(function(){
$('[name="telephone_prefix"]').val($(this).find(':selected').data('prefix'));
});
which would update the value accordingly.
I would say the best way of doing this would be joining the two PHP codes like this:
<select name="country">
<option value="--" disabled>Please Select...</option>
<option value="--" disabled>- - - - -</option>
<?php
// Populate Country Dropdown
$country_query = mysql_query("SELECT country_name, dialling_code FROM ukipdata.ukip_countries ORDER BY country_name ASC");
while ($cq = mysql_fetch_assoc($country_query)) {
$country = $cq['country_name'];
$prefix = $cq['dialling_code'];
// Select Current Country
echo "<option data-prefix='{$prefix}' value='{$country}' ";
if($country == $comp_cntry) echo "selected";
echo ">{$country}</option>";
}
?>
</select>
<input type="text" name="telephone_prefix" value="" readonly>
And this would return a list of the countries in a dropdown each with a data-prefix attribute of the appropriate prefix that they have.
We would then need to trigger jQuery on change and update the value, and this would look something like:
$("select[name=country]").on('change', function() {
var prefix = $("option:selected", this).attr('data-prefix');
$("input[name=telephone_prefix]").attr('value', prefix);
})
And this would have the following effect: http://jsfiddle.net/Tm75y/1/
I hope that's what you need.
Simply pass the prefix as an attribute of the select options:
<select id="country-select" name="country">
<option value="--" disabled>Please Select...</option>
<option value="--" disabled>- - - - -</option>
<?php
// Populate Country Dropdown
$country_query = mysql_query("SELECT country_name, dialling_code FROM ukipdata.ukip_countries
ORDER BY country_name ASC");
while ($cq = mysql_fetch_assoc($country_query)) {
$country = $cq['country_name'];
$prefix = $tq['dialling_code'];
// Select Current Country
if ($country == $comp_cntry) {
?>
<option value"<?=$country?>" prefix="<?=$prefix?>" selected><?=$country?></option>
<?php
}
else {
?>
<option value"<?=$country?>"><?=$country?></option>
<?php
}
}
?>
</select>
<input id="prefix-input" type="text" name="telephone_prefix" value="" readonly>
JAVASCRIPT
Then add a change handler to your select to get the prefix attribute of the selected option and set the text input:
$(function(){
$("#country-select").change(function(){
var prefix = $(this).find("option:selected").attr("prefix");
$("#prefix-input").val(prefix);
});
});
My suggestion would be to saving a javascript object which maps countries to phone codes, so when your country select has a change, you can trigger a change to the telephone prefix via javascript.
So let's assume you have a map (associative array) in javascript that is something like this:
$country_to_phone_prefix_map = array(
'country name A' => 'phone prefix A',
'country name B' => 'phone prefix B',
...
);
This could be built in your query while loop:
$country_to_phone_prefix_map = array();
while ($tq = mysql_fetch_assoc($telephone_query)) {
$country_to_phone_prefix_map[$tq['country_name']] = $tq['dialing_code'];
}
Then when rendering the page, inject this map into javascript
<script type="text/javascript">
var countryToPhonePrefixMap = <?php echo json_encode($country_to_phone_prefix_map); ?>;
</script>
Now, you build a change event listener on the country dropdown to change the value:
$('select[name="country"]').change(function() {
// get phone prefix from map
var selectedCountry = $(this).val();
var phonePrefix = countryToPhonePrefixMap[selectedCountry];
// change value of telephone prefix input
$('input[name="telephone_prefix"]').val(phonePrefix);
}