select2 remove tag_list item - activeadmin

Trying to get Select2 to remove an item and figure out why it keeps adding a new tag on update.
Using Select2.JS V3.5
Followed ActiveAdmin / Select2 example
When I try to delete an item, it does not remove it. It also ends up combining the tag list to a new STRING creating a new tag. i.e. If I have ["play", "doe"] and I update another field, it creates a new tag called "play doe" resulting in ["play", "doe", "play doe"]. This continues every time I update.
Here's my JS code
// Generated by CoffeeScript 1.9.3
$(document).ready(function() {
$('.tagselect').each(function() {
var placeholder, saved, url;
placeholder = $(this).data('placeholder');
url = $(this).data('url');
saved = $(this).data('saved');
$(this).select2({
tags: true,
placeholder: placeholder,
minimumInputLength: 3,
allowClear: true,
multiple: true,
debug: true,
initSelection: function(element, callback) {
saved && callback(saved);
},
ajax: {
url: url,
dataType: 'json',
data: function(term) {
return {
q: term
};
},
results: function(data) {
return {
results: data
};
}
},
createSearchChoice: function(term, data) {
if ($(data).filter((function() {
return this.text.localeCompare(term) === 0;
})).length === 0) {
return {
id: term,
text: term
};
}
}
});
});
});

Saw https://github.com/mbleigh/acts-as-taggable-on/issues/676
adding the block in my model, fixes the formtastic bug where all tags where coming in as a flat string vs a comma separated string. Monkey Patch for now.
class MyModel < ActiveRecord::Base
...
def tag_list
super.to_s
end
end

Related

Global search is not working in DataTable when server side is enabed in NodeJs

