AG-GRID value formatter not working for dynamically generated currency - ag-grid

I am trying to use a value-formatter in my AG-GRID table for displaying currency information.
This works perfectly when I have a hardcoded value in the formatter, in this case the unicode for 'Euros'
currencyFormatter(params) {
return '\u20ac' + params.value;
}
However, I dont know in advance what currency I will need to format the data in, as it is dynamically generated. If I try an use a value that is available in my component (like below) it doesn't like it!
currencyFormatter(params) {
return this.currencyUnicode + params.value;
}
There it throws in the console is:
TypeError: Cannot read property 'defaultCurrency' of undefined
It seems like all 'this' component variables are not available inside the currencyFormatter. Is there a way to make this work?

In order to access your component variables, you will have to bind your component context - this to the valueFormatter
...
name : 'Currency',
field : 'currency',
valueFormatter: this.currencyFormatter.bind(this) //bind your component's context here
...
currencyFormatter(params) {
return this.currencyUnicode + params.value;
}
This is a common javascript problem. Here is a good read
Also, this answer describes the 2 ways you can reference this.

Related

yup - is there any way to set the default value for a string field to be something without defining it for each one

I want that every time I use yup.string(), it will add a specific default value for it
for example:
const schema = yup.object({
text: yup.string()// I want it to also do .default('some string') in the background,
});
or - another option - is there any way to set the default value after creating the scheme? something like setDefault('text', 'some string')
The closest solution I came across to solve your issue is extending your string with a custom method that implements your needs. To do that you need to use addMethod from yup:
import { addMethod, string } from 'yup';
addMethod(string, 'append', function append(appendStr) {
return this.transform((value) => `${value}${appendStr}`);
});
Now, you can use your custom method (append) and apply it to any string you want:
string().append('~~~~').cast('hi'); // 'hi~~~~'
If you want to add the custom method to all your schema types like date, number, etc..., you need to extend the abstract base class Schema:
import { addMethod, Schema } from 'yup';
addMethod(Schema, 'myCustomMethod', ...)
Extra
For Typescript
In your type definition file, you need to declare module yup with your custom method's arguments and return types:
// globals.d.ts
import { StringSchema } from "yup";
declare module 'yup' {
interface StringSchema<TType, TContext, TDefault, TFlags> {
append(appendStr: string): this;
}
}
Unknow behavior for transform method
While I was trying to extend the functionality of the date schema with a custom method that transform the date that user enters from DD-MM-YYY to YYYY-MM-DD, the custom method broke after I used it with other methods like min, max for example.
// `dayMonthYear` should transform "31-12-2022"
// to "2022-12-31" but for some reason it kept
// ignoring the `cast` date and tried to transform
// `1900` instead!
Yup.date().dayMonthYear().min(1900).max(2100).required().cast("31-12-2022") // error
To work around this issue, I appended my custom method at the end of my schema chain:
Yup.date().min(1900).max(2100).required().cast("31-12-2022").dayMonthYear() // works as expected
This issue is mentioned in this GH ticket which I recommend going through it as it's going more in-depth on how to add custom methods with Typescript.
References
addMethod
Extending built-in schema with new methods
Example of addMethod in Typescript (GH ticket)

ag-grid setModel equivalent of selectValue

Using ag-grid 23.2.1, it looks like our current approach to filtering is on it's way out and listed as deprecated. Reading over the setModel documentation, I don't readily see a way to replace some of our selectValue, selectNothing, etc. usage.
Example 1: we clear the selection and then pick a couple of values on some condition else we select all
let filterInstance = this.gridOptions.api.getFilterInstance('make');
this.cacheFilterModel = this.gridOptions.api.getFilterModel();
if (condition) {
filterInstance.selectNothing();
filterInstance.selectValue('thing1');
filterInstance.selectValue('thing2');
}
else {
filterInstance.selectEverything();
}
filterInstance.applyModel();
this.gridOptions.api.onFilterChanged();
Example 2: we have some filter values in a column toggle-able via checkboxes, which call a method like the below. if one of the values is checked it gets added to the existing filter, if unchecked the value is removed. There could be values already filtered and I don't really see a way to contextually select/unselect values using setModel.
filterExample (make, add) {
let filterInstance = this.gridOptions.api.getFilterInstance('make');
if (add) {
filterInstance.selectValue(make);
}
else {
filterInstance.unselectValue(make);
}
filterInstance.applyModel();
this.gridOptions.api.onFilterChanged();
}
Are there setModel equivalents for these?
I had a similar issue with setColumnFilter where I had to pass a few values. You can use filterInstance.setModel to set these values by passing an array like so:
filterInstance.setModel({ values: ['value1', 'value2'] })
filterInstance.applyModel();
gridOptions.api.onFilterChanged()
here is a link to how to do it from the docs. I found this hard to find on google so providing it here.
https://www.ag-grid.com/javascript-grid-filter-set-api/

How can customData can be binded with JavaScript

