Unable to create a delete button in Meteor using reactive-table - javascript

I building a sortable table in Meteor with Reactive-Table and having trouble getting my delete button to work for removing entries from the table.
Please see my javascript code below:
Movies = new Meteor.Collection("movies");
if (Meteor.isClient) {
Template.body.events({
"submit .new-movie": function (event) {
var title = event.target.title.value;
var year = event.target.year.value;
var genre = event.target.genre.value;
Movies.insert({
title: title,
year: year,
genre: genre
});
event.target.title.value = "";
event.target.year.value = "";
event.target.genre.value = "0";
return false;
}
});
Template.moviestable.events({
"click .deletebtn": function (event) {
Movies.remove(this._id);
}
});
Template.moviestable.helpers({
movies : function () {
return Movies.find();
},
tableSettings : function () {
return {
showFilter: false,
fields: [
{ key: 'title', label: 'Movie Title' },
{ key: 'year', label: 'Release Year' },
{ key: 'genre', label: 'Genre' },
{ key: 'edit', label: 'Edit', fn: function () { return new Spacebars.SafeString('<button type="button" class="editbtn">Edit</button>') } },
{ key: 'delete', label: 'Delete', fn: function () { return new Spacebars.SafeString('<button type="button" class="deletebtn">Delete</button>') } }
]
}
}
});
}
Can anyone tell me what I'm doing wrong?

In the reactive tables docs, there's an example of how to delete rows from the table. Adapting the example in the docs for your needs, your event should look like this:
Template.moviestable.events({
'click .reactive-table tbody tr': function (event) {
event.preventDefault();
var objToDelete = this;
// checks if the actual clicked element has the class `deletebtn `
if (event.target.className == "deletebtn") {
Movies.remove(objToDelete._id)
}
}
});
The problem you are having is that you are trying to find the _id property on the button click instead of the row click.
If you do console.log(this) on your button click event (as you have it in your question above) you will get something like this Object {key: "delete", label: "", fieldId: "2", sortOrder: ReactiveVar, sortDirection: ReactiveVar} which does not contain the property _id
It is easier to register the row click, where the row object is the actual document you are trying to delete, and then check if the event's target has the delete class you added.

Related

How to get selected checkbox based on first selected dropdown after refresh the page?

