Vue Js2 cant kep old data from laravel on select option - laravel

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)

Related

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
}

I want to make an input in the admin panel with which you can increase / decrease prices in several tables in db by %

I want to make an input in the admin panel with which you can increase / decrease prices in several tables in db by %.
At the moment, I did it through a filter
{
return [
new TwigSimpleFilter('price_kiev', [$this, 'formatPriceKiev'])
];
}
public function getPriceEditKiev()
{
$result = DB::table('another_pricelist_edit')->select('price_edit_kiev')->where('id', 1)->first();
return $result->price_edit_kiev;
}
public function formatPriceKiev($number)
{
$a = $this->getPriceEditKiev();
if ($a >= 1) {
$price = $number + $number / 100 * $a;
return round($price, -1);
}else{
return $number;
}
}
markup:
<td class="column-3">
{{ item.price_kiev_1 | price_kiev | number_format(0, '', ' ' ) }}</td>
admin panel with tables:
input where I enter the number for the filter, which I want to remake in order to use it to change the prices in the table by a percentage:
In short, how can I make an input in the admin panel with which I can update the prices in the tables in database?
maybe there are similar guides, I will be grateful
sql something like this:
update
table1
set
table1.price = (price + price)/100 * input;
select
*
from
table1;
where -> input: num %
You just need to make one dedicated action and ajax handler in your controller.
action to render HTML
ajax handler to handle the request when you submit the form
Note: Please change all the paths and the name according to your plugin
Add action and ajax handler plugins/hardiksatasiya/so/controllers/Items.php
class Items extends Controller
{
// other code ....
public function updateTable() {
// we want to show our menu as active
BackendMenu::setContext('HardikSatasiya.SO', 'main-menu-item-main', 'side-menu-item-update-items');
}
public function onUpdateTableAjax() {
$value = post('update_value');
if(!$value) {
Flash::error("please enter value");
return;
}
// write your table with your logic
Item::query()->update([
'value' => \DB::raw("value * $value")
// please sanitize post input and use here we just used it here as demo
]);
Flash::success("Successfuly updated tabel with value: $value");
}
}
Add HTML markup plugins/hardiksatasiya/so/controllers/items/updatetable.htm
<form
class="form-elements"
data-request="onUpdateTableAjax"
data-request-flash
>
<div class="form-group span-left">
<label>Update Table</label>
<input type="text" name="update_value" value="" class="form-control" />
</div>
<div class="form-group span-left">
<button type="submit" class="btn btn-default">Update Table</button>
</div>
</form>
Now you also need to show this action/html in frontend so the user can go there so we set menu item
update plugins/hardiksatasiya/so/plugin.yaml : side-menu-item-update-items <- we are adding this menu item
plugin:
name: 'hardiksatasiya.so::lang.plugin.name'
description: 'hardiksatasiya.so::lang.plugin.description'
author: hardikSatasiya
icon: oc-icon-star
homepage: ''
navigation:
main-menu-item-main:
label: Items
url: hardiksatasiya/so/items
icon: icon-star
sideMenu:
side-menu-item-main:
label: Items
url: hardiksatasiya/so/items
icon: icon-star
side-menu-item-update-items:
label: Settings
url: hardiksatasiya/so/items/updatetable
icon: icon-sliders
Please check the video for the output result
if any doubt please comment.

Livewire Select2 Dynamic not updating public view

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

vue.js: vue-multiselect, clearing input value after selected

I am working on my project in laravel/vue.js and I decided to use simple vue-multiselect to choose categories from my database. Thing is I want to clear the value from input field (to look for item in list).
My multiselect component:
<multiselect
v-model="value"
placeholder="Find the category"
label="category_name"
:options="categories"
#input="addReceiversFromCategory">
</multiselect>
I try to clear an v-model but it work only on first select after page load (and also it is not a smart way..).
Last thing i try was the :clear-on-select="true" but it works onlu when multiple is true (which I dont want to be true).
I think its simple to do but I didn't find any way in documentation doc
If your v-model is just modeling the value selected, then you need to use that value however you want and reset value to null. I don't really know how your component is set up but it would look something like this:
<template>
<select v-model="value" v-on:change="doSomething()">
<option :value="null">-- Select --</option>
<option value="foo">Foo</option>
<option value="bar">Bar</option>
</select>
</template>
<script>
module.exports = {
data: function(){
return {
value: null
};
},
methods: {
doSomething: function() {
if( this.value ) {
var data = this.value; // now you can work with data
this.value = null; // reset the select to null
}
}
}
}
</script>

VueJS multiple selection

I tried to multiple select with select2
i used laravel and my data on userRoles is returned data on User model with relation roles, and allRoles is just all in Role model
code on view
<select class="form-control" name="roles[]" id="roles" multiple>
<option v-for="role in allRoles"
:value="role.id"
>
#{{ role.name }}
</option>
</select>
how to set selected options using userRoles array?
Add a computed hashMap (object) to search for selected roles:
computed: {
selectedRoleMap() {
var map = {};
this.userRoles.forEach(role => {
map[role] = 1;
});
return map;
}
}
Then add :selected="selectedRoleMap.hasOwnProperty(role.id)" to options.
Working fiddle here: https://jsfiddle.net/df7j8xhz/
Alternatively, you can add a hasRole method to loop through userRoles to see if an id is in userRoles, but build a hashMap and search in it has a better performance than looping the array allRoles.length times.

Resources