How to avoid livewire request for simple inputs calculations? - laravel

How would I avoid doing calculation for 3 inputs using Livewire and use JS instead, but still can bind the inputs and their new values with the component.
Example:
<input id="cash-price"
type="text"
wire:model="total_cache_price"
class="amount-credit">
<input id="deposit"
type="text"
wire:model="deposit"
class="amount-credit">
<input id="trade-in"
type="text"
wire:model="trade_in"
class="amount-credit">
I can easily do a simple calculation using JS, but the properties in Livewire component would still be empty or null after submitting the form. I am trying to avoid livewire requests for every input change.
Note: I understand the deferred updating in livewire, the problem is with the property values not changing.

I will show you an example in alpine js + livewire way.
Here I want to set value in two inputs from a selected option in select.
Please note that x-ref is used in alpine to directly access DOM elements without using getElementById.
<div x-data="{
from_date : #entangle('from_date').defer,
to_date : #entangle('to_date').defer,
dateChange(){
select = this.$refs.years;
this.from_date = select.options[select.selectedIndex].getAttribute('data-from');
this.to_date = select.options[select.selectedIndex].getAttribute('data-to');
},
resetFilters(){
this.net_balances = false;
}}">
<select x-ref="years" #change="dateChange()">
<option value="">Year</option>
#foreach ($years as $key => $year)
<option wire:key="{{ 'years'.$key }}" data-from="{{ $year->from_date }}" data-to="{{ $year->to_date }}" value="{{ $year->id }}">{{ $year->name }} </option>
#endforeach
</select>
<div>
<text type="date" x-model="from_date" />
</div>
<div >
<text type="date" x-model="to_date" />
</div>

Related

Laravel Livewire and select2 dropdown inside of bootstrap modal

