Change the index of an array in array push - laravel

In the application, we implemented the laravel-vue-pagination and in our pagination our columns are checkbox and paid amount(input field) where the checkbox is what user want to pay the item.
Once the page is load, it will save in one variable which is called items.
We have an event on clicking the checkbox where when the user check it will push to another variable which is called selected_items. When it is uncheck it will remove the value in the selected_items
getPerSelectedItems(i,purchase_item_id){
if(this.items.data[i].checked == true)
{
this.selected_items.push({
amount_due: this.items.data[i].amount_due,
balance: this.items.data[i].balance,
checked: this.items.data[i].checked,
date_due: this.items.data[i].date_due,
net_of_vat: this.items.data[i].net_of_vat,
number: this.items.data[i].number,
paid_amount: this.items.data[i].paid_amount,
purchase_item_id: this.items.data[i].purchase_item_id,
purchase_tag: this.items.data[i].purchase_tag,
selected_chart_of_account: { id: this.items.data[i].selected_chart_of_account.id, name: this.items.data[i].selected_chart_of_account.code+" : "+this.items.data[i].selected_chart_of_account.name },
selected_responsibility_center: { id: this.items.data[i].selected_responsibility_center.id, name: this.items.data[i].selected_responsibility_center.name },
selected_wht_list: { id: this.items.data[i].selected_wht_list.id, name: this.items.data[i].selected_wht_list.name, rate: this.items.data[i].selected_wht_list.rate },
total_amount_payable: this.items.data[i].total_amount_payable,
total_wht: this.items.data[i].total_wht,
transaction: this.items.data[i].transaction,
transaction_id: this.items.data[i].transaction_id,
wht_payable: this.items.data[i].wht_payable,
with_tax: this.items.data[i].with_tax
})
}else{
this.selected_items = this.selected_items.filter(function( obj ) {
// return obj.purchase_item_id !== this.items.data[i].purchase_item_id;
return obj.purchase_item_id !== purchase_item_id;
});
}
},
For example I checked the two items, the variable items will look like this.
Below is the selected_items.
Now my question is it possible to change the index of selected_items? In my example above, the selected_items should be like this
selected_items: [
5: {},
6: {}
]
Not like this
selected_items: [
0: {},
1: {}
]

Javascript array cant skip indexes or have "string indexes". A Javascript Array is exclusively numerically indexed. When you set a "string index", you're setting a property of the object.
If you set the index 5 and 6 of an array, it will look like this.
selected_items: [
0: undefined,
1: undefined,
2: undefined,
3: undefined,
4: undefined,
5: {},
6: {}
]

this.selected_items.push() will always set numeric key index.
You should use this to set a specific index.
this.selected_items[i] = this.items.data[i];

Related

How can I specify a Yup error on a validating field's parent schema?

I'm trying to set up a validation schema to use with Formik. I have a combobox that has items of shape { id: number; value: string; } and pulls the value out to display to the user, while submitting the whole item to Formik/Yup. However, in production, I won't know the shape of my items ahead of time; this is just the shape I've chosen for demoing.
const items = [
{ id: 1, value: 'foo' },
{ id: 2, value: 'bar' },
];
const [ field, meta, helpers ] = useField('value');
return (
<ComboBox
{...field}
invalid={meta.touched && !!meta.errors}
invalidText={meta.errors}
items={items}
itemToString={i => i?.value ?? ''}
onChange={data => helpers.setValue(data.selectedItem)}
selectedItem={field.value}
/>
);
I want to make only id = 1 to be valid.
const validationSchema = Yup.object({
value: Yup.object({
id: Yup.number().oneOf([1], "You've selected an invalid option."),
value: Yup.string(),
})
.required('You have not selected an option.')
.nullable(),
});
However, when this is in the error state, meta.errors is set to { id: "You've selected an invalid option." }. invalidText expects a ReactChild so when it receives this object, React throws an error.
I assume the solution, then, is to move .oneOf() to outside of the inner Yup.object(). I don't know how to specify the valid values, however, and neither the documentation nor a quick search of SO helped. Thoughts?

How to Programmatically append slots in vuejs app

I have a requirement to use vue js slot to inject the content anywhere in the dom.
The component is going to have props as below -
1. in: The target element. Should be able to accept a string selector, or an element as object.
2. as: Defines one of the insert modes: (append, prepend, replace, fill)
I am still looking for solution how the slot will be rendered in the given selector and inserted as per given insert mode. Below is my slot component -
MySlotComponent.vue:
<script>
export default {
props: {
in: {
type: [String, Object],
default: 'body'
},
as: {
type: String,
default: 'append'
}
},
render(h) {
return this.$scopedSlots.default();
},
}
</script>

Semantic-ui form rule only if option is selected

