Livewire Select2 Dynamic not updating public view - laravel

I am using a select2 component with wire:ignore and i want to update the select2 value dynamically after clicking a button. I set up this functionality with events and events work fine, so does the variable gets initialized as well. I am failing to update this public view of this select2.
my blade
<select class="select2-example form-control" id="subjects" wire:model.lazy="subjects" name="subjects">
</select>
#push('scripts')
<script>
$('#subjects').select2({
maximumSelectionLength: 1,
minimumInputLength:2,
tags: false,
placeholder: 'Enter Subject(s)',
.... // this all works great
});
$('#subjects').on('change', function (e) {
let data = $(this).val();
#this.set('subjects', data);
});
// my event listener and it is working as well
Livewire.on('editSubject', subject => {
console.log(subject);
#this.set('subjects', subject);
$('#subjects').val(subject);
$('#subjects').trigger('change'); //the public view doesn't get updated
})
</script>
#endpush
I so far tried with browser dispatch event as well. Nothing works. What would be the workaround for this? Any help is greatly appreciated.

in blade
<div class="col d-flex display-inline-block">
<label for="contact_devices">{{ __('Select Device') }}</label>
<select id="contact_devices" wire:model="selectedDevice" class="form-control contact_devices_multiple" multiple="multiple" data-placeholder="{{ __('Select') }}">
#foreach($devices as $device)
<option value="{{ $device->id }}">{{ $device->alias }}</option>
#endforeach
</select>
</div>
<script>
window.loadContactDeviceSelect2 = () => {
$('.contact_devices_multiple').select2({
// any other option
}).on('change',function () {
livewire.emitTo('tenant.contact-component','devicesSelect',$(this).val());
});
}
loadContactDeviceSelect2();
window.livewire.on('loadContactDeviceSelect2',()=>{
loadContactDeviceSelect2();
});
</script>
in component
public $selectedDevice;
protected $listeners = [
'devicesSelect'
];
public function devicesSelect($data)
{
dd($data);
$this->selectedDevice = $data;
}
public function hydrate()
{
$this->emit('loadContactDeviceSelect2');
}

Note: If some face the problem of real time validaiton while implementing the above mentioned solution as i have commented in the accepted answer above.
My Comments:
hey, I have implemented your solution its working great but there is
one problem, here is the scenario, I submit empty form and all the
validations gets triggered, when i start filling the form the error
starts to disappear but as soon as i change the select2 the validation
part $this-update($key, $value) function does not work. Can you please
tell me why real time validation is not working ? and how to fix it
please. thankyou – Wcan
Solution:
Use syncInput() function instead of assigning the value to country property. updated lifecycle hook will be trigerred automatically.
public function setCountry($countryValue)
{
// $this->country = $countryValue;
$this->syncInput('country', $countryValue);
}

Related

Vue Js2 cant kep old data from laravel on select option

I am working on a crud operation with vue js and laravel. Everything works fine but I am thinking of a small improvement to make the site more user friendly. So where i click edit button all my inputs have they old value (fetched from laravel) except selected options. They do not update with the corresponding values from the db and when i edit an record this is a problem . How can i set old value or coresponding value on this option
form select for my options
<div class="form-group">
<label class="form-label select-label" for="team_foreman">Team Skill</label>
<select v-model="edit_team_skills" class="form-select" id="team_foreman" >
<option v-if="!skills.length" class="text-center" disabled>No data to show</option>
<option v-for="skill in skills" :value="skill.id" :key="skill.id" >{{skill.skills_name}}</option>
</select>
</div>
vue data
data() {
return {
edit_team_skills: '',
}
}
//edit method
editTeam(id) {
axios.get('/teams/'+id+'/edit')
.then(response => {
// console.log(response.data.teams.skills)
this.id = response.data.teams.id,
this.edit_team_name = response.data.teams.team_name
.....
this.edit_team_skills = response.data.teams.skills
})
},
laravel edit controller
public function edit($id)
{
$teams = Team::with('skills')->find($id);
return response()->json([
'teams' =>$teams,
], Response::HTTP_OK);
}
The v-model of the select should be an array of active option values, as you fill those with the id of the skill you should make this.edit_team_skills an array of id's.
this.edit_team_skills = response.data.teams.skills.map(skill => skill.id)

How do I set selected value that is base on drop-down list in Jquery and assign it to my model?

