Keep the correct Selected option value in the edit form - laravel-8

I have an edit form as follows
<select name="department_id" id="department" class="form-control">
<option value="" selected disabled>{{ __('Select one') }}</option>
#foreach($departments as $key => $department)
<option value="{{ $department['id'] }}" {{ $department['department'] == $department['department'] ? 'selected' : '' }}>{{ $department['department'] }}</option>
#endforeach
</select>
User Model
public function department()
{
return $this->belongsTo(Department::class);
}
Department Model
public function employees()
{
return $this->hasMany(User::class);
}
Edit Methods
public function edit($id) {
$employee = User::find($id)->toArray();
$designations = Designation::where('deletion_status', 0)
->where('publication_status', 1)
->orderBy('designation', 'ASC')
->select('id', 'designation')
->get()
->toArray();
$departments = Department::where('deletion_status', 0)
->where('publication_status', 1)
->orderBy('department', 'ASC')
->select('id', 'department')
->get()
->toArray();
return view('pdd.employee.edit', compact('employee','designations','departments'));
}
My problem I could not get the selected value shown. Could anyone help

Solved:
User has one department
Department has many Users
Users in this case are employees
<select name="department_id" id="department" class="form-control">
<option value="" selected disabled>{{ __('Select one') }}</option>
#foreach($departments as $department)
<option value="{{ $department['id'] }}" {{ $department['id'] == $employee['department_id'] ? 'selected' : '' }}>{{ $department['department'] }}</option>
#endforeach
</select>

Related

Laravel - capture all input names starting with category_id at controller?

In my view I have several category_id inputs.
<select id="category_select1" class="form-control" name="category_id1">
#foreach($category as $c)
<option value="{{$c->id}}">{{$c->name}}</option>
#endforeach
</select>
<select id="category_select2" class="form-control" name="category_id2">
#foreach($category2 as $c)
<option value="{{$c->id}}">{{$c->name}}</option>
#endforeach
</select>
There might be more selectboxes like this so I want to get all of them no mater how many selectboxes there. All the selectbox names will be like category_id1, category_id2.. etc.
$request->input('category_id.*');
But this returns null. What am I doing wrong?
You should use arrays:
#foreach($categories as $i => $category)
<select id="category_select{{$i}}" class="form-control" name="category_id[]">
#foreach($category as $c)
<option value="{{$c->id}}">{{$c->name}}</option>
#endforeach
</select>
#endforeach
and in the controller simply use:
$categories = $request->input('category_id');
foreach($categories as $category_id) {
// ...
}
$request->input('category_id') will be an array of ids
Your solution (different named inputs) is not much reliable.
In any case if you want to use that,
you can use the collections to filter the request inputs by the name to get the categories' ids
Eg.
use Illuminate\Support\Str;
...
$categories = collect($request->all())->filter(function($value, $key) {
return Str::startsWith($key, 'category_id');
})->toArray();

Laravel/Livewire dynamic dropdown not sending the selected value

Using Laravel 8 + Livewire:
I was following this tutorial of creating a dynamic dropdown: https://www.itsolutionstuff.com/post/laravel-livewire-dependant-dropdown-exampleexample.html
I have this dropdown component:
public $suppliers;
public $beans;
public $selectedSupplier = NULL;
public function mount()
{
$this->suppliers = Supplier::whereHas('greenBeans')->get();
$this->beans = collect();
}
public function render()
{
return view('livewire.admin.supplier-beans-dropdown')->layout('layouts.admin.livewire');
}
public function updatedSelectedSupplier($supplier)
{
if (!is_null($supplier)) {
$this->selectedSupplier = Supplier::find($supplier);
$this->beans = $this->selectedSupplier->greenBeans;
}
}
The component's blade:
<div>
<div class="form-group">
<label for="supplier" class="col-md-4 form-label">Supplier</label>
<select wire:model.lazy="selectedSupplier" class="form-control">
<option value="" selected>Select Supplier</option>
#foreach($suppliers as $supplier)
<option value="{{ $supplier->id }}">{{ $supplier->name }}</option>
#endforeach
</select>
</div>
#if (!is_null($selectedSupplier))
<div class="form-group">
<label for="bean" class="form-label">Green Bean</label>
<select class="form-control" name="bean" wire:model.lazy="selectedBean">
<option value="" selected>Select Green Bean...</option>
#foreach($beans as $bean)
<option value="{{ $bean->id }}">{{ $bean->name }}</option>
#endforeach
</select>
</div>
#endif
I have an other component that needs to call this dropdown. So in this parent component I have this var: $selectedSupplier and in the view I call the dropdown component:
#livewire('admin.supplier-beans-dropdown')
When I select a supplier and submit the form, the selectedSupplier is null.
So how do I use this dropdown in different components?
How do I send the selected value to the parent component?
check this first I think you have some errors here. you have:
public function updatedSelectedSupplier($supplier)
{
if (!is_null($supplier)) {
$this->supplier = Supplier::find(supplier); --> typo error here???
$this->beans = $supplier->greenBeans; --> $supplier parameter is an ID???
}
}
and I think it should be:
if (!is_null($supplier)) {
$this->supplier = Supplier::find($supplier);
$this->beans = $this->supplier->greenBeans;
}

