Ag-grid - Events and Methods (Vuejs) - vue.js

I can't use the "save" method to save a change to my table data
I am using the "cellValueChanged" method to edit and save a table cell.
<ag-grid-vue :cellValueChanged="save"></ag-grid-vue>
methods: {
save() {
const method = this.instituicao.id ? 'put' : 'post'
const id = this.instituicao.id ? `/${this.instituicao.id}` : ''
axios[method](`${baseApiUrl}/instituicao${id}`, this.instituicao)
.then(() => {
this.$toasted.global.defaultSuccess()
this.reset()
})
.catch(showError)
},
Error message:
enter image description here

To achieve expected result, use event callback of #cell-value-changed
Change your event to #cell-value-changed = "save"
Use event callback to get old and new values of cell
save(event) {
console.log('onCellValueChanged: ' + event.oldValue + ' to ' + event.newValue);
}
Get required id value from that event callback and use it for POST call

Related

Vue VeeValidate - How to handle exception is custom validation

I have a custom validation in VeeValidate for EU Vat Numbers. It connects to our API, which routes it to the VIES webservice. This webservice is very unstable though, and a lot of errors occur, which results in a 500 response. Right now, I return false when an error has occured, but I was wondering if there was a way to warn the user that something went wrong instead of saying the value is invalid?
Validator.extend('vat', {
getMessage: field => 'The ' + field + ' is invalid.',
validate: async (value) => {
let countryCode = value.substr(0, 2)
let number = value.substr(2, value.length - 2)
try {
const {status, data} = await axios.post('/api/euvat', {countryCode: countryCode, vatNumber: number})
return status === 200 ? data.success : false
} catch (e) {
return false
}
},
}, {immediate: false})
EDIT: Changed code with try-catch.
You can use:
try {
your logic
}
catch(error) {
warn user if API brokes (and maybe inform them to try again)
}
finally {
this is optional (you can for example turn of your loader here)
}
In your case try catch finally block would go into validate method
OK, first of all I don't think that informing user about broken API in a form validation error message is a good idea :-| (I'd use snackbar or something like that ;) )
any way, maybe this will help you out:
I imagine you are extending your form validation in created hook so maybe getting message conditionaly to variable would work. Try this:
created() {
+ let errorOccured = false;
Validator.extend('vat', {
- getMessage: field => 'The ' + field + ' is invalid.',
+ getMessage: field => errorOccured ? `Trouble with API` : `The ${field} is invalid.`,
validate: async (value) => {
let countryCode = value.substr(0, 2)
let number = value.substr(2, value.length - 2)
const {status, data} = await axios.post('/api/euvat', {countryCode: countryCode, vatNumber: number})
+ errorOccured = status !== 200;
return status === 200 ? data.success : false;
},
}, {immediate: false})
}
After searching a lot, I found the best approach to do this. You just have to return an object instead of a boolean with these values:
{
valid: false,
data: { message: 'Some error occured.' }
}
It will override the default message. If you want to return an object with the default message, you can just set the data value to undefined.
Here is a veeValidate v3 version for this:
import { extend } from 'vee-validate';
extend('vat', async function(value) {
const {status, data} = await axios.post('/api/validate-vat', {vat: value})
if (status === 200 && data.valid) {
return true;
}
return 'The {_field_} field must be a valid vat number';
});
This assumes your API Endpoint is returning json: { valid: true } or { valid: false }

Computed prop returning undefined

I have a prop in a component that I want to pass with eventHub to a sibling component where I want to display the prop. However I can't make it to work and it always returns undefined.
<div class="user-menu">
{{getUsername != undefined ? 'Logged in as ' + getUsername + '!' : 'Not logged in'}}
</div>
computed: {
getUsername(){
var getUser;
this.$eventHub.$on('current-user', username => {
getUser = username
})
return getUser;
}
}
A computed property is not the right tool for the job here. You just need a data property:
data () {
return {
getUsername: null
}
},
created () {
this.$eventHub.$on('current-user', username => {
this.getUsername = username
})
}
Depending on how the event hub is created you would likely also need to remove the event listener when the component is destroyed.