I have dropdown, checkboxes and button submit. First, the user will choose at dropdown (position of work). Second, the user will select the checkbox and after that submit the data. Here, after refresh it should be appear back the previous selected dropdown and checkbox. But, I did not get it. Anyone here have more better solution?
JavaScript Dropdown
//dropdown position
$("#dropdown").kendoDropDownList({
optionLabel: "- Select Position -",
dataTextField: "functionName",
dataValueField: "hrsPositionID",
dataSource: {
transport:{
read: {
url: "../DesignationProgramTemplate/getData.php",
type: "POST",
data: function() {
return {
method: "getDropdown",
}
}
},
},
},
change: onChange
}).data('kendoDropDownList');
dropdownlist = $("#dropdown").data("kendoDropDownList");
Checkbox treeview (Kendo UI)
homogeneous = new kendo.data.HierarchicalDataSource({
transport: {
read: {
url: serviceRoot,
dataType: "json"
}
},
schema: {
model: {
id : "ehorsProgramID",
hasChildren: false,
children : "items"
}
},
filter: { field: "module", operator: "startswith", value: "Accounting" }
});
$("#AccountingTree").kendoTreeView({
check: onCheck,
checkboxes: { checkChildren: true } ,
// select: onSelect,
dataSource: homogeneous,
dataBound: function(){
this.expand('.k-item');
},
dataTextField: ["module","groupname","ehorsProgramName"]
});
AJAX for submit button
//AJAX call for button
$("#primaryTextButton").kendoButton();
var button = $("#primaryTextButton").data("kendoButton");
button.bind("click", function(e) {
var test = $("#dropdown").val()
$.ajax({
url: "../DesignationProgramTemplate/getTemplate.php",
type: "post",
data: {'id':test,'progid':array},
success: function () {
// you will get response from your php page (what you echo or print)
kendo.alert('Success'); // alert notification
//refresh
//location.reload("http://hq-global.winx.ehors.com:9280/ehors/HumanResource/EmployeeManagement/DesignationProgramTemplate/template.php");
},
});
});
JavaScript for check checkboxes
function checkedNodeIds(nodes, checkedNodes) {
for (var i = 0; i < nodes.length; i++) {
if (nodes[i].checked) {
checkedNodes.push(nodes[i].id);
}
if (nodes[i].hasChildren) {
checkedNodeIds(nodes[i].children.view(), checkedNodes);
}
}
}
var array = [];
function onCheck() {
var checkedNodes = [],treeView = $("#AccountingTree").data("kendoTreeView"),message;
var checkedNodes2 = [],treeView2 = $("#AdminSystemTree").data("kendoTreeView"),message;
var checkedNodes3 = [],treeView3 = $("#FnBTree").data("kendoTreeView"),message;
var checkedNodes4 = [],treeView4 = $("#HumanResourceTree").data("kendoTreeView"),message;
var checkedNodes5 = [],treeView5 = $("#InventoryManagementTree").data("kendoTreeView"),message;
var checkedNodes6 = [],treeView6 = $("#SalesMarketingTree").data("kendoTreeView"),message;
checkedNodeIds(treeView.dataSource.view(), checkedNodes);
checkedNodeIds(treeView2.dataSource.view(), checkedNodes);
checkedNodeIds(treeView3.dataSource.view(), checkedNodes);
checkedNodeIds(treeView4.dataSource.view(), checkedNodes);
checkedNodeIds(treeView5.dataSource.view(), checkedNodes);
checkedNodeIds(treeView6.dataSource.view(), checkedNodes);
if (checkedNodes.length > 0) {
message = checkedNodes.filter(x => !!x).join(",");
array = checkedNodes.filter(x => !!x);
} else {
message = "No nodes checked.";
}
}
Output
JavaScript for accessing the dataItem
// cookies
var values = ["LA1","LA6","LA12"]; //array nnti array ni la localstorage/cookies
var setTreeViewValues = function(values) {
var tv = $("#AccountingTree").data("kendoTreeView");
document.write(JSON.stringify(tv));
tv.forEach(function(dataItem) {
alert("test");
if (dataItem.hasChildren) {
var childItems = dataItem.children.data();
//document.write(JSON.stringify(childItems[0].items[0].programID));
}
// document.write(JSON.stringify(dataItem.items));
if (values.indexOf(childItems[0].items[0].programID) > -1) {
dataItem.set("checked", true);
}
});
};
setTreeViewValues(values);
console.log(datasource.data()[0].hasChildren);
// end cookies
So without knowing how you are binding the existing values to the page I am assuming you will be calling the page state somewhere within your Page loading.
So I have prepared a dojo that shows two different ways of setting the checked state of the items.
https://dojo.telerik.com/EhaMIDAt/8
1. Setting at the DataSource Level
So when setting up the datasource you can add an extra attribute to your collection called checked this will then set the checked value for the item or children items when loaded. using the example I have in the dojo:
{
id: 9,
text: "Reports",
expanded: true,
spriteCssClass: "folder",
items: [{
id: 10,
text: "February.pdf",
spriteCssClass: "pdf"
},
{
id: 11,
text: "March.pdf",
spriteCssClass: "pdf",
checked: true
},
{
id: 12,
text: "April.pdf",
spriteCssClass: "pdf"
}
]
}
this will set the checked state to true for you and show the checkbox as checked.
2. Manually Set the values after loading all the DataSources.
So I have done this on a button click but this could easily be done on a ready state or some other trigger if needed. Here the button when clicked will find the node in the tree with the text Research.pdf and either set it in a checked or unchecked state for you.
$('#checked').bind('click', () => {
var box = $("#treeview").data("kendoTreeView").findByText('Research.pdf').find('input[type="checkbox"]');
box.prop('checked', !box.is(':checked'));
});
Again the sample it taken from dojo link above. Hopefully this gives you a start on getting the values set according to your specific requirements.
I would probably have the value checked state set when you load the datasource for the treeview.

