ExtJS: How to set defaults for Grid columns within initComponent? - extjs

as you notice below, I'm using Ext.Array.merge to render columns within initComponent.
I'm try to set columns' flex property as default in initComponent.
How can I achieve to this arrangement?
initComponent: function () {
var me = this;
Ext.on('resize', function () { me.height = window.innerHeight - App.MAIN_FOOTER_HEIGHT - App.MAIN_HEADER_HEIGHT - 100 });
me.createGridMenu();
me.columns = Ext.Array.merge(me.getListColsStart(), me.getListCols(), me.getListColsEnd());
//I need to set through here. Any solution such as setDefaults or dot notation to fetch defaults of columns?
me.callParent(arguments);
},
and here is one of overrided functions
getListCols: function () {
return [];
},
UPDATE:
Related second question moved to Setting defaults to panel items for nested objects post. FYI.

Here is an excerpt from the API Docs, from the columns documentation (it also contains an example related to your question):
This can also be a configuration object for a
Ext.grid.header.Container which may override certain default
configurations if necessary. For example, the special layout may be
overridden to use a simpler layout, or one can set default values
shared by all columns:
So, in your case, here is how you can setup flex as a default config for all columns:
me.columns = {
items: Ext.Array.merge(
me.getListColsStart(),
me.getListCols(),
me.getListColsEnd()
),
defaults: {
flex: 1
}
}
EDIT
If the flex property must be applied only to a subset of columns, one way to achieve this is by applying the array map function on the needed subset:
me.columns = Ext.Array.merge(
me.getListColsStart(),
Ext.Array.map(me.getListCols(), function(listColConfig) {
listColConfig.flex = 1;
return listColConfig;
}),
me.getListColsEnd()
)

Related

How can I set default sorter and filters on antd table components?

I am using ant-design react components to make a dashboard and have used a table component where I can define how the filters and sorters once the data is populated.
If have a requirement where I want to apply default sorting(descending) on ID column and in environment column I want prod to be selected by default(to show only prod alerts by default). Since I can't ask usage question on ant-design website, I wanted to know if someone knows about it and can help me with this. I am open to a different approach if you can share.
function onChange(pagination, filters, sorter) {
console.log('params', pagination, filters, sorter);
let order_by = sorter.field;
if (sorter.order == 'descend'){
order_by = `-${order_by}`;
console.log(order_by);
}
let offset = ((pagination.current - 1) * pagination.pageSize);
let url = `${baseUrl}&offset=${offset}&ordering=${order_by}`;
this.fetchResults(url);
}
output for console.log
>>> params Object { showQuickJumper: true, pageSize: 20, current: 1, total: 301 } Object { env: Array['prod'], incident_type: Array['loadChk'] } Object { }
Use defaultSortOrder like defaultSortOrder: 'descend'
You can pass a default the sortOrder value: This can be ascend, descend or false; that would allow you to set a default sort order.
https://ant.design/components/table/#Column
As far as the default filter goes, you need to set the filteredValue prop as #Panther has mentioned above.
You can use defaultFilteredValue for setting a default filter value. Give the value you want to display as a string array.
Eg:
{
title: 'STATUS',
dataIndex: 'status',
key: 'status',
filters: createFilterArray(status),
defaultFilteredValue : ['Open'],
onFilter: (value, filters) => filters.status.indexOf(value) === 0,
},
For default sort use defaultSortOrder. It can take ascend and descend as values.

Access root property in ExtJS custom view? / Duplicate components