How to display multi dimensional array into the multiple dropdown menu?

I am working in multiple dropdown menu. I have created an array from php and it looks like this:
https://api.myjson.com/bins/1emzic
Now from this json I want to display 4 dropdown menu.
In the first drop down I need to display
"FS A", "FS MT" and "FS OTHER"
Based on the first selection I need to display its related data in second third and fourth and so on as I add in my data.
This is what I need to bind
<select [(ngModel)]="first" id="first">
<option value="" disabled selected>select a category</option>
<option *ngFor="let item of first_list" [value]="item.category">{{item.category}}</option>
</select>
<br>
<select [(ngModel)]="second" id="second">
<option value="" disabled selected>select a category</option>
<option *ngFor="let item of first_list" [value]="item.category">{{item.category}}</option>
</select>
<br>
<select [(ngModel)]="third" id="third">
<option value="" disabled selected>select a category</option>
<option *ngFor="let item of first_list" [value]="item.category">{{item.category}}</option>
</select>
<br>
<select [(ngModel)]="four" id="four">
<option value="" disabled selected>select a category</option>
<option *ngFor="let item of first_list" [value]="item.category">{{item.category}}</option>
</select>
Here is my json data
{"FS A":{"BKK":{"BKK PULL":{"BKK SR1":[]},"BKK PUSH":{"BKK BCDE1":[],"BKK BAKE SE1":[]}},"RSM2":{"CHIANGMAI":{"CMI WS SE1":[],"CMI WS SE2":[]},"NORTH":{"NO1 SE1":[],"NO2 SEPLUS1":[],"NO3 SE1":[]},"ASM HOTEL BKK":{"BKK HO 5STARS1":[],"BKK HO SR1":[],"BKK HO SR2":[],"BKK HO SR3":[]}}},"FS MT":{"FSR1":{"FSA1":{"FS MAKRO":[]}},"FSR2":{"FSA2":{"FS FOODLAND":[],"FS GAS STATION":[],"FS VILLA MARKET JP":[],"SIAM FOODSERVICE":[]}},"FS LOCAL EXP":{"FS LOCAL EXP BKK":{"FS LOCAL EXP BKK":[]},"FS LOCAL EXP CD":{"FS LOCAL EXP CD":[]},"FS LOCAL EXP MM":{"FS LOCAL EXP MM":[]}}},"FS OTHER":{"FS OTHER":{"FS OTHER":{"FS OTHER":[]}}}}
Can anybody help me in this?
Here I am working:
https://stackblitz.com/edit/angular-dsylxi
You need to define the dependency on each other and based on that you can fill the models and its options. I will go for generic solution which can be applied with one function and works for all the drop-downs.
This are the model variables you need
wholeList:any = [];
first:any = [];
second:any = [];
third:any = [];
four:any = [];
firstModel = ''
secondModel = ''
thirdModel = ''
fourModel = ''
Then first you fill the first dropdown
this.testService.get_data().subscribe(
res => {
this.wholeList = res;
this.first = Object.keys(this.wholeList).map(a=> a);
console.log("res", this.first);
},
err => {
console.log(err);
}
)
Then in the view you need to fire a dependency which should look like this, note that I am defining dependency ChangeDropdown(this.wholeList[firstModel],'second')"
<select [(ngModel)]="firstModel" id="first" (ngModelChange)="ChangeDropdown(this.wholeList[firstModel],'second')">
<option value="" disabled selected>select a category</option>
<option *ngFor="let item of first" [value]="item">{{item}}</option>
</select>
<br>
<select [(ngModel)]="secondModel" id="second" (ngModelChange)="ChangeDropdown(this.wholeList[firstModel][secondModel],'third')">
<option value="" disabled selected>select a category</option>
<option *ngFor="let item of second" [value]="item">{{item}}</option>
</select>
<br>
<select [(ngModel)]="thirdModel" id="third" (ngModelChange)="ChangeDropdown(this.wholeList[firstModel][secondModel][thirdModel],'four')">
<option value="" disabled selected>select a category</option>
<option *ngFor="let item of third" [value]="item">{{item}}</option>
</select>
<br>
<select [(ngModel)]="fourModel" id="four">
<option value="" disabled selected>select a category</option>
<option *ngFor="let item of four" [value]="item">{{item}}</option>
</select>
and finally one common function which will update the models
ChangeDropdown = (value,dropdownName) =>{
this[dropdownName] = Object.keys(value).map(a=>{
return a;
})
}
Demo

