How to avoid checking every time, if variable is set in blade template? Laravel 8 - laravel

I know about something like this:
{{ old('contents', $page->contents ?? null) }}
But what about more complicated cases, like checkboxes and selects?
<select id="custom_template" name="custom_template">
{{--default empty option, if nothing is selected yet--}}
<option label=" " {{ ($page->custom_template == null)? "selected" : "" }}></option>
#foreach($templates as $template)
<option value="{{ $template->id }}" {{ ($page->custom_template == $template->id)? "selected" : "" }}>{{ $template->name }}</option>
#endforeach
</select>
I need to avoid checking #isset($page) and also check old input. How can I do it in that select input?

You can use Type hinting to avoid the 'isset'.
Your controller
/**
* Show the form for creating a new resource.
*
* #param \App\Entities\Page $page
*
* #return \Illuminate\View\View
*/
public function create(\App\Entities\Page $page)
{
return view('page', compact('page'));
}
With using 'Type hinting' in create function will create empty collection of Page Entities. No need to check isset condition in view, $page->custom_template will give you null now, instead of error.
And your view, to check the old input.
<select id="custom_template" name="custom_template">
<option value="">Select Option</option>
#foreach($templates as $template)
<option value="{{ $template->id }}" {{ (old('custom_template', $page->custom_template) == $template->id) ? 'selected' : '' }}>{{ $template->name }}</option>
#endforeach
</select>
By using the above condition you can use same view for create and edit function.
Hope, this will solve your problem.

I'm not sure I quite understand what you're trying to do but this approach may help; provided you're using JQuery:
<script>
$(document).ready(function() {
#if($page->custom_template)
$('option[value="{{ $page->custom_template}}"]').prop("selected", true);
#endif
});
</script>

Related

Laravel Livewire: Input select, default option selected

I am trying to fetch country codes from my database and trying to get the default value via IP address. It works just as I want for a second but then I don't know what happens but it refreshes itself and scrolls to the first option instead of the selected option.
Livewire Controller Component
use App\Models\CountryCodes;
use Livewire\Component;
use Location;
class TestCountry extends Component
{
public $iso;
public $country_codes;
public $country_code;
public function mount()
{
$iso=Location::get('ip');
$this->iso=$iso->countryCode;
}
public function render()
{
return view('livewire.test-country',[
$this->country_codes = CountryCodes::select('nicename','iso','phonecode')->get()->toArray()
]);
}
}
Livewire Blade Component
<select wire:model.lazy="country_code" name="country_code" id="country_code" class="form-control" required>
#foreach($country_codes as $country_code)
<option value="{!! $country_code['iso'] !!}"
wire:key="{{$country_code['iso']}}"
{{ $country_code['iso'] == $iso ? 'selected' : ''}}>
{!! $country_code['iso'] !!} +{!! $country_code['phonecode'] !!}
</option>
#endforeach
</select>
This code does select my default option but it changes and moves to the first option automatically. Am I doing something wrong here?
I believe what is happening is, $iso is set correctly, but the select is bound to the $country_code property, not $iso, so briefly, the check you have works, but because $country_code doesn't have a value, the selected option is lost when the state is updated by Livewire.
TLDR: Livewire is checking whatever is in the wire:model attribute, so the class property must be set for it to work.
I would try something like this:
public function mount()
{
$iso = Location::get('ip');
$this->iso = $iso->countryCode;
// set $country_code to $iso
$this->country_code = $this->iso;
}
I believe Livewire will intelligently select the state, so I think the selected check can be removed:
<select wire:model.lazy="country_code" name="country_code" id="country_code" class="form-control" required>
#foreach($country_codes as $country_code)
<option
value="{!! $country_code['iso'] !!}"
wire:key="{{$country_code['iso']}}"
>
{!! $country_code['iso'] !!} +{!! $country_code['phonecode'] !!}
</option>
#endforeach
</select>
Also, any reason for using {!! !!} tags in the view rather than just {{ }}?

Laravel search-filter

