Format output row data in Vue Good Table - vue.js

I've built a Vue.js component. I have a vue-good-table, where it fetches data from the server. I need to format the output data. Now the data comes with numbers. For example: it's show number 1 as a value. Instead of "1" it has to be ITEM1, for 2 - ITEM2 and so on.
<vue-good-table
:columns="columns"
:rows="formattedItems"
:paginate="true"
:lineNumbers="true">
</vue-good-table>
<script type="text/javascript">
import config from '../main.js'
import moment from 'moment'
export default {
components: {
},
data(){
return {
items: [],
columns: [
{
label: 'Number',
field: 'number',
type: 'String',
filterable: true,
placeholder: 'Number'
},
{
label: 'Name',
field: 'name',
type: 'String',
filterable: true,
placeholder: 'Name'
},
{
label: 'Validity Date',
field: 'validitydate',
type: 'String',
filterable: true,
placeholder: 'dd/mm/yyyy'
},
{
label: 'Authority',
field: 'authority',
type: 'String',
filterable: true,
placeholder: 'Authority'
},
{
label: 'Status',
field: 'status',
type: 'String',
filterable: true,
placeholder: 'Status'
},
{
label: 'Structure',
field: 'structure',
type: 'String',
filterable: true,
placeholder: 'Structure'
},
{
label: 'Type',
field: 'type',
type: 'String',
filterable: true,
placeholder: 'Type'
},
{
label: 'National',
field: 'isnational',
type: 'String',
filterable: true,
placeholder: 'National'
},
],
json_meta: [
[{
"key": "charset",
"value": "utf-8"
}]
]
}
},
methods: {
computed: {
formattedItems () {
if (!this.items || this.items.length === 0) return []
return this.items.map(item => {
return {
...item,
validitydate: item.validitydate === null ? null :
moment(item.validitydate).format('DD/MM/YYYY')
}
})
}
}
}
</script>
I need to do it for columns Authority, Status, Structure, Type and National.
For Authority: 1 - ITEM1, 2 - ITEM2, 3 - ITEM3
For Status: 1 - Status1, 2 - Status2, 3 - Status3
And so on.
Update:
I was wondering for using Map as a way to make it. However, I am not very sure how.

vue-good-table supports a column proprty called formatFn where you can format the data before it shows up on the column.
// in your columns
{
label: 'Authority',
field: 'authority',
type: 'String',
filterable: true,
placeholder: 'Authority',
formatFn: this.formatAuthority,
}
// in your methods
methods: {
formatAuthority(value) {
return `ITEM ${value}`;
}
}
you can see the documentation here:
https://xaksis.github.io/vue-good-table/guide/configuration/column-options.html#formatfn

Related

Invalid property value: API create Mutation Sanity.io Reference is string - how to define as reference?

i am building a ecommerce site.
I have trouble adding orderItems to the Array in the Order-Document.
As you can see i am trying to reference the customer-Document and Product-Dokument in my orderItem. i am Posting in an array of objects that looks like:
[
{
productId: '5b79b3f8-6ef8-4c6d-bd85-5dcb14fb836d',
kundenId: 'c3777230-74cd-411b-a455-7fa905c90957',
quant: 1,
name: 'Position 1'
}
]
Can someone help me how i get sanity to understand the strings as _ref ?
My schemas are as follows:
export default {
title: 'Order Item',
name: 'orderItem',
type: 'object',
fields: [
{
title: 'Name',
name: 'name',
type: 'string',
},
{
name: 'kundenId',
title: 'Customer',
type: 'reference',
to: [{ type: 'customer' }],
options: {
disableNew: true,
},
},
{
name: 'productId',
title: 'Product',
type: 'reference',
to: [{ type: 'product' }],
options: {
disableNew: true,
},
},
{
title: 'Quantity',
name: 'quant',
type: 'number',
},
{
title: 'Price',
name: 'price',
type: 'number',
},
],
};
and:
export default {
name: 'order',
title: 'Order',
type: 'document',
fields: [
{
name: 'user',
title: 'User',
type: 'reference',
to: [{ type: 'user' }],
options: {
disableNew: true,
},
},
{
name: 'userName',
title: 'User Name',
type: 'string',
},
{
title: 'Order Items',
name: 'orderItems',
type: 'array',
of: [
{
title: 'Order Item',
type: 'orderItem',
},
],
},
{
title: 'CreatedAt',
name: 'createdAt',
type: 'datetime',
},
],
};
so i solved this by using JSON.parse like so:
productId: JSON.parse(`{"_ref":"${artikel._id}"}`),
Good luck to everyone with the same issue.

Vue Good Table how to access data in Selected Row Actions

I'm trying to use the checkbox in vue-good-table to select rows, then a button in the selected row action slow to perform a function on the selected rows. How can I access the data?
https://xaksis.github.io/vue-good-table/guide/advanced/checkbox-table.html#selected-row-action-slot
This doesn't work:
<vue-good-table
#on-selected-rows-change="selectAll"
:columns="columns2"
id="shift.id"
:ref="shift.id"
:rows="orderedPlacedUsers(shift)"
:select-options="{
enabled: true,
selectOnCheckboxOnly: true,
}"
>
<div slot="selected-row-actions">
<button class="btn btn__small btn__flat" #click="lockAll(shift)">Lock All <i class="ml-2 fas fa-lock-alt"></i></button>
</div>
</div>
</vue-good-table>
Then
data() {
return {
columns2: [
{
label: '',
field: 'extras',
tdClass: 'text-center',
sortable: false,
},
{
label: 'Name',
field: 'fullName',
},
{
label: 'Signed Up',
field: 'created',
sortable: false,
},
{
label: 'Job',
field: 'requestedJob.title',
tdClass: 'text-center',
},
{
label: '',
field: 'notes',
sortable: false,
tdClass: 'text-center',
},
{
label: '',
field: 'reservations',
tdClass: 'text-center',
tdClass: 'text-center',
sortable: false,
},
{
label: '',
field: 'delete',
tdClass: 'text-center',
sortable: false,
},
]
}
}
methods: {
lockAll(shift) {
console.log(shift.id)
console.log(this.$refs[shift.id].selectedRows)
},
orderedPlacedUsers (shift) {
function compare(a, b) {
if (a.firstName < b.firstName)
return -1;
if (a.firstName > b.firstName)
return 1;
return 0;
}
return this.filteredPlacedUsers.sort(compare).filter(user => {
return user.shift == shift.id && user.day == shift.day
});
},
}
The shift is "shift in eventShifts"... here's what that looks like:
{"day":"2021-08-27","endTime":null,"payrollComplete":true,"startTime":"14:00","event":"Los Bukis","id":"dvaBm5wQXMXvVCGBSK8e","exportedCont":{"seconds":1631208172,"nanoseconds":886000000},"collapse":false,"position":{"title":null},"selectedStaff":null,"eventId":"CGHMVzcKPnNLsmRxoeVj","exportedEmp":{"seconds":1631208185,"nanoseconds":622000000},"name":"Line Cook","staff":"50"}
Thank you!
To access the vue-good-table via this.$refs you need to add :ref property into vue-good-table.
<vue-good-table
:id="shift.id"
:ref="shift.id"
>
</vue-good-table>
But there is another thing to be considered, it says here that
When used on elements/components with v-for, the registered reference
will be an Array containing DOM nodes or component instances.
In your case, probably vue-good-table is used on an element/component with v-for. So, you can access it via this.$refs[shift.id][0]. Finally, you can print the selectedRows using console.log(this.$refs[shift.id][0].selectedRows)

