Hi can somebody please guide me how to implement inline table edit with select2 in laravel livewire?
I am having problem in my select as I can change the selected option in my select2 but the value I am getting upon submitting the form is the same as the original value.
Please see code below.
Table
#foreach ($purchaserequestitems as $index => $purchaserequestitem)
<tr >
<td><label class='label label-primary'>{{ $loop->iteration }}</label></td>
<td>
#if($editedPRItemsIndex !== $index)
<label>
{{ $purchaserequestitem['item']['name'] }}
</label>
<br/>
<small>
<label>{{ $purchaserequestitem['item']['code'] }}</label>
</small>
#else
<select wire:model.defer="purchaserequestitems.{{ $index }}.item_id" data-index="{{ $index }}" wire:change="getUomByItemId" class="form-control select2 item">
<option value="">-- Please Select -- </option>
#foreach ($items as $item)
<option value="{{ $item->id }}" >{{ $item->name }}</option>
#endforeach
</select>
#endif
</td>
<td>
#if ($editedPRItemsIndex !== $index)
{{ $purchaserequestitem['quantity'] }}
#else
<input type="text" wire:model.defer="purchaserequestitems.{{ $index }}.quantity" class="form-control">
#endif
</td>
<td>
#if ($editedPRItemsIndex !== $index)
{{ $purchaserequestitem['itemuomconversion']['unitmeasure']['code'] }}
#else
<select wire:model.defer="purchaserequestitems.{{ $index }}.item_uom_conversion_id" id="edituom" class="form-control select2">
<option value="">-- Please Select -- </option>
#foreach ($uom_options as $uom_option)
<option value="{{ $uom_option->id }}">{{ $uom_option->unitmeasure->code }}</option>
#endforeach
</select>
#endif
</td>
<td>
#if ($editedPRItemsIndex !== $index)
{{ $purchaserequestitem['comment'] }}
#else
<textarea wire:model.defer="purchaserequestitems.{{ $index }}.comment" class="form-control"></textarea>
#endif
</td>
<td>
<span class='pull-right'>
#if ($editedPRItemsIndex !== $index)
<button
class='btn btn-primary btn-sm rounded-0 py-0'
wire:click.prevent="editPRItem({{ $index }})">
Edit
</button>
<button
wire:click="deleteConfirm({{ $purchaserequestitem['id'] }})"
class='btn btn-danger btn-sm rounded-0 py-0'>
Delete
</button>
#else
<button wire:click.prevent="update({{ $index }})" class="btn btn-primary">Update</button>
#endif
</span>
</td>
</tr>
#endforeach
JS that sets the value of the select
$('.item').on('change', function (e) {
let data = $(this).val();
let idx = $(this).data('index');
#this.set(`purchaserequestitems.${idx}.item_id`, data);
});
Function that updates the data
public function update($prItemIndex)
{
$pritem = $this->purchaserequestitems[$prItemIndex] ?? NULL;
if(!is_null($pritem)){
$editedItem = PurchaseRequestItem::find($pritem['id']);
if($editedItem){
// dd($pritem);
$editedItem->update([
'item_id' => $pritem['item_id'],
'comment' => $pritem['comment'],
'quantity' => $pritem['quantity'],
'item_uom_conversion_id' => $pritem['item_uom_conversion_id']
]);
}
}
$this->editedPRItemsIndex = null;
}
Any help would be appreciated, or if you guys have any other way to implement an inline table editing with a select2 in it. Thank you
Tried to put the js inside an eventlistener but everytime I change the an option on the select box, it will just return to its original value.
So I'm very new to laravel and I have a filter in my website blade as follows:
goal: the user chooses a city and price from and price to and then clicks search and villas with what selected must be shown on another view! all values from the database!
I've tried to do this:
the route:
Route::get('/searched/{city_id}/{pricefrom}/{priceto}', [WebsiteController::class, 'search'])->name('search.clicked');
the controller:
public function index() {
$cities = DB::table('cities')
->select('*')->distinct()->get();
$users = Villa::with('City','Seller', 'Payment')->get();
$pricefrom = DB::table('villas')
->select('price')
->where('price', '<=', 50000)->distinct()->get();
$priceto = DB::table('villas')
->select('price')
->where('price', '>', 50000)->distinct()->get();
return view('website', compact('users','cities','pricefrom','priceto'));
}
public function search($city_id, $pricefrom, $priceto) {
$city = City::find($city_id);
$price = Villa::find($price);
$citydata = Villa::with('City','Seller', 'Payment')->where('city_id', $city_id)->get();
$lowdata = Villa::with('City','Seller', 'Payment')->where('price', $pricefrom)->get();
$highdata = Villa::with('City','Seller', 'Payment')->where('price', $priceto)->get();
$info = Villa::with('City','Seller', 'Payment')->get();
return view ('searched',compact('citydata','lowdata','highdata','info'))->with('city', $city )->with('price', $price);
}
the website view blade: here I didn't know how exactly I should pass the parameters for the route so I get an error
#foreach ($users as $villa)
<form action="{{ route('search.clicked', $villa->city_id,$villa->pricefrom,$villa->priceto) }}" method="get">
#csrf
<select name="city" class="form-select">
<option value="" id="searchoption"> City </option>
#foreach ($cities as $city)
<option >{{ $city->name }}</option>
#endforeach
</select>
<div class="col-lg-3 p-2">
<select name="pricefrom" class="form-select">
<option value="" id="searchoption"> Price From </option>
#foreach ($pricefrom as $low)
<option >{{ $low->price}}</option>
#endforeach
</select>
</div>
<div class="col-lg-3 p-2">
<select name="priceto" class="form-select">
<option value="" id="searchoption"> Price To </option>
#foreach ($priceto as $high)
<option >{{ $high->price}}</option>
#endforeach
</select>
</div>
<div class="col-lg-3 p-2">
<button type="button" class="btn btn-outline-success">search</button>
</div>
</form>
#endforeach
also Villa model
class Villa extends Model {
use HasFactory;
protected $fillable=[
"id", "title", "description", "price", "state", "status", "city_id", "seller_id", "payment_id",
"created_at", "updated_at"
];
public function City()
{
return $this -> hasOne(City::class,'id','city_id');
}
public function Seller()
{
return $this -> hasOne(Seller::class,'id','seller_id');
}
public function Payment()
{
return $this -> hasOne(Payment::class,'id','payment_id');
}
}
I think I have many errors I should fix And I want some help with my search bar!
I get this error:
Missing required parameters for [Route: search.clicked] [URI: searched/{city_id}/{pricefrom}/{priceto}] [Missing parameters: pricefrom, priceto].
try:
<form action="{{ route('search.clicked', [$villa->city_id,$villa->pricefrom,$villa->priceto]) }}" method="get">
According to route function second parameter should be string or array. String or Array if you're passing only 1 & array if you are passing 2 or more.
function route($name, $parameters = [], $absolute = true)
BLADE FILE:
#foreach ($users as $villa)
<form action="{{ route('search.clicked', $villa->city_id,$villa->pricefrom,$villa->priceto) }}" method="get">
#csrf
<select name="city" class="form-select">
<option value="" id="searchoption"> City </option>
#foreach ($cities as $city)
<option >{{ $city->name }}</option>
#endforeach
</select>
<div class="col-lg-3 p-2">
<select name="pricefrom" class="form-select">
<option value="" id="searchoption"> Price From </option>
#foreach ($pricefrom as $low)
<option >{{ $low->price}}</option>
#endforeach
</select>
</div>
<div class="col-lg-3 p-2">
<select name="priceto" class="form-select">
<option value="" id="searchoption"> Price To </option>
#foreach ($priceto as $high)
<option >{{ $high->price}}</option>
#endforeach
</select>
</div>
<div class="col-lg-3 p-2">
<button type="button" class="btn btn-outline-success">search</button>
</div>
</form>
#endforeach
to
#foreach ($users as $villa)
<form action="{{ route('search.clicked', ['city_id' => $villa->city_id, 'pricfrom' => $villa->pricefrom, 'priceto' =>$villa->priceto]) }}" method="get">
#csrf
<select name="city" class="form-select">
<option value="" id="searchoption"> City </option>
#foreach ($villa->cities as $city)
<option >{{ $city->name }}</option>
#endforeach
</select>
<div class="col-lg-3 p-2">
<select name="pricefrom" class="form-select">
<option value="" id="searchoption"> Price From </option>
#foreach ($villa->pricefrom as $low)
<option >{{ $low->price}}</option>
#endforeach
</select>
</div>
<div class="col-lg-3 p-2">
<select name="priceto" class="form-select">
<option value="" id="searchoption"> Price To </option>
#foreach ($villa->priceto as $high)
<option >{{ $high->price}}</option>
#endforeach
</select>
</div>
<div class="col-lg-3 p-2">
<button type="button" class="btn btn-outline-success">search</button>
</div>
</form>
#endforeach
You need add to route :
<form action="{{ route('search.clicked',$object->first()->city_id,$model->first()->pricefrom,$model->first()->priceto) }}" method="get">
when add next select, you lose the data of the first select of the municipalities.
Livewire controller SelectUsuario.php
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use Illuminate\Support\Facades\Http;
class SelectUsuario extends Component
{
public $estados;
public $estado;
public $estadoSigla;
public $municipios;
public $selects = [];
public $i = 0;
public function add($i)
{
$i = $i + 1;
$this->i = $i;
array_push($this->selects, $i);
}
public function remove($i)
{
unset($this->selects[$i]);
}
public function mount()
{
$this->estados = Http::get(
url("https://servicodados.ibge.gov.br/api/v1/localidades/estados"),
['orderBy' => 'nome']
)->json();
}
public function updatedEstadoSigla()
{
$this->getMunicipios();
}
public function getMunicipios()
{
if ($this->estadoSigla != '') {
foreach ($this->estadoSigla as $estado) {
$this->municipios = json_decode(
Http::get(
url("https://servicodados.ibge.gov.br/api/v1/localidades/estados/{$estado}/municipios")
)->body(),
true
);
}
}
}
public function render()
{
return view('livewire.select-usuario');
}
}
Livewire component select-usuario.blade.php
<div class="form-group row">
<div class="col-3"><label>Viagem</label></div>
<div class="col-3"><label>Seção</label></div>
<div class="col-4"><label>Funcionário</label></div>
<div class="col-2"><label>Ação</label></div>
<div class="col-3">
<select class="form-control" data-item_id="0">
<option value="R">Responsável</option>
</select>
</div>
<div class="col-3">
<select wire:model="estadoSigla.0" class="form-control" id="estado.0" name="estado.0">
<option value="">selecione estado...</option>
#foreach ($this->estados as $estado)
<option value="{{ $estado['sigla'] }}">{{ $estado['nome'] }}</option>
#endforeach
</select>
</div>
<div class="col-4">
#if ($this->estadoSigla)
<select class="form-control" name="municipio.0" id="municipio.0">
<option value="" selected>selecione município...</option>
#foreach ($this->municipios as $municipio)
<option value="{{ $municipio['id'] }}">{{ $municipio['nome'] }}</option>
#endforeach
</select>
#endif
</div>
<div class="col-2">
<button class="btn btn-info mb-2" wire:click.prevent="add({{ $i }})">adicionar</button>
</div>
{{-- Add Form --}}
#foreach ($selects as $key => $value)
<div class="col-3">
<select name="item_name[]" class="form-control" data-item_id="{{$value}}">
<option value="I">Ida</option>
<option value="V">Volta</option>
<option value="O">Ida e Volta</option>
<option value="R">Responsável</option>
</select>
</div>
<div class="col-3">
<select wire:model="estadoSigla.{{ $value }}" class="form-control" name="estado.{{ $value }}" id="estado.{{ $value }}">
<option value="">selecione estado...</option>
#foreach ($this->estados as $estado)
<option value="{{ $estado['sigla'] }}">{{ $estado['nome'] }}</option>
#endforeach
</select>
</div>
<div class="col-4">
#if ($estadoSigla)
<select class="form-control" name="municipio.{{ $value }}" id="municipio.{{ $value }}">
<option value="" selected>selecione município...</option>
#foreach ($this->municipios as $municipio)
<option value="{{ $municipio['id'] }}">{{ $municipio['nome'] }}</option>
#endforeach
</select>
#endif
</div>
<div class="col-2">
<button class="btn btn-dark mb-2" wire:click.prevent="remove({{ $key }})">remover</button>
</div>
#endforeach
</div>
try adding wire:key directive to the looped select elements while livewire need to keep tracking all the values of them.
<select wire:model="estadoSigla.{{ $value }}" class="form-control" id="estado.{{ $value }}" wire:key="estado-select-{{ $key }}"> // or $value, the unique identifier for its
also, try adding wire:ignore.self to the root div of the select elements
This code from product_listing.blade.php and here the dropdown filter. I need all the item name in ascending orde. Right now the list is in order how I can see it in a database table..
<div class="box-title text-center">
{{ translate('Filter by CarType')}}
</div>
<div class="box-content">
<div class="filter-checkbox">
<select class="form-control" data-placeholder="{{ translate('All CarType')}}" name="cartype" onchange="filter()">
<option value="">Select CarType</option>
#foreach (\App\CarType::all() as $cartype)
<option value="{{ $cartype->id }}" #isset($cartype_id) #if ($cartype_id == $cartype->id) selected #endif #endisset>{{ $cartype->name }}</option>
#endforeach
</select>
</div>
</div>
You can use collection's sortBy() method:
<div class="box-title text-center">
{{ translate('Filter by CarType')}}
</div>
<div class="box-content">
<div class="filter-checkbox">
<select class="form-control" data-placeholder="{{ translate('All CarType')}}" name="cartype" onchange="filter()">
<option value="">Select CarType</option>
#foreach (\App\CarType::all()->sortBy('name') as $cartype)
<option value="{{ $cartype->id }}" #isset($cartype_id) #if ($cartype_id == $cartype->id) selected #endif #endisset>{{ $cartype->name }}</option>
#endforeach
</select>
</div>
</div>
I have created a drop-down for categories and subcategory. It works fine when i submit the form, but when I edit the form, category field does not come with refilled data from the database, category drop-down come like it show in create form.
here is my edit:
<div class="form-group">
{!! Form::label('category','Category:') !!}
<select name="category" id="category" class="form-control input-sm">
#foreach($s as $k)
<option value="{{ $k['id'] }}">{{ $k['name'] }}</option>
#endforeach
</select>
</div>
<div class="form-group">
{!! Form::label('subcategory','Subcategory:') !!}
<select name="subcategory" id="subcategory" class="form-control input-sm">
<option value=""></option>
</select>
</div>
Controller:
public function edit($id)
{
// get the event
$event = Event::findOrFail($id);
$s = Category::all()->where('parent_id','=','0');
$r = Event::all();
$daysOfWeek = unserialize(Event::find($id)->days_of_week);
// show the edit form and pass the event
return view('event.edit',compact('event','s','r','daysOfWeek'));}
I haven't used relations for the dropdown, I have used jquery and ajax to select subcategory after I select category.
What can i do to get the value stored in database when I do edit form?
I got my answer thanks every one for help!
View:
<div class="form-group">
{!! Form::label('category','Category:') !!}
<select name="category" id="category" class="form-control input-sm">
#foreach($s as $k)
#if($k['id'] == $m)
<option value="{{ $k['id'] }}" selected="{{$m}}">{{ $k['name'] }}</option>
#else
<option value="{{ $k['id'] }}">{{ $k['name'] }}</option>
#endif
#endforeach
</select>
</div>
<div class="form-group">
{!! Form::label('subcategory','Subcategory:') !!}
<select name="subcategory" id="subcategory" class="form-control input-sm">
#foreach($subcat as $k)
#if($k['name'] == $subid)
<option value="{{ $k['id'] }}" selected="{{$subid}}">{{ $k['name'] }}</option>
#else
<option value="{{ $k['id'] }}">{{ $k['name'] }}</option>
#endif
#endforeach
<option value=""></option>
</select>
</div>
Controller:
public function edit($id)
{
$event = Event::findOrFail($id);
$s = Category::where('parent_id','=','0')->get();
$r = Event::all();
$m = Event::find($id)->category;
$subid = Event::find($id)->subcategory;
$subcat = Category::where('parent_id','=',$m)->get();
$daysOfWeek = unserialize(Event::find($id)->days_of_week);
return view('event.edit',compact('event','s','subcat','subid','r','daysOfWeek','m'));
}
There is a mistake in your Controller method edit()
Your code:
$s = Category::all()->where('parent_id','=','0'); // wrong
Isn't that supposed to be:
$s = Category::where('parent_id','=','0')->get(); // correct
You are already fetching the categories with all, and then passing the where condition, hence it is not showing you the results. where condition returns the instance of Illuminate\Database\Eloquent\Builder and not the desired results.
Update the wrong line with the correct one and the result should appear as you want.