Kendo UI adding new row to grid adds extra row with null value

I have been trying to figure out what is going on but haven't yet.
Please see the code below.It is a inconsistent behavior, so I am having hard time to catch what triggers it. This grid is inside a popup, I noticed when i refresh the page and try it, it works fine on first attempt. Then i save/cancel popup and keep repeating it fails at some point and starts accumulate null rows.
I tried to check the value of the grid using
$('#gridFldListItems').data("kendoGrid").dataSource.data()
It shows there is no data but as soon as click "Add new Record" it shows 2.
It does not necessarily fail on second attempt, but it never fails on first. I suspect that everytime I open the popup it is not necessarily empty(after first few tries) and it carries some data from previous attempts. I might be wrong.
When I click add new record, it adds a line with null value and gives me an option to input on the second row.
I also When I put itemname and click update, it does not trigger the "create" event and looks like this:
At this point the grid broken. Here is the code for the grid
var grid = $("#gridFldListItems").kendoGrid({
editable: {
"confirmation": "Are you sure you want to delete this item?",
"mode": "inline",
"createAt": "bottom"
},
selectable: true,
autoBind: false,
toolbar: ["create" ],
columns: [
{ field: 'Item' },
{
command: ['edit', 'destroy',
{ iconClass: "k-icon k-i-arrow-up", click: $.proxy(this, 'selectedFieldDef_onClkMoveUp'), name: 'Up' },
{ iconClass: "k-icon k-i-arrow-down", click: $.proxy(this, 'selectedFieldDef_onClkMoveDown'), name: 'Down' }], title: ' '
}
],
dataSource: this.selectedFieldDef_dsItems,
}).data("kendoGrid");
selectedFieldDef_dsItems: new kendo.data.DataSource({
transport: {
read: function (e) {
var field = editViewModel.get("selectedFieldDef");
var mapItems = $.map(field.Items, function (item, idx) {
return {
Item: item
};
});
//on success
e.success(mapItems);
},
create: function (e) {
// on success
e.success(e.data);
},
update: function (e) {
// on success
e.success();
},
destroy: function (e) {
var vm = editViewModel;
// locate item in original datasource and remove it
var field = vm.get("selectedFieldDef");
if (field.DefaultValue && !vm.selectedFieldDef_dsItemsFindItem(vm.selectedFieldDef_dsItems.data(), field.DefaultValue)) {
field.DefaultValue = null;
vm.set("selectedFieldDef", field);
$("#inpFldRegex").kendoDropDownList().data("kendoDropDownList").trigger("change");
}
// on success
e.success();
}
},
error: function (e) {
alert("Status: " + e.status + "; Error message: " + e.errorThrown);
},
schema: {
model: {
id: "Item",
fields: {
Item: { editable: true, nullable: true }
}
}
}
})
Any help would be much appreciated.
UPDATE:
It works fine when I refresh the page

Unable to submit custom field, which extends dataview