Filter query result by field value inside array of objects [Sanity.io & GROQ]

I'm trying to find a product variant inside my list of products(on sanity.io using GROQ), to do so, I have the sku of the variant that I want.
The query I'm using is
*[_type == "product" && variants[].sku.current =="kit-kat-wasabi-5" ]
But this query returns an empty array. I'm sure that the sku is correct because if I leave the filter aside, and fetch all I can find it.
I tried replacing the "==" with match, but the result is the same.
my schemas are
procuct
export default {
name: 'product',
title: 'Product',
type: 'document',
fields: [
{
name: 'title',
title: 'Inner Title',
type: 'string'
},
{
title: 'SKU',
name: 'sku',
type: 'slug',
options: {
source: 'title',
maxLength: 96
},
validation: Rule => Rule.required()
},
{
name: 'titleWebsite',
title: 'Title Website',
type: 'localeString'
},
{
name: 'active',
title: 'Active',
type: 'boolean'
},
{
name: 'mainImage',
title: 'Imagem',
type:"image"
},
{
name: 'slug',
title: 'Slug',
type: 'slug',
options: {
source: 'title',
maxLength: 96
}
},
{
title: 'Base Price',
name: 'basePrice',
type: 'localeCurrency'
},
{
title: 'Quantidade',
name: 'qty',
type: 'number'
},
/* {
title: 'Default variant',
name: 'defaultProductVariant',
type: 'productVariant'
},*/
{
title: 'Variants',
name: 'variants',
type: 'array',
of: [
{
title: 'Variant',
type: 'productVariant'
}
]
},
{
title: 'Tags',
name: 'tags',
type: 'array',
of: [
{
type: 'string'
}
],
options: {
layout: 'tags'
}
},
{
name: 'vendor',
title: 'Vendor',
type: 'reference',
to: {type: 'vendor'}
},
{
name: 'blurb',
title: 'Blurb',
type: 'localeString'
},
{
name: 'categories',
title: 'Categories',
type: 'array',
of: [
{
type: 'reference',
to: {type: 'category'}
}
]
},
{
name: 'body',
title: 'Body',
type: 'localeBlockContent'
}
],
preview: {
select: {
title: 'title',
manufactor: 'manufactor.title',
media: 'mainImage'
}
}
}
And productVariant
export default {
title: 'Product variant',
name: 'productVariant',
type: 'object',
fields: [
{
title: 'Title',
name: 'title',
type: 'string'
},
{
title: 'Title Website',
name: 'titleWebsite',
type: 'localeString'
},
{
title: 'Weight in grams',
name: 'grams',
type: 'number'
},
{
title: 'Price',
name: 'price',
type: 'localeCurrency'
},
{
title: 'SKU',
name: 'sku',
type: 'slug',
options: {
source: 'title',
maxLength: 96
},
validation: Rule => Rule.required()
},
{
title: 'Taxable',
name: 'taxable',
type: 'boolean'
},
{
name: 'blurb',
title: 'Blurb',
type: 'localeString'
},
{
name: 'images',
title: 'Images',
type: 'array',
of: [
{
type: 'image',
options: {
hotspot: true
}
}
]
},
{
title: 'Quantidade',
name: 'qty',
type: 'number'
},
{
title: 'Bar code',
name: 'barcode',
type: 'barcode'
}
]
}
This is a known bug in GROQ when traversing arrays. This will introduce breaking changes if it were to be fixed in GROQ v1. It will therefore be fixed in GROQ v2.
Here is a bug report explaining the issue: https://github.com/sanity-io/sanity/issues/1557. You can show your interest in this problem here.
There's a working draft for version two here: https://github.com/sanity-io/groq.
Regarding your schema, I would consider to change the type of the sku field to be something else, for example a string, and create a new field for the slug which has its source property set to the SKU to be automatically be generated by that field. Documentation for that can be found here: https://www.sanity.io/docs/slug-type.

