How do I bind a radio button value to my model? Laravel 5.3 - laravel-5

I have a form with a couple of radio buttons;
<div class="form-group{{ $errors->has('procurement') ? ' has-error' : '' }} col-md-6">
<label for="procurement" class="col-md-6 control-label">Procurement Type <span class="red">*</span></label><br>
<div class="col-md-12">
<input id="procurement" type="radio" name="procurement" value="owned"> Owned
<input id="procurement" type="radio" name="procurement" value="rental"> Rental
#if ($errors->has('procurement'))
<span class="help-block">
<strong>{{ $errors->first('procurement') }}</strong>
</span>
#endif
</div>
I am reusing the form for editing purposes so I want to be able to bind the object's value for 'procurement' when I present the form in edit view. I am able to use this bind the values for text inputs;
value="{{ isset($vehicle->model) ? $vehicle->model : old('model') }}"
But this does not work for radios or selects. What should I be doing? I am NOT using the Form facade for this.
Thanks!

You can use selected and checked for what you want to do. Just add it to the end of the element, and it will select/check the element.
Something like this for input type radio:
<input id="procurement" type="radio" name="procurement" value="owned" {{ old('model') === "owned" ? 'checked' : (isset($vehicle->model) && $vehicle->model === 'owned' ? 'checked' : '') }}> Owned
<input id="procurement" type="radio" name="procurement" value="rental" {{ old('model') === "owned" ? 'checked' : (isset($vehicle->model) && $vehicle->model === 'rental' ? 'checked' : '') }}> Rental
And this for select options:
<option value="something" {{ old('model') === "something" ? 'selected' : (isset($vehicle->model) && $vehicle->model === 'owned' ? 'selected: '')}}>Something</option>
Side note: I'd recommend making sure that old('something') comes before other possible values when you're filling values in. For instance, you had:
value="{{ isset($vehicle->model) ? $vehicle->model : old('model') }}"
which would override the user's original input with database results (if any, of course) upon a failed submission. So if I was say, updating my name in a text field, and there were errors to the form, it would direct me back to the form and lose my input because the database results are before the old value. Hope that makes sense!

Related

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

Undefined variable $attendance_status using radio button laravel

i am using laravel query builder but the problem is i am using radio buttons but i want to update the attendance at the radio button but it returns an error Undefined variable $attendance_status
i don't know why please help and how can i pass the $attendance_status variable
here is my code
my form
<form action="{{route('Attendances.update',$student->id)}}" method="post">
#csrf
#method('PUT')
<input type="hidden" name="id" value="{{$student->id}}">
<label class="block text-gray-500 font-semibold sm:border-r sm:pr-4">
<input name="attendences"
{{ $student->attendances()->first()->attendence_status == 1 ? 'checked' : '' }}
class="leading-tight" type="radio" value="presence">
<span class="text-success">حضور</span>
</label>
<label class="ml-4 block text-gray-500 font-semibold">
<input name="attendences"
{{ $student->attendances()->first()->attendence_status == 0 ? 'checked' : '' }}
class="leading-tight" type="radio" value="absent">
<span class="text-danger">غياب</span>
</label>
<div class="modal-footer">
<button type="button" class="btn btn-secondary"
data-dismiss="modal">{{trans('Students_trans.Close')}}</button>
<button class="btn btn-danger">{{trans('Students_trans.submit')}}</button>
</div>
</form>
here is my controller
update
public function update(Request $request, $id)
{
// return $request;
if($request->attendances == 'absent'){
$attendance_status = 0;
}
else if($request->attendances == 'presence'){
$attendance_status = 1;
}
Attendance::find($id)->update([
'student_id'=> $id,
'grade_id'=> $request->grade_id,
'class_id'=> $request->classroom_id,
'section_id'=> $request->section_id,
'attendance_date'=> date('Y-m-d'),
'status' => $attendance_status,
]);
return back();
You have an if and an elseif in your Controller, so only 2 conditions would create a variable named $attendance_status. You probably want to add a default branch, else basically, to make sure that the variable gets created with some default value before you try to use it in your update call.
Not sure which one of those 2 options you want to be the default but this would simplify things:
$attendance_status = $request->attendences == 'presence';
https://laravel.com/docs/9.x/redirects#redirecting-with-flashed-session-data
You may use the withInput method provided by the RedirectResponse instance to flash the current request's input data to the session before redirecting the user to a new location. Once the input has been flashed to the session, you may easily retrieve it during the next request:
return back()->withInput();
Surely {{ $student->attendances()->first()->attendence_status == 0 ? 'checked' : '' }} logic does not work in this way.
try this instead
<input name="attendences" checked="{{ $student->attendances()->first()->attendence_status == 0 ? true : false}}" class="leading-tight" type="radio" value="absent">

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;
}

How to avoid livewire request for simple inputs calculations?

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>

Show and update date with correct format

I have a edit page that shows a date and is possible to change the date and edit it.
I want to show the date in this format "25-08-18 - 15:30" if the date already is stored in DB. So I have this field:
<div class="form-group col-md-6">
<label for="date">Date</label>
<div class="input-group date" data-provide="datepicker">
<input type='text' onkeydown="event.preventDefault()"
name="date" value="{{!empty($post->date) ? $post->date->formatLocalized('j-m-y - H:i') : ''}}"
class="form-control" placeholder="DD/MM/YYY"/><span class="input-group-addon"><i class="fa fa-calendar text-primary"
aria-hidden="true"></i></span>
</div>
</div>
But like that it shows "j-m-y - H:i" in the input field value. Do you know why?
Like this:
value="{{!empty($post->date)
? $post->date->toDateTimeString()
: ''
}}
it shows the seconds "2018-08-25 15:30:00" but it should show only "2018-08-25 15:30".
Then to validate is used:
'date' => 'nullable|date_format:"j-m-y - H:i"',
And to update is used:
$post->date = (isset($request->date)) ?
Carbon::createFromFormat('j-m-y - H:i', $request->date) : null;
value="{{!empty($post->date)
? substr($post->date->toDateTimeString(),0,-2)
: ''
}}
format and formatLocalized are not the same and are not interchangeable.
formatLocalized() uses strrftime() under the hood and is used for formatting local time/date according to locale settings and does not accept the same formatting string/characters as the format() method.
You should be able to achieve what you're after by changing:
$post->date->formatLocalized('j-m-y - H:i')
to:
$post->date->format('j-m-y - H:i')

Resources