I have a problem with passing the selected index to my controller via click.
If I manually change the index in the browser, it is working.
(http://localhost:3000/admin/users?user=&sortBy=5)
$sortOptions is the name of my 2d array in my controller.
sortDisplay is a field in my 2d array in my controller.
Am I missing something in my foreach loop?
<label for="sortBy">Sort by</label>
<select class="form-control" name="sortBy" id="sortBy">
#foreach($sortOptions as $index => $sortOptions)
<option value="{{$index}}" {{ (request()->sortBy == $index ? 'selected' : '') }}>
{{$sortOptions["sortDisplay"]}}
</option>
#endforeach
</select>
Use jQuery to submit form when value changed
So your page will refresh and you will get what you want
In the foreach loop, you are assigning the same variable name as the variable you are iterating. In your case, after the first loop, you re-instantiate the $sortOptions variable with the content of the first index of $sortOptions.
#foreach($sortOptions as $index => $sortOption) // <-- $sortOption, not $sortOption(s)
<option value="{{$index}}" {{ (request()->sortBy == $index ? 'selected' : '') }}>
{{ $sortOption["sortDisplay"] }}
</option>
#endforeach

Laravel 5 - Pre-populate a HTML select using database value and old

I am trying to use 'old' in a Laravel 5 app to pre-populate a select form on an edit route like this...
<select id="category" name="category" required>
<option value="">Select</option>
<option value="animal" #if (old('category') == "animal") {{ 'selected' }} #endif>Animal</option>
<option value="vegetable" #if (old('category') == "vegetable") {{ 'selected' }} #endif>Vegetable</option>
<option value="mineral" #if (old('category') == "mineral") {{ 'selected' }} #endif>Mineral</option>
</select>
This works well and keeps the selected option if a validation fails, but I am trying to make it work so that it pre-populates when the page first loads.
How do I determine if this is the first load of the edit page, or if it has reloaded after a validation failure? Or is there a better way to do this?
Lets imagine you have sent the category value as $category.
So in every <option> tag,
<option value="animal"
{{ old('category') == 'animal' ? ' selected' :
$category == 'anumal' ? ' selected' : '' }}>
Animal
</option>
This is what is going on there:
if there is an old value and its matching, select this,
else if the original value is matching select this,
else do nothing.
Use the second parameter of the old function with a default/initial value:
<option value="animal" #if (old('category', 'animal') == "animal") {{ 'selected' }} #endif>Animal</option>
The second parameter will be returned as the function result if an old value cannot be found in the flashed input.

How to show selected value from database in dropdown using Laravel?

I want to show selected value from database into dropdown list on page load.
My controller index function is :
public function index()
{
$country_data =DB::table('country')->select('country_id','country_name')->get();
$profile_data= DB::table('profiles')->select('*')->where('id',$user_id)->first();
return view('profile_update',compact('profile_data','country_data'));
}
Column name in database for height is :Height
My dropdown in profile_update.blade.php is
<select class="select4" name="country" id="country">
<option value="">Please Select</option>
#foreach($country_data as $country)
<option value="{{$country->country_id}}" {{$country_data->country == $country->country_id ? 'selected' : ''}}>{{$country->country_name}}</option>
#endforeach</select>
This is a example of how I do this:
<select class="js-states browser-default select2" name="shopping_id" required id="shopping_id">
<option value="option_select" disabled selected>Shoppings</option>
#foreach($shoppings as $shopping)
<option value="{{ $shopping->id }}" {{$company->shopping_id == $shopping->id ? 'selected' : ''}}>{{ $shopping->fantasyname}}</option>
#endforeach
</select>
In order to understand it fully you will need basics of laravel (MVC),
Let suppose, you have controller. In my case I made a separate table for drop down values.
My Approach --- Separate table for values of drop down, you can try different approach but my explanation was mainly focused on concept.
Note: PersonInfo is model, sampleType is model of my drop down values and don't forget to make a route for the controller.
ExampleController{
public funtion getValues($id){
/*
I am fetching information of a single row from the database by id and
then passing it to the view. The $id to the function came from the
request by your view/form.
I also fetched the values of drop down from the separate table
of database and passed it to the exampleView.
*/
$selectedValue=PersonInfo::findOrFail($id);
$sampleType=SampletypePicker::all(); //model for fetching all values of drop down
return view('exampleView',compact('selectedValue','sampleType));
}
}
So, in the above controller I fetched all values and passed it to the ExampleView. Now in your View file you have to work likewise.
exampleView.blade.php add the below code
<?php $options=$selectedValue->sample_type ?> //note take the value from the database which stored for the individual record and match it with the selected one.
<select class="form-control" name="test">
<option>Select Test Type</option>
#foreach ($sampleType as $value)
<option value="{{ $value->sample_type }}" {{ ( $value->sample_type == $options) ? 'selected' : '' }}>
{{ $value->sample_type }}
</option>
#endforeach
</select>
It is one of the best approach when you want to add dynamic values to the drop down. I mean if you want to add more values to the select tag options then this is the best approach.
Another Approach - take the idea
<?php $months = array("Jan", "Feb", "Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"); ?>
<?php $options=$patient_data->month ?>
#if($patient_data->month)
<select id="expiry_month" name="month" class="form-control-sm">
#foreach($months as $month)
<option value="{{$month}}" {{($month==$options)? 'selected':'' }}>{{$month}}</option>
#endforeach
</select>
#endif
<span class="select-icon"><i class="zmdi zmdi-chevron-down"></i></span>
</div>
OUTPUT of ABOVE CODE
#Sarita Sharma show the error(s). Maybe then anyone help you to resolve this problem. Show data in colections in controler - use dd e.g.
dd($country_data);
dd($profile_data);
Do you want to display the country in the view with the appropriate Height value from profile_data?
Ps. How to put the code, please use the formatting code - put the code in `` and use camelCase in value name (maintaining good PSR-1 practice) - it is easier to read code.
Well, simply if anyone still looking for this, here is the simple way to select items for dropdown from database to blade view
$users = Users::pluck('name', 'id');
$selectedID = 2;
return view('users.edit', compact('id', 'users'));
add this in the controller function before rendering the view
and in the blade view, simply use this variable as foreach loop as
<select name="user_id" class="form-control" id="exampleFormControlSelect1">
#foreach ($users as $key => $value)
<option value="{{ $key }}" {{ ($key == $selectedID) ? 'selected' : '' }}>
{{ $value }}
</option>
#endforeach
</select>
if you don't want to select all users from DB, you can use where condition before pluck condition as
$users = Users::where('status', 1)->pluck('name', 'id');
works with Laravel 8 and Laravel6

Exploding Value from Select Option Value

Now I'm working with Laravel 5.
I got value from select option like below:
select name="billing_provider" onChange="changeLanguage(this.value)"> #foreach($tests as $test)
option value="{{ $test->tax_id }},{{ $test->npi }}" name="billing_provider">
{{ $test->test_name }} </option>#endforeach </select>
Here I need to explode the option value and store it into another text field value.
How can I do that?
First, you have made a mistake building your HTML.
<select> has an attribute name which is going to be the key in the global arrays $_GET or $_POST.
However <option> doesn't have attribute name. You should remove that.
If you want to separate the value of billing_provider in your backend (php /w Laravel), do so.
In your method which handles the submission of the form:
$input = Input::get('billing_provider');
$billing_provider = explode(',', $input);
//Now $billing_provider[0] === $test->tax_id
//And $billing_provider[1] === $test->npi
Or if you want to perform this action before form submission and you're using jQuery, then you can do this:
https://jsfiddle.net/17fkpqbe/
JavaScript (/w jQuery):
$(document).ready(function() {
$('select').change(function() {
$('.inputs').html('');
var $explodedVal = $(this).val().split(',');
for(i = 0; i < $explodedVal.length; i++) {
$('.inputs').append('<input value="' + $explodedVal[i]+'">');
}
});
});
HTML:
<select>
<option></option>
<option value="123,555">Some Name 1</option>
<option value="123,444">Some Name 2</option>
<option value="123,333,555">Some Name 3</option>
</select>
<div class="inputs"></div>

Resources