vue good table - 3 requests to the service

I use vue-good-table object to render table in Vue.js. I use paging and sorting serverside.
My code:
<vue-good-table v-if="authorizations"
id="AuthorizationsTable"
ref="refToAuthorizationsTable"
#on-page-change="onPageChange"
#on-sort-change="onSortChange"
#on-column-filter="onColumnFilter"
#on-per-page-change="onPerPageChange"
mode="remote"
:columns="columns"
:rows="authorizations"
:totalRows="totalRecords"
:pagination-options="{
enabled: true,
mode: 'pages',
nextLabel: 'następna',
prevLabel: 'poprzednia',
ofLabel: 'z',
pageLabel: 'strona',
rowsPerPageLabel: 'wierszy na stronie',
allLabel: 'wszystko',
dropdownAllowAll: false
}"
:sort-options="{
enabled: true,
initialSortBy: {
field: 'id',
type: 'asc'
}
}">
(...)
export default {
name: 'AuthoritiesAdministration',
components: {},
data() {
return {
totalRecords: 0,
serverParams: {
columnFilters: {},
sort: {
field: 'id',
type: 'asc'
},
page: 1,
perPage: 10
},
rows: [],
columns: [
{
label: 'ID',
field: 'id',
type: 'number',
tdClass: 'vue-good-table-col-100'
},
{
label: 'Data wystawienia',
field: 'issueDate',
formatFn: this.formatDate,
tdClass: 'vue-good-table-col-200',
},
{
label: 'Nazwa operatora',
field: 'operator',
sortable: true,
formatFn: this.formatOperatorName,
},
{
label: 'Login',
field: 'operator.login'
},
{
label: 'Spółka',
field: 'company.description',
type: 'text',
},
{
label: 'Data ważności',
field: 'endDate',
type: 'text',
formatFn: this.formatDate,
},
{
label: 'Akcje',
field: 'btn',
tdClass: 'vue-good-table-col-250',
sortable: false
}
],
}
},
(...)
methods: {
updateParams(newProps) {
this.serverParams = Object.assign({}, this.serverParams, newProps);
},
onPageChange(params) {
this.updateParams({page: params.currentPage});
this.loadAuthorizations();
},
onPerPageChange(params) {
this.updateParams({
perPage: params.currentPerPage
});
this.loadAuthorizations();
},
onSortChange(params) {
this.updateParams({
sort: {
type: params[0].type,
field: params[0].field
}
});
this.loadAuthorizations();
},
onColumnFilter(params) {
this.updateParams(params);
this.loadAuthorizations();
},
loadAuthorizations() {
getAllAuthorizationsLightWithPagination(this.$store.getters.loggedUser.token, this.serverParams).then(response => {
this.totalRecords = response.data.totalRecords;
this.rows = response.data.authorizations;
}).catch(err => {
this.$showError(err, true);
});
},
I have noticed that there are sent 3 requests to the server instead of 1: there are called methods like onPageChange, onPerPageChange and onSortChange but only the first time when my page is loaded. It is unnecessary. I have one method in "mounted" section where I load the first 10 results (sorting and paging by default). It's common, well-known problem with vue-good-table? Or maybe should I add an additional flag to not to invoke these 3 methods unnecessarily when the page is loaded?
Your onSortChange method is called at the table loading because you made a initialSortBy with specific values. To remove this calling juste remove
initialSortBy: {
field: 'id',
type: 'asc'
}
from you table configuration, but your sort will not be set, so I think this should be a legit function call.
The onPerPageChange and onPageChange are triggered by the config below
:pagination-options="{
enabled: true,
...
}
just remove the colon before pagination-options to have a config like this
pagination-options="{
enabled: true,
...
}