I need the value from the option to be assigned to my model once the user clicks on the specific option.
<select name="isEmailVerified" class="form-select">
<option value="" selected> all </option>
<option value="true"> verified </option>
<option value="false"> unverified </option>
</select>
expected value => #Model.IsEmailVerified.XXXXX(my value)
What I usually do when I want to asyncronously send data back and forth is this:
I take advantage of Tag Helpers as they're great and saves you a ton of boilerplate code, so I create a standard <form> element without an actual Submit button, just a div that looks like one. You might want to check official MSDN Documentation for the Select Tag Helper to create an appropriate model.
#model VerificationModel
<form asp-action="CheckEmail" method="post">
<select asp-for="IsEmailVerified" asp-items="Model.VerificationTypes">
<div id="SubmitCheck" class="btn">Check email</div>
</form>
Create a javascript function that takes care of the actual submitting chore. Since the form is created with the Tag Helpers, the request body will automatically bind
$('#SubmitCheck').on('click', function() {
let form = $(this).parents('form')[0];
let formData = new FormData(form);
let request = function () {
return fetch(form.getAttribute('action'), {
method: 'POST',
body: formData
});
};
let onresponse = function() {
// do some preliminary actions on 200 response
}
let callback = function() {
// deal with response result
}
let onerror = function() {
// deal with errors
}
request()
.then(response => onresponse())
.then(result => callback())
.fail(err => onerror());
})
Add the [FromForm] attribute to Controller props (model is the same used in the page) to ensure model binding
public async Task<CustomResultClass> CheckEmail([FromForm] VerificationModel model)
{
// do something
}

Livewire - updated hook without render of complex data

I'm using Livewire for data table with a complex database query with pagination. In table are also checkboxes and after check/uncheck is quite annoying to wait for render method with fetching all necessary data witch are required only for first component load.
I know I can use defer flag for checkboxes but I need also do some action when is any checkbox checked/unchecked so I cannot use that flag. So my question is if I can use updated hook method for checkbox without loading data in render.
Here is my example code:
class LivewireComponent extends Component
{
public $arrayOfCheckboxes = [];
public function render(SomeService $service)
{
$data = $service->fetchComplexData->paginate();
return view('livewire.some-component', ['data' => $data]);
}
public function updatedArrayOfCheckboxes($value)
{
// if value is true/false then do some action
// do I really need to call render and fetch complex data again?
}
}
// livewire.some-component.blade.php
<div>
<table>
#foreach($data as $row)
<input type="checkbox" wire:model="arrayOfCheckboxes" value="{{ $row->someValue }}">
#endforeach
</table>
</div>

livewire alpine flatpickr getting null

I can't get this to give me the dd() of the date. It keeps coming back as null. i've implemented flatpickr correctly and all works accept when i try to get the actual date. However, when i add an additional button to submit the date with wire directive it works. But i want it to fire when a date is clicked. Any help would be appreciated. Thanks
in my livewire file.
public $date;
public function secondStepSubmit()
{ dd('date');
};
in my view
<input x-data x-init="flatpickr($refs.input, null);" wire:change="secondStepSubmit" x-ref="input" type="text" />
</div>
flatpickr has its own change event listener.
you can use that to get the value of the date of the input as follows.
<div>
<input x-data x-init="flatpickr($refs.input, {
onChange: function(dateObj, dateStr) {
#this.call('secondStepSubmit', dateStr)
}
});" x-ref="input" type="text" />
</div>
I have used #this blade directive from livewire, we also can use $wire from alpine too.
in the Livewire component,
public function secondStepSubmit($date)
{
dd($date);
}

jQuery returning null - selected option not being posted correctly?

This jQuery script is returning null. I've tried using other syntax for selected options but here's what I've got below:
The script works and runs correctly, allowing me to download the Excel file. However the ID is not being set correctly (via the option selected) and thus is parsing as "0".
<script>
//When Page Loads....
$(document).ready(function(){
$('#dropdown').change(function(){
// Call the function to handle the AJAX.
// Pass the value of the text box to the function.
sendValue($(this).val());
});
});
// Function to handle ajax.
function sendValue(str){
// post(file, data, callback, type); (only "file" is required)
$.post(
"scripts/export_to_excel/index.php", //Ajax file
{ sendValue: str }, // create an object will all values
//function that is called when server returns a value.
function(data){
$('#linkDiv').html(data.returnValue);
},
//How you want the data formatted when it is returned from the server.
"json"
);
}
</script>
Select HTML
<p>Select event for export to Excel:</p>
<p>
<select name="eventIDExport" id="dropdown">
<option value=0>
<?=$options?>
</select>
</p>
<?php var_dump($_POST['eventIDExport']); ?>
<div id="linkDiv"></div>
Rendered mark-up
<p>Select event for export to Excel:</p>
<p>
<select name="eventIDExport" id="dropdown">
<option value=0>
<option value="1">BIG event</option>
<option value="54">2013 Network Conference</option>
</select>
</p>
NULL
<div id="linkDiv"></div>
Some of the code in index.php to process Ajax request - I think this is triggering the null value?
if (isset($_POST['eventIDExport']))
{
$eventIDExport = $_POST['eventIDExport'];
}else{
$eventIDExport = "";
}
Why you POST sendValue and check if eventIDExport is set?
$.post("scripts/export_to_excel/index.php", {
sendValue: str
^^^^^^^^^
and
if (isset($_POST['eventIDExport']))
^^^^^^^^^^^^^
Your code should be:
if(isset($_POST['sendValue']))
{
$eventIDExport = $_POST['sendValue'];
} else {
$eventIDExport = "";
}
or
$.post("scripts/export_to_excel/index.php", {
eventIDExport: str

Resources