I have a select2 blade component that I'm using inside of a bootstrap modal. Everything is working as expected, except when the modal form is submitted, the styling of the select 2 is lost, and a new empty option (must be the placeholder) is shown as an option, but only in the selects where I'm doing a yes/no option where the value is either 1 or 0 (See code below).
The styling is messed up on all, but the extra placeholder option only shows up on some.
Here's the normal way it should look, and does look when you first open the modal after a page refresh:
After submitting the modal it looks like this (notice the extra placeholder option):
Here's the code for my select2 component:
#props(['id', 'usePlaceholder' => null])
<div wire:ignore style="width:100%;" id="select2-{{ $id }}">
<select {{ $attributes }} id="{{ $id }}" name="{{ $id }}[]" class="form-select select2" data-width="100%" data-select2-id="{{ $id }}">
#if ($usePlaceholder)
<option></option>
#endif
{{ $slot }}
</select>
</div>
{{-- blade-formatter-disable --}}
#push('custom-scripts')
<script>
$(document).ready(function() {
let select2 = $('#' + #js($id));
select2.select2({
dropdownParent: $('#select2-' + #js($id)),
placeholder: 'Select an option',
minimumResultsForSearch: 15
});
***The below listeners I can comment out, they have no effect as far as I can tell, just including them for reference***
window.addEventListener('hideModal', event => {
select2.val(null).trigger('change');
});
window.addEventListener('set'+#js(ucfirst($id)), event => {
select2.val(event.detail).trigger('change');
});
});
</script>
#endpush
{{-- blade-formatter-enable --}}
And here's where I'm actually using the component:
<div class="col-md-6">
<x-input.group label="Sales Tax" for="salesTax" :error="$errors->first('salesTax')">
<x-input.select2 usePlaceholder="{{ empty($salesTax) ? 'true' : '' }}" wire:model.defer="salesTax" id="salesTax">
<option name="no" id="sales-tax-0" value="0">No</option>
<option name="yes" id="sales-tax-1" value="1">Yes</option>
</x-input.select2>
</x-input.group>
</div>
I've tried destroying and re-initializing the select2 when the modal is dismissed, but that hasn't done anything for me.

Laravel Livewire: Bootstrap Select-Picker unable to render

I want to load categories and multiple sub categories according to all the categories that are selected, inside a multi-step form at step 4, but I am not able to select multiple categories using bootstrap selectpicker (multiple selects) library inside livewire component. The issue with using Bootstrap-Select with Livewire is that both of these libraries use JavaScript to update the page dynamically, which is probably causing conflicts. If I try accessing the same without livewire, it works perfectly fine, but with livewire I am unable to render it.
form.blade
#section('content')
<livewire:multi-step-form />
#endsection
#push('before-styles')
<link rel="stylesheet prefetch" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.css" />
#endpush
#push('before-scripts')
<script rel="javascript prefetch" src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.bundle.min.js"></script>
<script rel="javascript prefetch" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.18/js/bootstrap-select.min.js" integrity="sha512-yDlE7vpGDP7o2eftkCiPZ+yuUyEcaBwoJoIhdXv71KZWugFqEphIS3PU60lEkFaz8RxaVsMpSvQxMBaKVwA5xg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
#endpush
multi-step-form.blade
<select wire:model="categories" name="categories[]" class="selectpicker form-control" multiple data-live-search="true" required id="categories" title="{{ trans('select category') }}">
#foreach($categories as $category)
<option value="{{$category->id}}" {{ (collect(old('categories'))->contains($category->id)) ? 'selected' : '' }}>
{{$category->category}}
</option>
#endforeach
</select>
Some Failed Attempts
Inside livewire component
Attempt 1
<script>
document.addEventListener('livewire:load', function () {
$('.selectpicker').selectpicker();
});
</script>
This works well but only once, i.e. at the start when livewire was loaded. This doesn't work, after the livewire component is updated by some input. So I added a code right below it:
Attempt 2
<script>
document.addEventListener('livewire:load', function () {
$('.selectpicker').selectpicker();
$('.selectpicker').selectpicker('render');
});
</script>
This didn't work too. Some few articles had render separated in updated script so I did that too.
Attempt 3
<script>
document.addEventListener('livewire:load', function () {
$('.selectpicker').selectpicker();
});
document.addEventListener('livewire:updated', function () {
$('.selectpicker').selectpicker('render');
});
</script>
Unfortunately this didn't work either.
I have tried adding the same scripts to my app.js too later, but am not sure where am I going wrong, and how can I make this working.
Attempt 4
Kept the scripts as is, and added wire:ignore in parent div
<div wire:ignore class="form-group">
<select wire:model="categories" name="categories[]" class="selectpicker form-control" multiple data-live-search="true" required id="categories" title="{{ trans('select category') }}">
#foreach($categories as $category)
<option value="{{$category->id}}" {{ (collect(old('categories'))->contains($category->id)) ? 'selected' : '' }}>
{{$category->category}}
</option>
#endforeach
</select>
</div>
As suggested in livewire/livewire/issues/45, but this didn't work as well.

Laravel 8 Livewire and google places autocomplete not working

sI have a livewire form with an address field that has google places autocomplete enabled on it. Every time I select an address from the autocomplete list and move to a new input in the form the address input gets reset to the value before clicking the address I wanted.
I added wire:ignore on my field and it still gets reset to the value typed in before the click event. This is my code for the input:
<div wire:ignore id="for-input-address" class="form-group col-lg-6{{ $errors->has('address') ? ' has-danger' : '' }}">
<label class="form-control-label" for="input-address">{{ __('Home address') }}</label>
<input wire:model="address" type="text" name="address" id="input-address" class="form-control form-control-alternative{{ $errors->has('address') ? ' is-invalid' : '' }}" placeholder="{{ __('Home address') }}" value="{{ old('address') }}" required autofocus>
#if ($errors->has('address'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('address') }}</strong>
</span>
#endif
</div>
So if I type 56 and select the address the moment I move to the next field the input gets reset to 56.
I want to say I have some select fields with wire:ignore that work just fine when livewire reloads the DOM.
Put an additional attribute to your input -> autocomplete="off" to tell the browser not to use any autocomplete mechanisms.
See: https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/autocomplete
I ended up using livewire events, documented here: https://laravel-livewire.com/docs/2.x/events in my blade file and I fired an event on google autocomplete "place_changed" like so
google.maps.event.addListener(autocomplete, 'place_changed', function() {
Livewire.emit('addressUpdated', addressAndTown, postcode);
});
and in my controller I did the following before the submit function
public function addressUpdated($address, $postcode)
{
$this->address = $address;
$this->postcode = $postcode;
}
and updated my values in the controller

Livewire uncaught (in promise) DOMException with select

I have a dropdown in my component that seems to be causing an error in Livewire.
Uncaught (in promise) DOMException: Failed to execute 'setAttribute'
on 'Element': '?' is not a valid attribute name.
I added the wire:key code based on what I read in the docs under the troubleshooting section, but it didn't seem to help. It updates the value on save just like it should, but when it refreshes the dom with the new data, it's not working.
Here's the offending element:
<div class="mb-3 col-md-4 ">
<label for="state" class="form-label">State</label>
<select wire:model.defer="location.state" class="form-select"
id="state" name="state">
#foreach ($states as $state)
<option
name="{{ $state->name }}"
id="{{ $state->code }}"
wire:key="{{ $state->id }}"
value="{{ $state->code }}"
#if (isset($location->state)
&& $location->state === $state->code) ? selected #endif
>{{ $state->name }}
</option>
#endforeach
</select>
</div>
You have a typo here,
#if (isset($location->state) && $location->state === $state->code)
? selected
#endif
Where it tries to apply ? as an attribute on the element, but ? is not a valid attribute. Just remove the ?.
That said, you cannot use the selected property on <select> elements in Livewire to set the selected value. You need to set the value of your wire:model in your component. This means that you have to remove the #if(..) selected #endif from your Blade entirely, and instead set the value in your component,
public function mount() {
$this->location['state'] = $state->code;
}