I am using semantic ui and am trying to do some form validation with it.
The scenario I have is the user has 2 options: email,or phone app verrifcation. They select one of the options and enter whatever in a text field then click submit.
However I am not sure how to do rules on this with semantic UI.
I know if I wanted to check if it was blank I could do something like this:
$('.ui.form')
.form({
fields: {
CODE: {
identifier: 'code',
rules: [
{
type : 'empty',
prompt : 'Please enter your verification code'
}
]
}
} } );
However I would like additional rules based upon which option is selected. I have javascript that currently tells me the value of what is selected, and is updated on change. Unsure how to add it into the rules though, so that I can be like -- If phone was select, must be exactly 6 chars long, or IF email was selected, must be 18 chars long (different lengths for different option).
Is there a way to have conditional rules like this? Closet I could find was:
depends: 'id'
Which checks to ensure it is not empty.
Does anyone know how to have conditional rules such as this based on another form element? I am using the most recent version of Semantic-UI
You can do so by adding custom rules.
$.fn.form.settings.rules.atLeastOne = function (value, fields) {
fieldsToCompare = fields.split(",")
if (value) {
// current input is not empty
return true
} else {
// check the other input field(s)
// atLeastOne is not empty
atLeastOne = false
for (i = 0; i < fieldsToCompare.length; i++) {
// gets input based on id
if ($("#" + fieldsToCompare[i]).val()) {
atLeastOne = true
}
}
return atLeastOne
}
}
$(".ui.form").form({
fields: {
number:{
identifier: "number",
rules: [{
type: "exactLength[6]",
prompt: "number has to be 6 chars long"
}, {
// include the input fields to check atLeastOne[email, address, ...]
type: "atLeastOne[email]",
prompt: "Please provide an email or a number"
}]
},
email: {
identifier: "email",
rules: [{
type: "exactLength[18]",
prompt: "email has to be 18 chars long"
}, {
type: "atLeastOne[number]",
prompt: "Please provide an email or a number"
}]
}
}
});
Note that the function uses the input id as the identifier and not the input name. You might also want to look at optional fields.

bootstrap-typeahead's displayfield using multiple values

I'm sorry if this is a duplicate question but I do not understand the answers of other people. I'm using Twitter Bootstrap Ajax Typeahead Plugin (https://github.com/biggora/bootstrap-ajax-typeahead/) to search emails from data that comes from an SQL query. This is the code I use with a php file, where I use people's emails as valueField and people's names as displayField and it works well.
inputSearch.typeahead({
ajax: {
url: urlAjax + '?requete=rechercheannuaire',
displayField: "description",
valueField: "id",
triggerLength: 2,
method: "get",
loadingClass: "loading-circle",
preProcess: function(data){
if(data.type === "error")
{
return false;
}
return data.datas;
}
},
onSelect: function(data){
//alert("assez tot");
data.text = data.value;
//console.log(data);
$("#chercherinvite").val(data.text);
return data;
}
});
The problem is that I have to be able to search "Dujardin" as well as "Du Jardin" and I cannot find a way to assign multiple values to displayField. If someone could explain how typeahead works, I'd be thankfull, I don't understand the documentation.
According to the plugin documentation, you cannot assign multiple values to the displayField option. However, it is possible for you to re-write events.
After a quick lookup into the source code of bootstrap-ajax-typeahead, we can figure out that the "matcher" event is used as the filter for displaying - or not - values to the user.
To allow to match both "Du jardin" and "Dujardin", we have to manipulate strings. Here, I suggest you to :
Remove any diacritic character
Remove any non-word character (all except [A-Za-z0-9_])
Remove any underscore
Set the string to lowercase
To do #1, I suggest you to use this fantastic script by rdllopes.
I wrote a POC. Here is the JSON source (called "source.json"):
[
{ "id": 1, "name": "jdupont#example.com - Jean Du Pont"},
{ "id": 2, "name": "jdupont2#example.com - Jean Dupont"},
{ "id": 3, "name": "jdupont3#example.com - Jéan Dupônt"},
{ "id": 4, "name": "mbridge#example.com - Michel Bridge"}
]
And here is the script that I used for matching elements :
$('#search').typeahead({
// Our source is a simple JSON file
ajax: 'source.json',
// Display field is a list of names
displayField: 'name',
// And value field a list of IDs
valueField: 'id',
matcher: function(item)
{
// For both needle and haystack, we :
// 1. Remove any diacritic character
// 2. Remove any non-word character (all except [A-Za-z0-9_])
// 3. Remove any underscore
// 4. Set the string to lowercase
var needle = removeDiacritics(this.query).replace(/[^\w]/gi, '').replace('_', '').toLowerCase();
var haystack = removeDiacritics(item).replace(/[^\w]/gi, '').replace('_', '').toLowerCase();
// Does the needle exists in haystack?
return ~haystack.indexOf(needle);
}
});

KendoUI Grid: Array as a field

I have a data source, which gets built from a JSON data string, containing a field called Fruit:
[{
... /other entries
fruit: [{
name: 1
}, {
name: 2
}, {
name: 3
}]
}]
I'm using this field in a KGrid, and would like to do a comma seperated list of links, from the names:
1, 2, 3
Currently, I'm hooking into the dataBound function, and build this up individually for the fruit field, is there an easier way to do this with, let's say, a template? I tried to look up information about something similar in the docs, but couldn't find anything pertaining to splitting arrays?
I wouldn't transform the data at the data source. That job is the responsibility of the UI component. Instead move your logic to the column template function of your grid. [ API reference ]
$('#grid').kendoGrid({
columns: [ {
field: 'fruit',
template: function(dataItem) {
var html = [];
for (var i = 0; i < dataItem.length; i++) {
html.push('' + dataItem[i].name + '');
}
return html.join(', ');
}
}],
dataSource: data
});

Resources