For testing purposes, I made 2 views. One that requires the other view. Now I want people to be able to open components multiple times as a tab, so I obviously have to assign unique ID's to each tab and element inside of the component, right?
My question is, how can I access one of the root properties in a view from say the docketItems object?
In the code below, it will cause an undefined this.varindex error at id: 'accountSearchField' + this.varindex,. varindex is dynamically assigned from the other component. (I hardcoded it in the example code below)
Note that I will not know the exact ID, so I can not use something such as Ext.getCmp. I could make use of Ext.ComponentQuery.query('searchAccount') but perhaps there is a better way to do this?
Listed below is a portion of the code that is required by my main component.
Ext.define('cp.views.search.Account', {
extend: 'Ext.panel.Panel',
xtype: 'searchAccount',
varindex: "uniqueid_assigned_by_main_component",
listeners: {
beforerender: function(){
this.id = 'panelSearchAccount' + this.varindex
}
},
items: [
{
xtype: 'grid',
store: {
type: 'Account'
},
id: 'searchAccount' + this.varindex,
columns: [
///
],
dockedItems: [
{
xtype: 'fieldset',
items: [
{
id: 'accountSearchField' + this.varindex,
xtype: 'searchfield'
}
]
}]
}
]
});
Ext will generate IDs for DOM elements and ensure they are unique to the page, so it is unusual to use the id attribute for referencing components. There are two configuration properties with this purpose, itemId and reference.
There are multiple methods that can be used to acquire a component by itemId from a parent container or globally.
Ext.container.Container.getComponent
Ext.container.Container.query
Ext.container.Container.down
Ext.container.Container.child
Ext.ComponentQuery.query
Additionally, components can be acquired by Ext.app.Controllers using the refs configuration. These methods take a selector string. The selector for an itemId is the itemId prefixed with '#' (e.g. '#itemId'). You do not specify the '#' when configuring a component with an itemId.
Introduced along with support for MVVM in Ext JS 5, the reference identifier is unique to the component's container or ViewController. A component can be acquired by reference from components or ViewControllers using lookupReference. The lookupReference method takes only references as input and therefore, does not require a prefix.
If you want to be able to reference a component associated with a particular model instance (account), you can define the component class with an alias and configure the reference or itemId when you add each instance to the container.
for (var i = 0, ilen = accountModels.length; i < ilen; ++i) {
container.add({
xtype: 'accountpanel',
reference: accountModel[i].get('accountNumber')
});
}
In this example, an account's associated panel can be acquired later on using the account number.
var accountPanel = this.lookupReference(accountModel.get('accountNumber'));
Actually I may have figured it out. I simply moved the items inside of the beforerender event and made use of the this.add() function.

Need to set class/id values on buttons in Extjs MessageBox

Our testing team require IDs or class values to be set on the HTML elements in our message popup boxes. This is for their automated tests.
I can pass in a class value for the dialog panel by passing in a cls value like so:
Ext.Msg.show({
title:'Reset Grid Layout',
msg: 'Are you sure that you want to reset the grid layout?',
cls:'Reset-Grid-Layout-Message',
buttons: Ext.Msg.YESNO,
fn: function (response) {
if (response == 'yes') {
}
},
icon: Ext.window.MessageBox.QUESTION
});
Now we also need it on the buttons, and also on the text being displayed. Is there some way of getting a cls value onto the buttons?
I was thinking it may be possible to expand the button parameter into something like :
buttons : [{name:'but1', cls:'asdf'}, {name:'but2', cls:'asdf2'}]
But google is not giving me back anything useful.
If your testing team uses Selenium for their automated test, adding ids/classes in every component could be difficult for both of you.
Overriding components in Ext is a good solution, but I don't recommend this because it will affect all your components. Unless you know what you're doing.
I suggest, extend Ext.window.MessageBox and generate classes for your buttons based on your parent cls.
// Put this somewhere like /custom/messagebox.js
Ext.define('App.MyMessageBox', {
extend: 'Ext.window.MessageBox'
,initConfig: function(config) {
this.callParent(arguments);
}
,makeButton: function(btnIdx) {
var me = this;
var btnId = me.buttonIds[btnIdx];
return new Ext.button.Button({
handler: me.btnCallback
,cls: me.cls + '-' + btnId
,itemId: btnId
,scope: me
,text: me.buttonText[btnId]
,minWidth: 75
});
}
});
To use:
App.Box = new App.MyMessageBox({
cls:'reset-grid-layout'
}).show({
title:'Reset Grid Layout'
,msg: 'Are you sure that you want to reset the grid layout?'
,buttons: Ext.Msg.YESNO
,icon: Ext.window.MessageBox.QUESTION
});
Your buttons will have reset-grid-layout-yes and reset-grid-layout-no class.
You can do the same with other components you have. Check out the Fiddle. https://fiddle.sencha.com/#fiddle/7qb
You should refer to the API
cls : String A CSS class string to apply to the button's main element.
Overrides: Ext.AbstractComponent.cls
You can also use the filter on right side (not the one in the right top corner). Just type cls and you will see all properties, methods and events containing cls (note that you see by default just public members, use the menu on the right of this searchfield to extend this)
Edit
If you just need it for testing purpose I would recommend to override the responsible method. This should work (untested!)
Ext.window.MessageBox.override({
buttonClasses: [
'okCls', 'yesCls', 'noCls', 'cancelCls'
],
makeButton: function(btnIdx) {
var btnId = this.buttonIds[btnIdx];
var btnCls = this.buttonClasses[btnIdx];
return new Ext.button.Button({
handler: this.btnCallback,
cls: btnCls,
itemId: btnId,
scope: this,
text: this.buttonText[btnId],
minWidth: 75
});
}
});