How to handle Angular 5 select binding to a null value

I have a reactive form with a select
<select [(ngModel)]="user.positionId" name="positionId" class="custom-select form-control form-control-sm" required
formControlName="positionId"
[ngClass]="{
'is-invalid': positionId.invalid && (positionId.dirty || positionId.touched),
'is-valid': positionId.valid && (positionId.dirty || positionId.touched)
}">
<option value="">--Select--</option>
<option *ngFor="let position of user.positionSelectList" value="{{position.value}}">
{{position.text}}
</option>
</select>
It gets passed positionId which is a nullable number
export class User{
id: string;
userName: string;
positionId?: number;
}
The above works when I pass a number value as positionId.
However when it gets passed a null value then the default option of "--Select--" is not selected but an additional blank option appears above it.
What I have tried.
<option value=null>--Select--</option>
and
<option value=udefined>--Select--</option>
but this gives the same result of "--Select--" not selected
I do not wish to set hardcoded number values a fixed number e.g. -1 as I need the required validation to kick in which requires a blank value if not selected.
Have you tried using ngValue?
<select [(ngModel)]="user.positionId" name="positionId" class="custom-select form-control form-control-sm" required
formControlName="positionId"
[ngClass]="{
'is-invalid': positionId.invalid && (positionId.dirty || positionId.touched),
'is-valid': positionId.valid && (positionId.dirty || positionId.touched)
}">
<option [ngValue]="null">--Select--</option>
<option *ngFor="let position of user.positionSelectList" value="{{position.value}}">
{{position.text}}
</option>
</select>

Laravel 5 Same value for each input

Hello and here is my problem.
I have a hidden field on my form for registering candidates that supplies a purchase_order_number to a candidate; this is generated using $purchase_order_number = Str::quickRandom(7); in the create view.
I will hopefully use this to group candidates later on.
As more than one candidate can be registered at once, I would like the value of this hidden field to be input for each candidate. I have tried several things but with no success.
Here is the controller for my create view:
public function centreQualification($id)
{
$centre = Centre::with('sites')->find($id);
$purchase_order_number = Str::quickRandom(7);
return view('vault.create', compact('centre','purchase_order_number'));
}
And here is the view itself:
#extends('app')
#section('content')
<h1>Register New Candidates</h1>
<hr/>
{!! Form::open(['url' => 'candidates', 'name' => 'candidate_registration_form', 'id' => 'candidate_registration_form'] ) !!}
{!! Form::label('qualification_id','Qualification:') !!}
<select name="qualification_id" class="form-control">
#foreach($centre->qualification as $qualification)
<option value="{{ $qualification->id }}">{{ $qualification->title }}</option>
#endforeach
</select>
<input type="text" name="purchase_order_number" id="purchase_order_number" value="{{ $purchase_order_number }}" />
<hr/>
#include ('errors.list')
#include ('vault.form')
{!! Form::close() !!}
#stop
Now when I store (create) a new candidate I have this controller function:
public function store(CandidateRequest $request)
{
$candidateInput = Input::get('candidates');
foreach ($candidateInput as $candidate)
{
$candidate = Candidate::create($candidate);
}
return redirect('candidates');
}
Is there any way to attach this $purchase_order_number to each candidate?
<input type="hidden"
name="purchase_order_number"
id="purchase_order_number"
value="{{ $purchase_order_number }}" />
This creates a hidden field with the purchase_order_number.
In your store() method, get it using
$request->input('purchase_order_number');