Setting the reader on a extjs store

I have a store on extjs4 that return a list of objects, and i want to set the reader property to be able to count the elements so i can use paging afterward.
For reference, the example that extjs use already comes with a count property(totalCount) and the type of object listed(topics), while mine dont have it, just the list.
for reference:
example
Also, in my code the grid doesnt recognize the limit of results per page, but the paging toolbar does:
var sm = Ext.create('Ext.selection.CheckboxModel');
Ext.define('Cliente', {
extend: 'Ext.data.Model',
fields: [{
name: 'ID',
type: 'int'
}, {
name: 'Nome',
type: 'string'
}, {
name: 'Email',
type: 'string'
}, {
name: 'RazaoSocial',
type: 'string'
}, {
name: 'TipoDeCliente',
type: 'string'
}],
idProperty: 'ID'
});
var store = Ext.create('Ext.data.Store', {
pageSize: 3,
model: 'Cliente',
remoteSort: true,
proxy: {
type: 'ajax',
url: 'http://localhost:4904/Cliente/ObterClientes',
extraParams: {
nome: '',
tipopessoa: '',
email: '',
cpf: '',
estado: '',
cidade: '',
cep: ''
},
reader: {
type: 'json',
root: 'data'
},
simpleSortMode: true
},
sorters: [{
property: 'Email',
direction: 'DESC'
}]
});
var pluginExpanded = true;
var grid = Ext.create('Ext.grid.Panel', {
width: 500,
height: 250,
title: 'Array Grid',
store: store,
selModel: sm,
loadMask: true,
viewConfig: {
id: 'gv',
trackOver: false,
stripeRows: false
},
columns: [{
id: 'gridid',
text: "ID",
dataIndex: 'ID',
hidden: true
}, {
text: 'Nome',
width: 150,
sortable: true,
dataIndex: 'Nome'
}, {
text: 'Tipo de Cliente',
width: 100,
sortable: true,
dataIndex: 'TipoDeCliente'
}, {
text: 'Email',
width: 150,
sortable: true,
dataIndex: 'Email'
}],
bbar: Ext.create('Ext.PagingToolbar', {
store: store,
displayInfo: true,
displayMsg: 'Exibindo clientes {0} - {1} of {2}',
emptyMsg: "Nenhum cliente"
}),
renderTo: 'clientes',
});
store.loadPage(1);
The store needs the total count to calculate the paging parameters and to show the total. Your server side implementation must change to add that count with your data.
Also load the data like this store.load(); instead of loadPage.
EDIT: you also have an extra comma here: renderTo: 'clientes', I would suggest running your code through JSLint.