Backgrid formatter adding values from other columns

Is it possible, with BackGrid, to build a custom Cell vía formatter, composing values from hidden columns?
var grid = new Backgrid.Grid({
columns: [
{
name:"half_value_1",
cell:"string",
rendered: false
},
{
name:"half_value_2",
cell:"string",
rendered: false
},
{
name: "composite",
cell: "string",
formatter: _.extend({}, Backgrid.CellFormatter.prototype, {
fromRaw: function (half_value_1, half_value_2) {
return half_value_1 + '/' + half_value_2;
}
})
}],
collection: col
});
Can I get the half_value_1 and half_value_2 inside the fromRaw function?
I think the best way to get the result you want is to use a custom cell rather than a custom formatter. You could do something like this for that particular column:
{
name: "composite",
cell: Backgrid.Cell.extend({
render: function(){
// You have access to the whole model - get values like normal in Backbone
var half_value_1 = this.model.get("half_value_1");
var half_value_2 = this.model.get("half_value_2");
// Put what you want inside the cell (Can use .html if HTML formatting is needed)
this.$el.text( half_value_1 + '/' + half_value_2 );
// MUST do this for the grid to not error out
return this;
}
})
}
That should work perfectly for you - I use it for a handful of grids in my projects. I didn't test this code though, so I may have typos :)
Key

how to delete or add column in grid panel

grid.getcolumnModel().setHidden(0,true) will be effected for column menu
and not grid panel. In column menu u can enable or disable the column. How do we add or remove the column in grid panel dynamically?
I think this is what you are looking for http://www.extjs.com/forum/showthread.php?53009-Adding-removing-fields-and-columns
Make sure you look at post #37 in the thread as well.
For those who reach this question looking for a solution for Ext.js 4.2 and avobe.
I use "reconfigure" method to dynamically change the grid columns: http://docs.sencha.com/extjs/4.2.2/#!/api/Ext.grid.Panel-method-reconfigure
Here is a nice example: http://marcusschiesser.de/2013/12/21/dynamically-changing-the-structure-of-a-grid-in-extjs-4-2/
You may have to refresh the Ext.grid.GridView in order for the column change to show.
grid.getView().refresh(true) // true to refresh HeadersToo
In ExtJs 3.x this piece of code can help:
Note: I have used checkbox, as the first column. Please remove that line if you don't need it.
var newColModel = new Ext.grid.ColumnModel({
columns: [
grid.getSelectionModel(),
{
header: 'New column 1'
}, {
header: 'New column 2'
}
],
defaults: {
sortable: false
}
});
grid.store.reader = new Ext.data.JsonReader({
root: 'items',
totalProperty: 'count',
fields: [
// Please provide new array of fields here
]
});
grid.reconfigure(grid.store, newColModel);
The reconfigure function might not work well with plugins. Especially if you have something like FilterBar.
If you only need to do this once, based on some global settings that use can use initComponent and change your initial config. Be sure to make all changes to the config before calling this.callParent();
Tested with ExtJS 6.2 (but should also work for ExtJS 4 and 5)
initComponent: function() {
// less columns for this setting
if (!app.Settings.dontUseFruits()) {
var newColumns = [];
for(var i=0; i<this.columns.items.length; i++) {
var column = this.columns.items[i];
// remove (don't add) columns for which `dataIndex` starts with "fruit"
if (column.dataIndex.search(/^fruit/) < 0) {
newColumns.push(column);
}
}
this.columns.items = newColumns;
}
this.callParent();
maybe try
store.add(new_record);
store.commitChanges();
or store.remove() and store.commitChanges()

Resources