How to set a default value for <v-select> that will update value if user changes the selection in Vue.js - vuejs2

I have searched online and have not found an answer to this Vue.js question.
I am pretty new to Vue.js. In my form, there is a drop down for end time which gives a choice of times to choose from. The default for this field is 30 minutes after start time, but the user can change this value. For now, the user is able to change the displayed time for end time, but the data property end_time is not getting changed. I need this value to update (not just stay at the default) so I can use it to calculate duration from start time to end time. Code is below. Thanks for the help in advance.
v-select:
<v-select
:items="times"
:value="getEndTime"
label="End Time"
box
placeholder="End Time"
></v-select>
part of my data object (note: end_time)
export default {
data: () => ({
date: new Date().toISOString().slice(0,10),
menu2: false,
times: [],
start_time: '',
end_time: '',
from methods: section:
getStartTimeIndex()
{
// looking for index of start_time in times array
var startTimeIndex=0;
for(var x =0; x<this.times.length;x++)
{
if(this.times[x] == this.start_time)
{
startTimeIndex = x;
break;
}
}
return startTimeIndex;
}
from computed: section:
getEndTime()
{
var startTimeIndex = this.getStartTimeIndex();
//if start time is set and end time is not:
if (this.start_time != '' && this.end_time == '')
{
this.end_time = this.times[startTimeIndex + 2]; // two 15 min. increments is 1/2 hr. later
console.log("getEndTime(): startTimeIndex = " + startTimeIndex);
}
return this.end_time;
}

Use component's change event:
<v-select
:items="times"
:value="getEndTime"
label="End Time"
box
placeholder="End Time"
#change="changeEndTime"
></v-select>
In methods:
changeEndTime(value)
{
this.$set(this, 'end_time', value);
},

Related

How to use two arrays in Vuetifyes v-autocomplete

I have two arrays, one with 7 boolean values representing the weekdays, and the other with the weekdays names and the value of which day of the week it represents, kind of index of weekdays (0 beeing sunday, and 6 beeing saturday)
This sample is from the ts file belonging to the vue file where the autocomplete is.
export const scheduleDays: TextValueViewModel[] = [
{ Text: "Mon", Value: 1},
{ Text: "Tue", Value: 2 },
{ Text: "Wed", Value: 3 },
{ Text: "Thu", Value: 4 },
{ Text: "Fri", Value: 5 },
{ Text: "Sat", Value: 6 },
{ Text: "Sun", Value: 0 }
];
This is from a view model I have containing this array with booleans representing the weekdays.
public readonly SelectedDays: boolean[] = [false,false,false,false,false,false,false];
I then have a autocomplete where I want to save the clicked checkboxes and that would be saved into the boolean array
<v-autocomplete
v-model="editedReleaseSchedule.ScheduleInterval.SelectedDays"
:items="scheduleDays"
:item-text="item => `${item.Text}`"
:item-value="item => `${item.Value}`"
:label="'ADMINISTRATION_RELEASE_SCHEDULE_DETAILS_SCHEDULED_DAYS' | translate('Selected days')"
:disabled="formDisabled"
:rules="[rules.required]"
outlined
hide-details
multiple
dense
/>
How can I make the clicked value of the weekday array beeing saved into the boolean array in the right index spot? And at the same time I want the correct checkboxes be checked in the autocomplete field.
The implemented auto complete in the interface
Using Vue 2 at my workplace, so no solution for vue 3 would work out for me.
I've tried to google if I can get the index of the v-autocomplete row and use that in item-value like:
editedReleaseSchedule.ScheduleInterval.SelectedDays[index]
but that does not seem possible. I've also tried different ways of filtering before using v-autocomplete, but I still want the whole list, not only the clicked (marked) once.
Use an intermediate model for the selectedValues, watch it, and map the selected values ([1,2,3...,0]) into the real model.
data: () => ({
selectedValues: [],
// ...
<v-autocomplete
v-model="selectedValues"
<!-- etc -->
watch: {
selectedValues(newValues) {
const allFalse = [false,false,false,false,false,false,false];
this.editedReleaseSchedule.ScheduleInterval.SelectedDays = allFalse;
newValues.forEach(value => {
// presumes sunday is the last index, the others are offset by +1
let j = value === 0 ? 6 : value-1;
this.editedReleaseSchedule.ScheduleInterval.SelectedDays[j] = true;
})
},

How to show icon next to value in cloumn in aurelia slickgrid/slickgrid?

I want to show en edit icon next to value in Amount column. This is because the Amount column is actually editable.But to give that as a hint to user, i want to show some edit icon next to it. How to do that in aurelia slickgrid?
Or maybe there is a way to highlight a field on hover ?
I am using aurelia slickgrid and looking if there is some option in aurelia slickgrid itself.
Go to the aurelia slickgrid example link and click on the link of example's source code
When you open it, there is a method called defineGrids
/* Define grid Options and Columns */
defineGrids() {
this.columnDefinitions1 = [
...,
...,
...,
...,
...,
{ id: 'effort-driven', name: 'Effort Driven', field: 'effortDriven', formatter: myCustomCheckmarkFormatter, type: FieldType.number, sortable: true, minWidth: 100 }
];
... rest of the code
}
The row with id effort-driven is where the icons are placed. On the other words, when you push a data collection(usually array of json object) to the table, values of the data objects with key name effort-driven are given to column with id effort-driven. Furthermore, for each passed value to the column, the method myCustomCheckmarkFormatter reformat it(for example 0 -> false or null -> not filled) and place it to the corresponding table's cell. look at the below method:
// create my custom Formatter with the Formatter type
const myCustomCheckmarkFormatter: Formatter<DataItem> = (_row, _cell, value) => {
// you can return a string of a object (of type FormatterResultObject), the 2 types are shown below
return value ? `<i class="fa fa-fire red" aria-hidden="true"></i>` : { text: '<i class="fa fa-snowflake-o" aria-hidden="true"></i>', addClasses: 'lightblue', toolTip: 'Freezing' };
};
As you can see, when the method is called, it returns an icon such as <i class="fa fa-fire red" aria-hidden="true"></i> which is placed in the table's cell.
I added an edit icon next to Amount,
{
id: "Edit",
field: "edit",
excludeFromColumnPicker: true,
excludeFromExport: true,
excludeFromQuery: true,
excludeFromGridMenu: true,
excludeFromHeaderMenu: true,
minWidth: 30,
maxWidth: 30,
formatter: Formatters.editIcon,
},
and used this custom format from ghiscoding comment:
const customEditableInputFormatter: Formatter = (_row, _cell, value, columnDef, dataContext, grid) => {
const isEditable = !!columnDef.editor;
value = (value === null || value === undefined) ? '' : value;
return isEditable ? `<div style="background-color: aliceblue">${value}</div>` : value;
};
The result is as shown in the picture.

How to create correct rule for validating zero via vee-validate

"vee-validate": "^2.2.11",
"vue": "^2.5.16",
I need a simple rule, the rule should be that the input must be required,numeric and greater than 0.
So in this case, if I input 0 it validates correctly(return false), but if I input something like this 0.0 vv returns true. Even if I remove is_not:0, the result still the same.
<sui-input
type="text"
v-validate="'required|decimal|is_not:0'"
name="cellSize"
v-model="cellSize">
You could also create a custom rule, like follows.
created() {
this.$validator.extend(
'greaterThanZero',{
getMessage: field => field + ' needs to be > zero.',
validate: (value) => {
// value must be > zero
if (value > 0 ) return true;
return false;
}
});
},
then call the code on your field instance.
v-validate="'required|decimal|greaterThanZero'"
more on custom rules here:
https://vee-validate.logaretm.com/v2/guide/custom-rules.html#creating-a-custom-rule
or you could also use this following style (if you were going to add more than one rule for example). Here the code would be inserted in the area where you do your imports, i.e. directly after the script tag.
import { Validator } from 'vee-validate';
Validator.extend(
'greaterThanZero',
(value) => {
// value must be > zero
if (value > 0 ) return true;
return false;
}
);
let instance = new Validator({ greaterThanZeroField: 'greaterThanZero' });
you can now add a second rule to the style directly above using the following code:
instance.extend('greaterThan1Million', {
getMessage: field => field +' needs to be > 1,000,000',
validate: value => (value > 1000000 ? true : false)
});
instance.attach({
name: 'greaterThan1MillionField',
rules: 'greaterThan1Million'
});
again that second rule could be called as follows:
v-validate="'required|decimal|greaterThan1Million'"
I found this solution(to leave everything greater than 0)
<sui-input
type="text"
v-validate="{ required: true, regex: /^(?=.*[1-9])\d+(\.\d+)?$/ }"
name="cellSize"
v-model="cellSize">
</sui-input>
Did you try to use a regex to exclude 0 ?
Example:
<input v-validate="{ required: true, regex: /[1-9]*/ }">

ChartJS Unix Time Values changed

I'm importing data from a Sybase database into ChartJS in VueJs2. I'm using the vue-chart module
I push the timestamps into an array as Unix times using
this.firstIn(new Date(tnaDetails[0].Sunday_FirstIn).getTime())
So:
[Sunday_FirstIn:2010-01-17 08:00:00.0]
Would convert to
1263708000000
Which I then add to the dataset:
datasets: [{
type: 'line',
label: "First In",
backgroundColor: "green",
data: this.firstIn,
fill: false
}
]
However, when the data is plotted on the graph, the values are changed. The above Unit Timestamp becomes
1263700000000
Which obviously returns the wrong time. I'm not doing anything to the ticks in the options.
Below is a result of the numbers being changed. The console has the original data:
Is there a setting that alters the precision/values of numbers in ChartJS that I'm not aware of?
Thanks.
Seth
For anyone who has any similar problem in future, I patched together a few solutions I found.
Firstly, from here Unix Timestamp in JavaScript, I wrote the method:
getTimeString: function(dateString) {
var hours = new Date(dateString).getHours();
var mins = new Date(dateString).getMinutes();
return Math.round((new Date("1970-02-01 " + hours + ":" + mins)).getTime());
}
The important part here is to make sure you have the same day. Not doing this will cause the ChartJS graph to plot the times in different places on the y-axis, even if the hours are the same.
Then from this StackOverFlow question and the related plunker, in the chart options, I have:
{
responsive: true,
maintainAspectRatio: false,
scales: {
yAxes: [{
position: 'left',
ticks: {
callback: value => {
let date = moment(value);
if (date.diff(moment('1970-02-01 23:59:59'), 'minutes') === 0) {
return null;
}
return date.format('H:mm');
},
stepSize: 3.6e+6
}
}]
}, //end scales
tooltips: {
callbacks: {
label: function(toolTipItem, data) {
let date = moment(toolTipItem.yLabel);
if (date.diff(moment('1970-02-01 23:59:59'), 'minutes') === 0) {
return null;
}
return date.format('H:mm');
}
}
}
}
Pay attention to the callbacks. They will format the time, calculating the difference from a set time to the time you need plotted. In the first function, you could really use any day, it wouldn't matter, as long as it's the same day. The stepSize will display hourly intervals on the yAxis.

Dojo gridx: using "onAfterRow" disables "onCellWidgetCreated"?

When creating a gridx, I use the following column definition to insert an Edit button in to the last cell of each row:
var editColumn = { field : 'Edit', name : '', widgetsInCell: true,
onCellWidgetCreated: function(cellWidget, column){
var btn = new Button({
label : "Edit",
onClick : function() {
console.log('Do stuff here');
});
btn.placeAt(cellWidget.domNode);
}
};
columns.push(editColumn);
var grid = new Grid({
cacheClass : Cache,
store : store,
structure : columns,
modules: ["gridx/modules/CellWidget"]
}, 'gridNode');
grid.body.onAfterRow = function(row){
...do stuff on the row here
};
Whne I include the onAfterRow function the row processing happens but the OnCellWidgetCreated does not. Each function seems wo work in absence of the other. Any suggestions on how I can: (1) format the rows according to row data AND (2) insert the button widgets in the last cell of each row?
Ok, solved it. Rather than assign the grid.body.onAfterRow, the way that worked for me was:
aspect.after(grid.body,'onAfterRow',function(row){
key = row.id;
if ('anulada' in row.grid.store.get(key)){
if(row.grid.store.get(key).anulada == true){
row.node().style.color = 'gray';
}
}
},true);
You need to require "dojo/aspect".