Property [kodeSparepart] does not exist on this collection instance

I want to get all of the data from sparepart database using all() function, then use foreach in view to access the data, but I keep get that error. It works fine when I use the same method for other view blade.
Controller
public function LaporanSisaStok(Request $request) {
if($request->kode == "")
{
$spareparts = Sparepart::all();
return view('laporan/sisaStok')->with(['spareparts' => $spareparts]);
}
else {
$query = DB::table("historisparepart")->select(DB::raw('EXTRACT(MONTH FROM tanggal) AS Bulan, SUM(jumlah) as Sisa'))
->where('kodeSparepart', $request->kode)
->groupBy(DB::raw('EXTRACT(MONTH FROM tanggal)'))
->get();
return view('printPreview/sisaStok', ['data'=>$query]);
}
}
View
<form method="POST" action="{{ route('laporan.sisaStok') }}" enctype="multipart/form-data">
#csrf
<div class="form-group-row">
<label for="sparepart" class="col-sm-2 col-form-label">Sparepart</label>
<select class="custom-select" id="kode" name="kode">
<option value="">-Pilih Sparepart-</option>
foreach($spareparts as $sparepart)
{
<option value="{{$sparepart->kodeSparepart}}"> {{$sparepart->namaSparepart}} </option>
}
</select>
</div>
<br>
<button type="submit" class="btn btn-info"><i class="oi oi-task"></i> Cari </button>
You aren't looping through anything. You need to give the foreach() method a variable from your spareparts collection. I think it might help you avoid confusion, to name the collection variables plural:
In your controller:
$spareparts = Sparepart::all();
return view('laporan/sisaStok', compact('spareparts'));
Then, most importantly, you need to tell foreach what it should produce. In your view, change:
foreach($sparepart)
to
#foreach($spareparts as $sparepart)
Don't forget you are in blade, so use the # before the foreach. Then, assuming you actually have a property on the spareparts model called kodeSparepart, this should work fine.
This is not a looping syntax in the laravel view
foreach($spareparts as $sparepart)
{
<option value="{{$sparepart->kodeSparepart}}"> {{$sparepart->namaSparepart}} </option>
}
It should be like this
#foreach($spareparts as $sparepart)
<option value="{{$sparepart->kodeSparepart}}"> {{$sparepart->namaSparepart}} </option>
#endforeach
And another problem is you are passing the data in wrong way. It should be like this
return view('printPreview/sisaStok', ['spareparts'=>$query]);
You shoud use the plural of your dtb name to loop over the values so your 'sparepart' variable should change to 'spareparts'
$sparepart = Sparepart::all();
return view('laporan/sisaStok')->with(['spareparts' => $sparepart]);
In your view change your loop to the new variable and loop using your current variable, so your view shoul look like this:
View
<div class="form-group-row">
<label for="sparepart" class="col-sm-2 col-form-label">Sparepart</label>
<select class="custom-select" id="kode" name="kode">
<option value="">-Pilih Sparepart-</option>
#foreach($spareparts as $sparepart)
{
<option value="{{$sparepart->kodeSparepart}}"> {{$sparepart->namaSparepart}} </option>
}
#endforeach
</select>
</div>

Resources