In the affected application is a responsive table whose ColumnListItems are added via JavaScript code. Now the lines should be highlighted by the highlighting mechanism depending on their state. The first idea was to control the whole thing via a normal controller function. I quickly discarded the idea, since the formatter is intended for such cases. So I created the appropriate Formatter function and referenced it in the JavaScript code. The call seems to work without errors, because the "console.log" is triggered in each case. Also the transfer of fixed values is possible without problems. However, the values I would have to transfer are located within customData of each line...
No matter how I try to form the path I get an "undefined" or "null" output.
I have already tried the following paths:
"/edited"
"/customData/edited"
"mAggregations/customData/0/mProperties/value"
"/mAggregations/items/0/mAggregations/customData/0/mProperties/value"
The code from Controller.js (with consciously differently indicated paths):
var colListItem = new sap.m.ColumnListItem({
highlight: {
parts: [{
path: "/mAggregations/items/0/mAggregations/customData/0/mProperties/value"
}, {
path: "/edited"
}],
formatter: Formatter.setIndication
},
cells: [oItems]
});
// first parameter to pass while runtime to the formatter
colListItem.data("editable", false);
// second paramter for the formatter function
colListItem.data("edited", false);
oTable.addItem(colListItem);
The code from Formatter.js:
setIndication: function (bEditable, bEdited) {
var sReturn;
if (bEditable && bEdited) {
// list item is in edit mode and edited
sReturn = "Error";
} else if (bEditable || bEdited) {
// list item is in edit mode or edited
sReturn = "Success";
} else {
sReturn = "None";
}
return sReturn;
}
The goal would also be for the formatter to automatically use the value of the model in order to avoid its own implementation of a listener, etc.
I hope one of you has a good/new idea that might bring me a solution :)
Many thanks in advance!
You cannot bind against the customData. Because the customData is located in the element, it is like a property.
Thats why you defined it here on colListItem: colListItem.data("key", value)
You only can bind against a model.
So I see three solutions
Store the information in a separate local JSON model whereof you can speficy your binding path to supply the values to your formatter
Do not supply the information via a binding path to the formatter, but read a model/object/array from a global variable in the controller holding the information via this (=controller) in formatter function
Store the information in the customData of each element and access the element reference in the formatter function via this(=ColumnListItem).data().
Passing the context to the formatter similar to this formatter: [Formatter.setIndication, colListItem]
Cons of 1. and 2: you need a key for a respective lookup in the other model or object.
From what I understand I would solve it with solution 3.

Multiple formatter date options in jqgrid

I have a date field in jqgrid that doesn't sort correctly. The reason is because I my initial formatter:'date' is getting overwritten by my second reference to formatter: function(...).
How do I preserve both pieces of functionality ?
Here is my code:
{name:'FUSInvitedDateX',hidden:true,index:'FUSInvitedDateX',width:'250',
search: true,searchoptions:{sopt:['eq','ne','lt','le','gt','ge'], dataInit:
function(elem) {$(elem).datepicker();}},sorttype: 'date',
formatter:'date',formatoptions: {srcformat: 'm/d/Y', newformat: 'm/d/Y' },
formatter: function(cellvalue, options, rowObject) { return
highlight(cellvalue, options, rowObject, ['FUSScheduledDateX','FUSCompletedDateX','InterviewStatus_DerivedX'],'interview-invite-late');}}
and then in the highlight function I have something like this:
function highlight(cellvalue,options,rowObject,compare,color) {
if (cellvalue.length==0) { return cellvalue; }
[ evaluating code ]
return '<span>' + cellvalue + '</span>';
Any advice would be much appreciated
Sorry but one can't define two properties with the same name in one object. On the other side you included twice the formatter property in the column definition. It's syntax error.
Even if you would remove formatter:'date' and use only custom formatter (formatter callback function) then sorttype: 'date' will not work because jqGrid will be unable to parse the date correctly.
If you really need to use custom formatter (callback function) then you should define sorttype as callback function too. You can parse the input string inside of sorttype function and return it as ISO date (like 2017-06-15).

Richfaces 4 dynamic select options when user type

I am using rich faces select component.
I want dynamic values when user manually type some thing in the select component.
<rich:select enableManualInput="true" defaultLabel="start typing for select" value="#{supplierSearchBean.userInput}">
<a4j:ajax event="keyup" execute="#this" listener="#{supplierSearchBean.userInputChange}"/>
<f:selectItems value="#{supplierSearchBean.selectOptions}" />
</rich:select>
Java code as follows
public void userInputChange(ActionEvent ae){
Map map = ae.getComponent().getAttributes();
System.out.println(map.toString());
}
public void setUserInput(String userInput) {
System.out.println("userINput = " + userInput);
this.userInput = userInput;
}
Here i found 2 issues
1st: setUserINput always print empty string when user type value
2nd: listener method never get call.
any help ?
The problem is most probably that there is no selected value while the user types, and this component restricts the allowed values to the specified select items. A partial input is thus not valid and cannot be bound to your bean.
I think you could get the expected behavior if you use a rich:autocomplete instead. However, if you want to restrict the allowed values, maybe you can keep your rich:select and listen for the selectitem event.
Override getItems function in richfaces-utils.js file in richfaces-core-impl-4.0.0.Final.jar under richfaces-core-impl-4.0.0.Final\META-INF\resources folder.
Change the condition of pushing items to be
if(p != -1)
instead of
if(p == 0)
This should fix the issue.