I am trying to get form data from MongoDB server and showing it into data table using nodeJs.I successfully have done server-side pagination using npm Paginate v-2 plugin. But now the searching is not working. Below is my NodeJs and javascript files code. Please help me for searching.
NodeJs code
app.get('/gettable',(req,res)=>{
console.log(req.query);
user.paginate({},{
page:Math.ceil(req.query.start / req.query.length) + 1,
limit:parseInt(req.query.length)
},function(err,result){
var mytable = {
draw:req.query.draw,
recordsTotal:0,
recordsFiltered:0,
data:[],
}
if(err) {
console.log(err);
res.json(mytable);
} else {
if(result.totalDocs > 0) {
mytable.recordsTotal = result.totalDocs;
mytable.recordsFiltered = result.totalDocs;
for(var key in result.docs) {
mytable.data.push([
result.docs[key]['name'],
result.docs[key]['lastname'],
result.docs[key]['email'],
result.docs[key]['pass'],
result.docs[key]['birthdate'],
result.docs[key]['zipcode'],
result.docs[key]['phonenumber'],
]);
}
}
res.json(mytable);
}
});
DisplayTable.Js code
$(document).ready(function(){
$('#example').DataTable({
"processing": true,
"serverSide": true,
"ajax": "http://localhost:8080/gettable"
});
})
As I said, I am successfully getting data from a server and showing into data table with server-side pagination but searching is not working but in searching div whatever I search, I am getting that value in search array, like this
search: { value: 'svs', regex: 'false' },
_: '1548653540009' }
But its not implementing in datatable to filter columns.
As I said in the comment that search will not work out of the box when server side is enabled in DataTable, it is because now the whole functionality, whether sorting, paging, limit, and search has to be implemented in the server. DataTable will only send the parameter needed for doing the functionality. Following is the code just for your reference, it is not tested and you may get an error also. You may get inputs from the following code. Feel free to edit the following code if in case of getting errors so that it can help future readers.
app.get('/gettable',(req,res)=>{
console.log(req.query);
var query = {},
// array of columns that you want to show in table
columns = ['name', 'lastname', 'email', 'pass', 'birthdate', 'zipcode', 'phonenumber',];
// check if global search is enabled and it's value is defined
if (typeof req.query.search !== 'undefined' && req.query.search.value != '') {
// get global search value
var text = req.query.search.value;
// iterate over each field definition to check whether search is enabled
// for that particular column or not. You can set search enable/disable
// in datatable initialization.
for (var i=0; i<req.query.columns.length; i++) {
requestColumn = req.query.columns[i];
column = columns[requestColumn.data];
// if search is enabled for that particular field then create query
if (requestColumn.searchable == 'true') {
query[column] = {
$regex: text,
};
}
}
}
user.paginate(query,{
page:Math.ceil(req.query.start / req.query.length) + 1,
limit:parseInt(req.query.length)
},function(err,result){
var mytable = {
draw:req.query.draw,
recordsTotal:0,
recordsFiltered:0,
data:[],
}
if(err) {
console.log(err);
res.json(mytable);
} else {
if(result.totalDocs > 0) {
mytable.recordsTotal = result.totalDocs;
mytable.recordsFiltered = result.totalDocs;
for(var key in result.docs) {
var data = [];
for(var column in columns) {
data.push(result.docs[key][column]);
}
mytable.data.push(data);
}
}
res.json(mytable);
}
});

Extjs Grid - Click next page button with search condition

I have a gridpanel and i create store in initComponet function like
,initComponent: function() {
var store = Ext.create('Ext.data.Store', {
model: 'MyObject',
autoLoad: false,
pageSize:22,
remoteSort:true,
proxy: {
type: 'ajax',
url: 'example.php',
reader: {
type: 'json',
totalProperty: 'total',
root: 'results'
}
}
});
this.store = store;
this.dockedItems = [{
xtype: 'pagingtoolbar',
store: this.store,
displayMsg: '{0} - {1} / {2}',
emptyMsg: 'empty',
dock: 'bottom',
displayInfo: true,
pageSize: 22
}];
this.callParent(arguments);
this.store.load({params:{start:0, limit:22}});
}
I make a form search with some value and when i press search button i will do below code
grid.store.load({
params:{
start:0,
limit:22,
signalSearch: 1,
search1: myValue1,
search2: myValue2,
}
});
In my php file will catch that to know that's search
if ( have $_REQUEST["signalSearch"]) {
// print json with condition search
}else {
// print json with all data
}
And results return with 2 page (it well). But when i press Next page button to see some results on page 2 But my store load fail (i think they call store.load({params:{start:0, limit:22}}); when i press next page button and in my php file that will run with else case).
That's not call
grid.store.load({
params:{
start:0,
limit:22,
search1: myValue1,
search2: myValue2,
}
});
My idea to make search is not good? How can i fix that thank
If you use params in the "load" function of the store, those are referred to the single request only so if you click next page of the toolbar you won't post the signalSearch param.
You should register a custom listener on the before load event and add your params:
initComponent: function(){
....
this.callParent(arguments);
this.store.addListener('beforeload', function(store, operation){
Ext.apply(operation.params, {
signalSearch: 1 // Or you could make conditions if apply this search param
});
return true;
}, this);
}

extjs4 MVC Scope Issue

I am trying to call resetCombo method once i click on link from tooltip which is rendered on combo
But i am not able to access it because of scope issue not sure what i am missing. Please help me on this.
Ext.define('test.BasicForm', {
extend: 'Ext.form.Panel',
renderTo:Ext.getBody(),
initComponent :function(){
this.items=[
{
fieldLabel: 'Test',
xtype: 'combo',
displayField: 'name',
width: 320,
labelWidth: 130,
store: [
[1, 'Value 1'],
[2, 'Value 2'],
[3, 'Value 3'],
[4, 'Value 4']
],
listeners:{
afterrender: function(combo) {
Ext.create('Ext.tip.ToolTip', {
target: combo.getEl(),
autoHide: false,
name:'tool-tip',
scope:this,
html: 'Old value was '+ combo.getValue()+ ' test',
listeners: {
beforeshow: function() {
return combo.isDirty();
}
}
});
}
},
value:'1'
}];
this.callParent(arguments);
},
resetCombo:function(){
alert('called');
}
});
First this has nothing to do with ExtJS4's MVC features which are generally associated with a controller's control method:
http://docs.sencha.com/ext-js/4-1/#!/api/Ext.app.Controller-method-control
Second, you may be able to instead get the effect you want by switching to the following, fully qualified path to reset combo:
onclick="javascript:test.BasicForm.resetCombo();" //etcetera
Lastly, though you may get the above to work, it is far from best practice. I don't have time to give the complete answer, but essentially what you want to do consists of:
Adding a click event handler to the tooltip's underlying Element
Then inside the element use the arguments to Ext.dom.Element.click (see http://docs.sencha.com/ext-js/4-1/#!/api/Ext.dom.Element-event-click) to ensure it was an <A> tag that got clicked
Then invoke the desired function without having to use Javascript pseudo-URL's and a fully qualified path to the function
Here is my working re-write of the afterrender listener following the above guidelines, with some tweaks to scope, in particular storing a reference to the form in a variable of the same name.
listeners:{
afterrender: function(combo) {
var form = this;
var tooltip = Ext.create('Ext.tip.ToolTip', {
target: combo.getEl(),
autoHide: false,
name:'tool-tip',
html: 'Old value was '+ combo.getValue()+ ' <a class="tooltipHref" href="#">test</a>',
listeners: {
beforeshow: function() {
return combo.isDirty();
},
afterrender: function() {
tooltip.el.on('click', function(event, element) {
if (element.className == 'tooltipHref') {
form.resetCombo();
}
});
}
}
});
},
scope: this
}
test
this code is attempting to call a function named resetCombo which is stored inside the top-level object (the window object).

JqueryUI Autocomplete : only one character is displayed per list item

I'm using jquery-1.4.2.min and jquery-ui-1.8.6.custom to get the autocomplete data on a jsp page, here is the code snippet:
$(document).ready(function() { $("input#airportfrom").autocomplete({minLength: 3,
source: function(request, response) { $.ajax({
url: "MLocationLookupSearchPopUpAuto.action?LANGUAGE=${param.LANGUAGE}&SITE=${param.SITE}&RESULT_FILTER=3",
dataType:"text/html",
data: { MATCH : $("#airportfrom").val() },
success: function(data) { response(data); } }); } }); });
The result returned is correct as I have used an alert(data); inside the success function and it gave correct result, but in the list, it is showing one character or one alphabet per line, hence if I want to get LONDON, it is displayed as:
l
o
n
d
o
n
Any idea why this happening ? Whether we have to give data as json only because here I'm getting the data from a jsp.
Try to split the response data into lines using "\n"
$("#tags").autocomplete({
source: function(request,response) {
$.ajax({
dataType: "text",
url: 'yourscript.php?extraParam=foo',
data: { term: request.term },
success: function(data) {
var lines = data.split("\n");
response(lines);
}
})}
});
I had the same problem and it was down to serializing the object twice (by mistake) on the server side. The JSON data returned to the client was being de-serialized to a string rather than an array.

Autocomplete using values from AJAX

I have a table using tabulator.
Everything works great, but I am trying to get autocomplete working with Ajax
What I am trying is:
var customerNumbers = [];
var table = new Tabulator("#edi-table",
ajaxURL: baseUrl + '/PaginatedEndPoint',
pagination: "remote",
paginationSize: 30,
paginationSizeSelector: [30, 60, 100, 200],
ajaxSorting: true,
ajaxFiltering: true,
selectable: true,
cellEdited: function (cell) {
cell.getElement().style.backgroundColor = "#32CD32";
},
dataLoading: function () {
customerNumbers = ["11", "12", "13"];
},
columns: [
{
title: "CustomerNumber", field: "CustomerNumber", headerFilter: "input", editor: "autocomplete", editorParams: {
searchFunc: function (term, values) {
var matches = [];
values.forEach(function (item) {
if (item.value === term) {
matches.push(item);
}
});
console.log(matches);
return matches;
},
listItemFormatter: function (value, title) {
return "Mr " + title;
},
values: customerNumbers
}
}
]
However, this does not show any predictions value predictions for me, it seems that autocomplete is built before "dataLoading" or any other Callback (I have tried many) is called.
I have tried to make an auxilary array in the style of values like {Title: "Mr + title", value: "title"} and then assign it in the searchFunc, and it didn't work despite being returned in matches.
Is it even possible to dynamically create autofill?
It seems like the current autocomplete functionality does not allow for the editorParams to take a function as an argument to set the dropdown values. You can set it with an object of key/values if you can send that via AJAX, but as far as dynamically setting, altering, or searching the data, it seems like that's impossible to do at the moment.
The other option would be use the editor:"select", which can take a function to set its editorParams. It's not the best solution, but it's the one I had to go with at the moment.
There is an open issue on the Tabulator docs, but so far no response from the developers.
I wish I had a better answer for you!

Resources