Multiselect search whole string - search

I have a multiselect with search bound to a store (with attribute string_value). Search only searches strings that start with "string to search" instead of contains "string to search" (similar to searching for '%string%' instead of 'string%'). Is there a way to do this by extending 'multiselector-search'?
Below is my multiselector control bound to a form:
var ms = Ext.widget('form', {
xtype: 'multi-selector',
width: 400,
height: 300,
requires: [
'Ext.view.MultiSelector'
],
layout: 'fit',
renderTo: Ext.getBody(),
items: [{
bbar: [{
xtype: 'button',
itemId: 'button',
html: 'Toolbar here',
text: 'Submit request to API',
// get submitted array
handler: function() {
if (cardioCatalogQT.config.mode === 'test') {
console.log('In submitted values handler: ');
}
var submitted = Ext.getCmp('test');
var dx = [];
Ext.Array.each(submitted.store.data.items, function (item) {
dx.push(item.data.string_value);
}); // each()
Ext.Msg.alert('Submitted Values',
'The following diagnoses will be sent to the server: <br
/>' + dx);
if (cardioCatalogQT.config.mode === 'test') {
console.log(dx);
}
}
}],
xtype: 'multiselector',
title: 'Selected Dx',
id: 'test',
name:'test',
fieldName: 'string_value',
viewConfig: {
deferEmptyText: false,
emptyText: 'No Dx selected'
},
// TODO: fix ability to remove selected items when box is unchecked
search: {
field: 'string_value',
store: 'Diagnoses'
}
}]
}).center();
The closest I could find to this problem was http://www.sencha.com/forum/showthread.php?240887. I tried making it work with the multiselect search with no success.

The MultiSelector uses the Ext.util.Filter to narrow the results based on the typed text. You need to enable the anyMatch property for it to match anywhere.
To do that, you'll have to include a new "search" function in your multiselector's search object that will have anyMatch=true.
Please see my fiddle, https://fiddle.sencha.com/#fiddle/jf5, for an example of how to do this.

Related

Why is the Tabulator getRows() function not working?

This seems like the simplest of requests but I can't seem to retrieve a set of rows from a Tabulator object.
Here's the code which instantiates the Tabulator object.........
function TabulatorInvitees(divId, companyName, userEmail) {
try {
var table = new Tabulator(divId, {
columns: [
{
title: "<div style='width:20%; float:left; text-align:left; color:blue; font-size:14px;'>Vendor Invitees</div>",
columns: [
{ title: "Id", field: "Id", visible: false },
{ title: "Added", field: "Added", visible: false },
{ title: "Changed", field: "Changed", visible: false },
{ title: "MarkedForExclusion", field: "MarkedForExclusion", visible: false },
{ title: "Email Address", field: "Email", widthGrow: 1, responsive: 0, hozAlign: "center", editor: "input", visible: true },
{ title: "First Name", field: "FirstName", widthGrow: 0.5, responsive: 1, hozAlign: "center", editor: "input", visible: true },
{ title: "Last Name", field: "LastName", widthGrow: 0.5, responsive: 1, hozAlign: "center", editor: "input", visible: true }
]
},
{
title: tabulatorAddUser(companyName),
field: "ManageRows",
widthGrow: 0.25,
responsive: 2,
hozAlign: "center",
formatter: "tickCross",
headerClick: function (e, row) {
row.getTable().addRow({ Id: 0, Added: true }, false);
},
cellClick: function (e, cell) {
tabulatorFreezeUnfreezeDelete(cell.getRow());
}
},
],
data: [],
height: "100%",
layout: "fitColumns", // required when using 'widthGrow'
placeholder: tabulatorPlaceholder(companyName), //display message to user on empty table
reactiveData: true, //enable reactive data
responsiveLayout: "collapse",
rowContextMenu: tabulatorContextMenu(),
});
table.on("rowTapHold", function (e, row) {
// from Tabulator documentation: "The rowTapHold event is triggered when a user taps on a row on a touch display and holds their finger down for over 1 second."
//e - the tap event object
//row - row component
tabulatorContextMenu();
});
table.on("tableBuilt", function () {
if (companyName.length > 0) {
table.setData(getDataSync({ caseSelector: "VendorMgmt_EmployeeList", companyCode: companyName, userEmail: userEmail }));
}
else {
table.setData([]);
}
});
}
catch (error) {
console.log(error);
}
}
The setData() function makes a call to a database function which returns three rows, similar to the following:
The following JQuery function is called when a radio button is clicked....
$(".vendorStatus").click(function (e) {
const status = e.target.value;
const tbls = Tabulator.findTable("#divVendorEmployees");
const tbl = tbls[0];
const tblRows = tbl.getRows();
console.log("tbls.length", tbls.length);
console.log("tblRows", tblRows);
});
The browser console indicates a table has been found (tbls.length = 1) but the tblRows array is empty:
I see the three rows in my Tabulator but I am not able to recall them programmatically. It seems like a simple problem which should have a simple answer.
I am using the most recent version of Tabulator (v5.4).
Any assistance is greatly appreciated.
After much searching, I finally came to the realization the DOM element associated with the Tabulator instance must be managed when attempting to refresh or replace data. I've implemented a method which allows me to delete and rebuild the DOM element each time I need to save data to my database and subsequently refresh my Tabulator instance.
Here's the code...
function refreshTabulatorObject(obj) {
let parentId = obj.parentId;
let childId = obj.childId;
//Empty and remove the current version of the [Tabulator] object.
const tables = Tabulator.findTable(childId);
if (tables.length > 0) {
var table = Tabulator.findTable(childId)[0];
table.setData([]);
}
//Remove the existing <div> from the DOM.
$(childId).remove();
//Re-create the <div> element for the [Tabulator] object and append it to the DOM.
var parentDiv = document.getElementById(parentId);
parentDiv.innerHTML = "";
var childDiv = document.createElement("div");
childDiv.setAttribute("id", childId);
parentDiv.appendChild(childDiv);
//Re-create the [Tabulator] object.
TabulatorInvitees("#" + childId, obj.companyName);
}
I'm sure those of you with a more intimate knowledge of Tabulator would likely suggest a more elegant method, however, this one appears to work and I've already spent far more time on this issue that I had anticipated. Unfortunately, elegance is not a luxury I can afford at this point.
I hope this solution might be of help to some other struggling soul.

jTable dynamic custom toolbar item in child table

I have a jTable with a child table for each row. On the toolbar header of the child table I have added a custom toolbar item. I want to make that toolbar item dynamic in the sense that if there are already some rows I do not want it to show. I came across a very similar query for the main toolbar "add new" button which added a function to run on recordsLoaded:
Below is my first attempt - it is just the field entry for the main table that specifies the child table. However the ".find(....)" spec will not work in my case as mine is a custom toolbar item. What do I need to put as the .find criteria?
Thanks
Dance: {
title: '',
width: '4%',
sorting: false,
create: false,
listClass: 'centreCol',
display: function(book) {
var $img = $('<img src="Images/layers.png" title="Show associated dance entries" />');
//Open child table when user clicks the image
$img.click(function() {
var thisrow = $img.closest('tr'); //Parent row
if($('#BookTableContainer').jtable('isChildRowOpen',thisrow)) { // Clicking image a second time closes the child row
$('#BookTableContainer').jtable('closeChildRow',thisrow);
} else {
currentTitleID = book.record.DanceTitleID;
$('#BookTableContainer').jtable(
'openChildTable',
thisrow,
{
title: 'Related Dance',
toolbar: {
items: [
{
icon: 'Images/add.png',
text: 'New dance',
tooltip: 'Add dance details',
click: function() { CreateDanceDialog(); }
}
]
},
actions: {
listAction: 'BookPageData.php?action=listChildDances&DanceTitleID=' + currentTitleID,
// createAction: 'dancesData.php?action=createAssignment',
// deleteAction: 'dancesData.php?action=deleteAssignment'
},
recordsLoaded: function(event, data) {
var rowCount = data.records.length;
if (rowCount>0){
$('#BookTableContainer').find('.jtable-toolbar-item.jtable-toolbar-item-add-record').remove();
}
},
fields: {
DanceID: { key: true, create: false, edit: false, list: false, visibility: 'hidden' },
DanceTitleID: { type: 'hidden', defaultValue: currentTitleID },
ChoreographerID: { title: 'Choreographer', width: '40%', options: function() { return ChoreographerOptions; } },
FormationID: { title: 'Formation', width: '30%', options: function() { return FormationOptions; } },
GenreID: { title: 'Genre', width: '30%', options: function() { return GenreOptions; } }
}
},
function(data) { data.childTable.jtable('load'); }
);
}
});
//Return image to show on the person row
return $img;
}
},
Try this
$('#BookTableContainer').find('.jtable-toolbar').remove();

Adding a column to a dstore backed dgrid

I have a grid with five columns - username, email, enabled, locked and remove.
Username, email, enabled and locked are sourced from the server. Remove is a client-side element used to indicate that a row should be removed.
I would like to either inject the default value of remove in the store on the client side as the grid content is loading, or set it as the user interacts with the CheckBox widget.
How can I catch the code which is requesting the objects from the server and add another column?
Or, is there a better way to do this.
var TrackableRest = declare([Rest, SimpleQuery, Trackable]);
var store = new TrackableRest({target: '/api/users', useRangeHeaders: true, idProperty: 'username'});
aspect.after(store, "fetch", function (deferred) {
return deferred.then(function (response) {
response.remove = false;
return json(response);
})
});
var grid = new (declare([OnDemandGrid, Selection, Editor]))({
collection: store,
className: "dgrid-autoheight",
columns: {
username: {
label: core.username
},
email: {
label: core.email
},
enabled: {
label: core.enabled,
editor: CheckBox,
editOn: "click",
sortable: false,
renderCell: libGrid.renderGridCheckbox
},
locked: {
label: core.locked,
editor: CheckBox,
editOn: "click",
sortable: false,
renderCell: libGrid.renderGridCheckbox
},
remove: {
editor: CheckBox,
editorArgs: {"checked": false},
editOn: "click",
label: core.remove,
sortable: false,
className: "remove-cb",
renderHeaderCell: function (node) {
var inp = domConstruct.create("input", {id: "cb-all", type: "checkbox"});
return inp;
},
renderCell: libGrid.renderGridCheckbox
}
},
selectionMode: "none"
}, 'grid');
In addition, I don't want to send the remove column to the server.
My final implementation was to code the remove column like so:
remove: {
editor: CheckBox,
label: core.remove,
sortable: false,
className: "remove-cb",
renderHeaderCell: function (node) {
var inp = domConstruct.create("input", {id: "cb-all", type: "checkbox"});
return inp;
}
}
The code to perform the removes is as follows:
var removeBtn = new Button({
label: core.remove
}, 'user-remove-btn');
removeBtn.startup();
removeBtn.on("click", function (event) {
var markedForDeletion = query(".dgrid-row .remove-cb input:checked", "user-grid");
if( markedForDeletion.length > 0 ) {
lib.confirmAction(core.areyousure, function () {
markedForDeletion.forEach(function (node) {
var row = grid.row(node);
store.remove(row.data.username);
});
});
}
});
Thus the remove column became a client-side only control that was handled by the grid and the event handler.

Grid store config throws "Uncaught TypeError: Cannot read property 'buffered' of undefined"

I have form and grid. the user must enter data in form fields then display related records in the grid.
I want to implement a search form, e.g: user will type the name and gender of the student,
then will get a grid of all students have the same name and gender.
So, I use Ajax to send form fields value to PHP and then create a json_encode which will be used in grid store.
I am really not sure if my idea is good. But I haven't found another way to do that.
The problem is there is a mistake in my store but I couldn't figure out what it is. I get this error:
Uncaught TypeError: Cannot read property 'buffered' of undefined
My View:
{
xtype: 'panel',
layout: "fit",
id: 'searchResult',
flex: 7,
title: '<div style="text-align:center;"/>SearchResultGrid</div>',
items: [{
xtype: 'gridpanel',
store: 'advSearchStore',
id: 'AdvSearch-grid',
columns: [{
xtype: 'gridcolumn',
dataIndex: 'name',
align: 'right',
text: 'name'
}, {
xtype: 'gridcolumn',
dataIndex: 'gender',
align: 'right',
text: 'gender'
}
],
viewConfig: {
id: 'Arr',
emptyText: 'noResult'
},
requires: ['MyApp.PrintSave_toolbar'],
dockedItems: [{
xtype: 'PrintSave_tb',
dock: 'bottom',
}]
}]
}
My Controller:
.
.
.
xmlhttp.open("GET","AdvSearch.php?search_name="+search_name,true);
xmlhttp.send(null);
My PHP script:
if (!$con) {
throw new Exception("Error in connection to DB");
}
$query ="SELECT name, gender FROM students WHERE name ILIKE '%$search_name%' ";
$result = pg_query($query);
while ($row = pg_fetch_array($result)) {
$Arr[] = array('name' => $row[0], 'gender' => $row[1]);
}
$searchResult_list = array();
$searchResult_list['success'] = true;
$searchResult_list['Arr'] = $Arr;
$searchResult_list['totalCount'] = count( $searchResult_list['Arr'] );
echo json_encode($searchResult_list);
if (!$result)
die("Error in query: " . pg_last_error());
pg_close($con);
My Store, Model:
Ext.define('AdvSearchPost', {
extend: 'Ext.data.Model',
proxy: {
type: 'ajax',
url: 'AdvSearch.php',
reader: {
type: 'json',
root: 'Arr',
totalProperty: 'totalCount'
}
},
fields: [{
name: 'name'
}, {
name: 'type_and_cargo'
}
]
});
advSearchStore = Ext.create('Ext.data.Store', {
pageSize: 10,
model: 'AdvSearchPost'
});
Well it is just a typo of your storename.
The error Uncaught TypeError: Cannot read property 'buffered' of undefinedonly indicates that the store could not be bound. It may be a bit misleading.
Try the grid with either
store: advSearchPost
or
store: Ext.StoreMgr.lookup('AdvSearchPost') // if in any form a controller takes care about your store
and it will work.
Edit
I guess you haven't any controller so I recommend you to create your store like this
Ext.create('Ext.data.Store', {
pageSize: 10,
model: 'AdvSearchPost',
storeId: 'AdvSearchPost'
});
That will enable you to receive the store by the StoreManager from everywhere (after it is created). That will also enable the last statement to work without any controller.
Even if you call like this..
store: Ext.StoreMgr.lookup('bla bla bla') won't throw any error in the console.
Replace store parameter with storeId and then assign your actual store to it which will connect to your actual store. storeId:advSearchPost

Ext JS 4: Custom object property value based on condition

I'm trying to create custom property values (based on a condition of a function) for my Ext objects, instead of specifying just a value.
Example 1:
old code (working)
this.buttons = [
{
text: 'Save',
new code (not working)
this.buttons = [
{
text: function() {
return 'Save X';
},
Example 2:
old code (working)
}, {
width: 270,
labelAlign: 'right',
xtype: 'textfield',
name: 'user_id',
fieldLabel: 'User ID',
hidden: true
}]
new code (not working)
}, {
width: 270,
labelAlign: 'right',
xtype: 'textfield',
name: 'user_id',
fieldLabel: 'User ID',
hidden: function() { return true; }
}]
Example 3:
Ignore entire textfield object (lazy instance) completely based on a condition:
}, {
width: 270,
labelAlign: 'right',
xtype: 'textfield',
name: 'employee_number',
fieldLabel: 'Employee Number'
}]
You simply can't do it this way. It is not possible to replace a type with a function. In your case you assign a function reference to a variable which is expected to be boolean, same for the string.
Solution A.
You should consider to write yourself a field factory. Within that factory you can then execute any function before assigning configs. (Sort of same then B but can be used to reduce function calls)
Solution B.
Use a function reference itself. This one should then get executed. (spare the requirement of class extension and is over that reuseable)
// The data store containing the list of states
var states = Ext.create('Ext.data.Store', {
fields: ['abbr', 'name'],
data : [
{"abbr":"AL", "name":"Alabama"},
{"abbr":"AK", "name":"Alaska"},
{"abbr":"AZ", "name":"Arizona"}
//...
]
});
Ext.namespace('my.util.helper');
my.util.helper.decideHide = function() { return true; }
// Create the combo box, attached to the states data store
Ext.create('Ext.container.Container', {
renderTo: Ext.getBody(),
items: [{
xtype: 'combo',
fieldLabel: 'Choose State',
store: states,
queryMode: 'local',
displayField: 'name',
valueField: 'abbr',
test: my.util.helper.decideHide(),
listeners: {
afterrender: function(n) {
alert(n.test);
}
}
}]
});
Solution C.
And the solution I use most in such cases are simplified if else statements
// ... // more code
{
    text: myCondition ? 'Text A' : 'Text B',
// more code
}
// ... // more code
Yeah that is not going to work, some Ext configs take a function that will be evaluated but most of them don't. Instead of creating anonymous functions and not invoking them I would do something like this:
Ext.define('UserPanel', {
extend : 'Ext.panel.Panel',
initComponent : function() {
this.items = [{
xtype : 'button',
text : this._getSaveButtonText()
}, {
width : 270,
labelAlign : 'right',
xtype : 'textfield',
name : 'user_id',
fieldLabel : 'User ID',
hidden : this._isUserIdHidden()
}]
this.callParent();
},
_getSaveButtonText : function() {
return 'Save';
},
_isUserIdHidden : function() {
return true;
}
});

Resources