Is v-bind called when referencing a component in Vue?

I have an upload component that submits after a message has been sent. In that component I have an action that states the request URL which is v-binded. However, every time I call the reference, the v-bind seems to not trigger and just gives me a blank. I'm using Element UI btw.
HTML
<el-upload :action="latestMessageAttachmentUrl" ref="uploadFiles"></el-upload>
JS
submitMessage () {
// Submit data to server
return api.createMessage( messageToSend, ( message ) => {
this.latestMessageAttachmentUrl = './messages/' + message.id + '/attachments';
this.$refs.uploadFiles.submit();
} );
}
Because Vue does not update View right update when data changes so you should submit in nextTick
submitMessage () {
// Submit data to server
return api.createMessage( messageToSend, ( message ) => {
this.latestMessageAttachmentUrl = './messages/' + message.id + '/attachments';
this.$nextTick(() => {
this.$refs.uploadFiles.submit();
})
} );
}

Get data object on row click

I am using jquery datatables and I am having trouble grabbing the row data on click event. How can I get my data object from my datatable on row click event?
What I do:
jquery post to get a json response load json response as data into datatable (array of objects)
jquery, register click event on
datatable rows when user clicks on row, need to get data object for
row clicked on
My current code:
function contactSearchListTable(data) {
// data is array of javascript object
console.log('contactSearchListTable()');
$(contactSearchResultsTableElement + ' tbody').off();
if ( $.fn.dataTable.isDataTable(contactSearchResultsTableElement) ) {
$(contactSearchResultsTableElement).DataTable().destroy();
}
if (data.length == 0) {
$(contactSearchResultsTableElement).html('');
}
var table = $(contactSearchResultsTableElement);
var params = {"data":data
,"info": false
,"searching": false
,"ordering": false
,"lengthChange": false
,"columns":[
{"data":"id","visible":false}
,{"data":"name","title":"Name","class":"clickable"}
,{"data":"phoneHome","title":"Home","class":"clickable"}
,{"data":"phoneWork","title":"Work","class":"clickable"}
]
};
var dt = table.dataTable(params);
$(contactSearchResultsTableElement + ' tbody').on('click', 'tr', function () {
console.log(this); // <tr> html from datatable
// **** need to get hidden ID value here, HOW?
} );
}
You can access the data using row().data() function, change you click handler to:
$(contactSearchResultsTableElement + ' tbody').on('click', 'tr', function (){
var data = dt.api().row(this).data();
});

How to call a method from controller in extjs

I have a bar column chart.. I want when I click on the column then the value of it will be shown and call another function where i will call the database thru ajax.
When I click on the column the value is shown but the 2nd part i.e. the 2nd function call is not done..
here is my controller code...
initializedEvents: false,
init: function() {
this.control({
'#barColumnChart': {
afterlayout: this.afterChartLayout
}
});
},
afterChartLayout: function(){
if(this.initializedEvents==true) return;
this.initializedEvents=true;
Ext.getCmp('barColumnChart').series.items[0].on('itemmousedown',function(obj){
var barData=obj.storeItem.data['source']+ ' &' + obj.storeItem.data['count'];
// I want to call the dataBaseCall function here
});
},
dataBaseCall: function(barData){
alert(barData);
}
Try this
afterChartLayout: function(){
var me = this;
if(this.initializedEvents==true) return;
this.initializedEvents=true;
Ext.getCmp('barColumnChart').series.items[0].on('itemmousedown',function(obj){
var barData=obj.storeItem.data['source']+ ' &' + obj.storeItem.data['count'];
me.dataBaseCall(barDat);
});
},
dataBaseCall: function(barData){
alert(barData);
}
You can also add the controller scope to the event but I personally prefer this.