I have a fiddle which demonstrates this strange behaviour. In a nutshell, I have a custom field which extends Ext.DataView. I need to extend dataview, because this field is supposed to have dynamic contents. This is how my field is defined:
Ext.define('Ext.ux.SimpleList', {
extend: 'Ext.DataView',
alias: 'widget.simplelist',
requires: [
'Ext.XTemplate'
],
itemSelector: 'div.record',
isFormField: true,
getFieldIdentifier: function () {
return this.name;
},
getModelData: function() {
var me = this;
var data = {};
data[me.getFieldIdentifier()] = me.getValue();
return data;
},
getSubmitData: function() { return {}; },
submitValue: true,
isValid: function () { return true; },
isDirty: function () { return true; },
validate: function () { return true; },
isFileUpload: function() { return false; },
constructor: function(config) {
Ext.applyIf(config, {
tpl: [
'{% var name = this.owner.name; %}',
'<tpl for=".">',
'<div class="record"><input record-id="{id}" type="checkbox" name="{[name]}" /> {label}</div>',
'</tpl>',
{compiled: true}
]
});
this.callParent([config]);
},
getValue: function () {
var cb = this.el.select("input").elements, i, res = [];
for (i in cb) {
if (cb.hasOwnProperty(i) && cb[i].checked) {
res.push(cb[i].getAttribute("record-id"));
}
}
return res;
},
setValue: function (values) {
//not yet implemented
}
});
And this is how I add this field to a form:
Ext.create("Ext.form.Panel",{
renderTo: Ext.getBody(),
items:[{
xtype: "textfield",
name: "text"
},{
xtype: "simplelist",
name: "list",
store: {
fields: ["id", "label", "checked"],
data: [{"id": "1", "label": "One"},{"id": "2", "label": "Two"}]
}
},{
xtype: "button",
text: "Submit",
handler: function () {
var frm = this.up("form").getForm();
console.log(frm.getFieldValues()); // it' ok
//simplelist field is not submitted
this.up("form").getForm().submit({
url: "/"
});
}
}]
});
As you can see, when I submit the form I log to the console form field values. And what is interesting about that, is that I see my custom field among those field values. So, I have a field with isFormField set to true, this field is in the list returned by form getFields() method and this field is also among those values returned by form getFieldValues() method, but still this field is not submitted. What is wrong with that and how can I fix it?
Your code uses basicForm.getFieldValues(), which calls basicForm.getValues() with some parameters, while the form while submitting uses the same method with different parameters. One of those parameters is useDataValues, which decides whether to use the getModelData or getSubmitData.
You are returning empty object in your getSubmitData method, which prevents it to correctly get the values.
All you need to change, for both methods to work in your current state, is this:
getSubmitData: function() {
return this.getModelData();
}

How to get Ext JS component from DOM element

Trying to create an inline edit form.
I have a form that looks like this:
var editPic = "<img src='https://s3.amazonaws.com/bzimages/pencil.png' alt='edit' height='24' width='24' style='margin-left: 10px;'/>";
var submitPic = "<img id='submitPic' src='https://s3.amazonaws.com/bzimages/submitPic.png' alt='edit' height='24' width='24'/>";
Ext.define('BM.view.test.Edit', {
extend: 'Ext.form.Panel',
alias: 'widget.test-edit',
layout: 'anchor',
title: 'Edit Test',
defaultType: 'displayfield',
items: [
{name: 'id', hidden: true},
{
name: 'name',
fieldLabel: 'Name',
afterSubTpl: editPic,
cls: 'editable'
},
{
name: 'nameEdit',
fieldLabel: 'Name',
xtype: 'textfield',
hidden: true,
cls: 'editMode',
allowBlank: false,
afterSubTpl: submitPic
}
]
});
The controller looks like this (a lot of events):
init: function() {
this.control({
'test-edit > displayfield': {
afterrender: this.showEditable
},
'test-edit': {
afterrender: this.formRendered
},
'test-edit > field[cls=editMode]': {
specialkey: this.editField,
blur: this.outOfFocus
}
});
},
outOfFocus: function(field, event) {
console.log('Lost focus');
this.revertToDisplayField(field);
},
revertToDisplayField: function(field) {
field.previousNode().show();
field.hide();
},
formRendered: function(form) {
Ext.get('submitPic').on('click', function (event, object) {
var field = Ext.get(object).parent().parent().parent().parent();
var cmp = Ext.ComponentQuery.query('test-edit > field[cls=editMode]');
});
},
editField: function(field, e) {
var value = field.value;
if (e.getKey() === e.ENTER) {
if (!field.allowBlank && Ext.isEmpty(value)){
console.log('Not permitted!');
} else {
var record = Ext.ComponentQuery.query('test-edit')[0].getForm().getRecord();
Ext.Ajax.request({
url: '../webapp/tests/update',
method:'Post',
params: {
id: record.getId(),
fieldName: field.name,
fieldValue: field.value
},
store: record.store,
success: function(response, t){
field.previousNode().setValue(value);
t.store.reload();
var text = response.responseText;
// process server response here
console.log('Update successful!');
}
});
}
this.revertToDisplayField(field);
} else if (e.getKey() === e.ESC) {
console.log('gave up');
this.revertToDisplayField(field);
}
},
showEditable: function(df) {
df.getEl().on("click", handleClick, this, df);
function handleClick(e, t, df){
e.preventDefault();
var editable = df.nextNode();
editable.setValue(df.getValue());
editable.show();
editable.focus();
df.hide();
}
},
I'm using the 'afterSubTpl' config to add the edit icon, and the accept icon.
I have listeners set up to listen on click events concerning them, but after they are clicked, I only have the element created by Ext.get('submitPic'). Now I want to have access to the the Ext field and form that surround it. The parent method only brings back other DOM elements. How do I connect between them? You can see what I tried in formRendered.
I hope someone can clarify this little bit for me.
Walk up the DOM tree until you find a component for the element's id:
getCmpFromEl = function(el) {
var body = Ext.getBody();
var cmp;
do {
cmp = Ext.getCmp(el.id);
el = el.parentNode;
} while (!cmp && el !== body);
return cmp;
}
Ext.Component.from(el) does exactly this since ExtJS 6.5.0, as I just learnt. Doc
Source
You can get the component by id, but only if your component and its dom element have the same id (they usually do):
Ext.getCmp(yourelement.id)
But this is not exactly good practice -- it would be better to set up your listeners so that the handler methods already have a reference to the component. For example, in your 'submitPic' component, you could define the click listener like this:
var me = this;
me.on({
click: function(arguments){
var cmp = me;
...
});

How to disable the delete button using if condition in Extjs

How to disable the delete button using if condition in Extjs for ex;i want to disable the button if it satifies the given if condition else remain enabled.
if(validAction(entityHash.get('entity.xyz'),actionHash.get('action.delete')))
This is the grid Delete button code.
Ext.reg("gridheaderbar-inActive", Ad.GridInActiveButton,{
xtype: 'tbspacer', width: 5
});
Ad.GridCampDeleteButton = Ext.extend(Ext.Toolbar.Button, {
//text: 'Delete',
cls: 'ad-img-button',
width:61,
height:40,
iconCls: 'ad-btn-icon',
icon: '/webapp/resources/images/btn_del.png',
handler:function(){
statusChange(this.parentBar.parentGrid, 'Delete')
}
});
create actioncolumn and make custom renderer:
{
xtype: 'actioncolumn',
width: 38,
renderer: function (val, metadata, record) {
this.items[0].icon = '${CONTEXT_PATH}/images/' + record.get('fileType') + '.png';
this.items[0].disabled = !record.get('isDownloadActionEnable');
this.items[1].disabled = !record.get('isDeleteActionEnable');
metadata.style = 'cursor: pointer;';
return val;
},
items: [
{
icon: '${CONTEXT_PATH}/images/pdf.png', // Use a URL in the icon config
tooltip: 'Download',
handler: function (grid, rowIndex, colIndex) {
//handle
}
},
{
icon: '${CONTEXT_PATH}/images/delete.png', // Use a URL in the icon config
tooltip: 'Delete',
handler: function (grid, rowIndex, colIndex) {
handle
}
}
]
}
in this example You see additionally how to change dynamically icon.
One way to solve it is to attach a unique ID to your delete button and bind a listener to the selectionchange event of your SelectionModel, whenever the selection changes you can check whatever you want and enable/disable the button as you see fit.
ie.
Ad.GridCampDeleteButton = Ext.extend(Ext.Toolbar.Button, {
id: 'btnDelete',
cls: 'ad-img-button',
...
});
and in your selectionmodel do something like this :
var sm = new Ext.grid.CheckboxSelectionModel({
...
,listeners: {
'selectionchange' : {
fn: function(sm) {
if (sm.hasSelection()) {
var selected = sm.getSelected();
if (selected.get('field') == value) {
Ext.getCmp('btnDelete').disable();
}
else {
Ext.getCmp('btnDelete').enable();
}
}
}
,scope: this
}
}
});

Categories

Resources