Dynamic default value for Kendo Grid - javascript

I want an auto increment column in my Kendo Grid. This field isn't server side auto increment, because I want the user to see the value and be able to change it.
My current solution is to add a click attribute to Create button and loop over rows to find the highest value and increment it.
But how can I insert this value inside the newly created row? Click event happens before the new row is created.
So there is two possible solution:
Have a variable as default value and update it in my JS code.
Access the newly created row somehow, and update the value.
This is my JS code:
function createClick(id) {
var grid = $("#" + id).data('kendoGrid');
var highestRadif = 0;
grid.tbody.find('>tr').each(function () {
var dataItem = grid.dataItem(this);
var radif = dataItem.SRadifReqR;
highestRadif = highestRadif < radif ? radif : highestRadif;
})
alert(++highestRadif);
}

You can use Grid's edit event to add your new generatedId value to new Grid's model.
This is some explanation from their documentation:
Edit
fired when the user edits or creates a data item.
e.container jQuery, jQuery object of the edit container element, which wraps the editing UI.
e.model kendo.data.Model, The data item which is going to be edited. Use its isNew method to check if the data item is new
(created) or not (edited).
e.sender kendo.ui.Grid, The widget instance which fired the event.
I suppose your click have something like this
//generate id code
vm.newId = ++highestRadif; // we need to store generated Id
grid.addRow();
then on edit event
edit: function(e) {
var model = e.model; // access edited/newly added model
// model is observable object, use set method to trigger change event
model.set("id", vm.newId);
}
Note: Your schema model's field must set property editable: true, due to enable us to change model field value using set method. Also if your field schema have validation required, you need to remove it.
model: {
id: "ProductID",
fields: {
ProductID: { editable: true, nullable: true },
}
}
Sample

I was able to put a function in the datasource schema for this.
schema: {
model: {
id: "id",
fields: {
currencyType: { defaultValue: getDefaultCurrency },
invoiceDate: { type: "date" }
}
}
}
function getDefaultCurrency() {
return _.find(vm.currencyTypes, { id: vm.currencyId });
};

Related

Non editable kendo grid ID

I'm new using kendo grid UI, i'm trying to make a non editable column (when updating) using a simple code :
schema: {
id: 'ID',
fields: {
id: { editable: false }
}
}
This default schema, makes by default non editable id column, and i can't even create a new row with id .
I want to make it non editable (when updating) but i want the possibility to create a row and assign an id from user (when creating).
Any ideas ?
Edit :
PS : the proprety is not related to only id, it can be on every column (can't update but can create)
The editable required a function instead of a value.
columns: [
{ field: 'value', editable: function () { return false; } }
],
Checkout here:
https://dojo.telerik.com/oROJayAd
I always doubt about that model editable option. It never really worked for me. It should have something very deep in the setup to make it work which I never realized what it. So this is a way to acomplish what you need that I know it indeed works: To cancel the edit event. Check it out:
edit: function(e) {
// Cancels a new row
if (arguments, e.model.isNew()) {
this.cancelRow(e.container.parent());
}
else { // Cancels a cell editing
this.closeCell(e.container);
}
}
Demo
Now, if you like to add a condition in that event based on what you have set in your model, you can access it within event as well:
edit: function(e) {
let currentColumn = this.options.columns[e.container.index()].field,
model = this.dataSource.options.schema.model.fields[currentColumn];
if (model.editable === false) {
// Cancels a new row
if (arguments, e.model.isNew()) {
this.cancelRow(e.container.parent());
}
else { // Cancels a cell editing
this.closeCell(e.container);
}
}
}
Demo
You can add an option yourself in the model to set if the column can be updated or only created, and handle that information inside the event, canceling the editing whenever you like.
This is how I just did it, though there are other ways.
In columns option if you remove the field option from a column it doesn't know from where to bind it.
Then use the template option to show(bind) the id. Thus making it readonly
columns: [
{
title: 'Id', width: "40px",
template: "#= id #",
},
...]

How to reflect change made in a component's variable to the view in Angular 2?

I have (n) check boxes and a button in my angular2 view . When I click on one of them a function is called. When I click on the button every checkbox must be unchecked. How to do it?? (n) may vary dynamically.
enter image description here
I will give you an example from a table, since I have no idea what your code actually looks like, but it should work for what you need.
You need some object defined for all of your checkboxes. They likely all have certain properties in common, like labels. Here is an example of such an object:
myData = {
content: [
{
some_string: '',
some_number: 0,
type: '',
selected: false
}
]
};
With this object you can create checkbox instances and push each one to an array, which will hold all of your checkbox objects.
Create your checkboxes in your html in a loop using the objects you have defined above. In your html have your checkboxes call a function. In the case below the checkToggle() function is called.
<input id='{{row.id}}' class='bx--checkbox bx--checkbox--svg'
type='checkbox' name='checkbox' (change)="checkToggle($event,
row.id)" [checked]="row.selected">
checkToggle() has been defined as follows:
//select or deselect this check box
checkToggle(event, nodeId) {
const id = this.findNode(nodeId);
this.myData.content[id].selected = !this.myData[id].selected;
}
Your button should end up calling a function to check all of the boxes
<button (click)="checkToggleAll($event)">Your Button Title</button>
Finally, have your checkToggleAll() function go through the entire array of checkboxes and set them. Here is an example:
//select or deselect all the check boxes
checkToggleAll(event) {
for (let i = 0; i < this.myData.content.length; i++) {
if (this.controls[this.myData.content[i].type]) {
this.myData.content[i].selected = event.target.checked;
}
}
}
This is not something you can plug into your code but it should give you some idea of how to accomplish what you're after.

How to display the role name in the dialog box when Delete button is pressed

I've a table specifying the roles and actions, if I check in the role and press delete button, then I should get a dialog box indicating that specific role
If I click on add button, I should get a dialog box or message box with the list of few other roles and on clicking on that role, a rolename should be displayed that has to be added to the respective table
I've created the sap.m.Table and I'm binding the JSON data
Enclosed the Image of the UI:
I've tried with various methods and I'm enclosing my code
Here is the code..
I can delete the item from the table, but I should get a dialog/message box indicating that, the checkmarked role in the table has been deleted
<script>
function delete1()
{
var v = false;
$('input[type="checkbox"]:checked').each(function() {
v = true;
alert("Checked item in the table will be deleted from the table");
});
if (v == false)
{
alert("Please check the item to be deleted");
}
$('input[type="checkbox"]:checked').closest("tr").remove();
}
var oModel = new sap.ui.model.json.JSONModel("JSon/etc5.json");
// Load JSON in model
sap.ui.getCore().setModel(oModel,"model1");
//create table
//"cells"
var oRoles = new sap.m.Text({text: "{model1>Role}"});
var oAction = new sap.m.Button({text: "DETAILS",
type : sap.m.ButtonType.Emphasized,
});
// corresponding columns
var oColAbbr = new sap.m.Column({header: new sap.m.Text({text:"ROLES"}) });
var oColAct = new sap.m.Column({header: new sap.m.Text({text:"ACTION"}) });
// row template
var oRow = new sap.m.ColumnListItem();
oRow.addCell(oRoles).addCell(oAction);
// instantiating the table
var oTab = new sap.m.Table("app",{
inset : true,
headerText : "SOME DATA",
headerDesign : sap.m.ListHeaderDesign.Standard,
includeItemInSelection : false,
});
oTab.addColumn(oColAbbr).addColumn(oColAct);
oTab.bindItems("model1>/emp", oRow); //binding data to the tables
oTab.setMode(sap.m.ListMode.MultiSelect);
var oButton = new sap.m.Toolbar({
content: [
new sap.m.ToolbarSpacer(),
new sap.m.Button({
text : "ADD",
textAlign : "Center",
width : "10%",
type: sap.m.ButtonType.Emphasized,
press: function() {
// oCDialog2.open();
},
}),
new sap.m.Label({text:""}),
new sap.m.Button({
text : "DELETE",
textAlign : "Center",
width : "10%",
type: sap.m.ButtonType.Reject,
press: function() {
// oCDialog1.open();
delete1();
}
}),
]
});
//creating the icons
var iTab = new sap.m.IconTabBar({
items:[
new sap.m.IconTabFilter({
text: "HR",
icon: "sap-icon://group",
content:[oTab]
}),
]
});
var page = sap.m.Page({
content: [iTab,oButton],
showHeader : false,
enableScrolling : true,
});
var app = sap.m.App();
app.addPage(page);
app.placeAt("content");
</script>
It is probably easiest to use the Checkbox control and bind it's value to the same model as where the item lines come from (model1>/emp). In your delete method, you could then easily iterate through the emp array and test on the value representing the checkbox.
Whenever you delete an entry from the array, either UI5's MessageToast or MessageBox controls to show the message. Alerts may be blocked by "Check here to disable alerts from this website" functionality in some browsers.
You may also want to change the $.each to a $.grep instead. This loops through an array in pretty much the same way as $.each with one exception. If you return true from the callback, the element is retained. Otherwise, it is removed from the array.
Your code should look something like this:
items = this.getView().getModel("model1").getProperty("/emp");
items = $.grep(items, function (el, i) {
if (el.propertyBoundToCheckbox) {
MessageToast.show("Deleting entry: " + el.getName())
return false;
}
return true; // keep the element in the array
});
Note: The code above pulls the model from the view, as that's a best practice. Try not to tie anything to the core, as the core is shared between all applications running in the browser window (e.g. in Fiori Launch Pad scenario).

Ext js grid remove selection model

I have a situation where I need to dynamically add or remove grids selection model.
Searching the documentation I see that the selection model doesn't have a destroy() method or anything similar. How can I remove or destroy a selection model from a grid in ext js 4.x.?
If this is not possible I still have an option to revert some functionallity and dynamically add the selection model to an already created grid. But I'm also not sure if this is possible.
I'd suggest to disable the selection model instead of destroying it.
You can clear the current selection (deselectAll) and lock the selection model to prevent further selection (setLocked):
selModel.deselectAll();
selModel.setLocked(true);
As you're using a checkbox selection model, you'll also need to hide the corresponding column which is added to the grid:
grid.headerCt.child('gridcolumn[isCheckerHd]').hide();
Selection models are not designed to be replaced, so... it's gonna be complicated!
You'd have to reproduce the initialization of the sel model, unwire the previous one, and rewire the new one...
Here's an example that works in substituting a row selection model for a checkbox model. It may still contains memory leaks from listeners registered by the first selection model that I would have forgot. The creation of the new selection model relies on the getSelectionModel method of the grid, which implements the disableSelection, simpleSelect, and multiSelect options of the grid (see the code).
Ext.widget('grid', {
renderTo: Ext.getBody()
,store: ['Foo', 'Bar', 'Baz']
,selType: 'checkboxmodel'
,columns: [{
dataIndex: 'field1'
,text: "Name"
}]
,listeners: {
selectionchange: function(sm, records) {
var grid = sm.view.up(),
item = grid.down('tbtext');
if (records.length) {
item.setText(
'Selection: ' + Ext.pluck(Ext.pluck(records, 'data'), 'field1').join(', ')
);
} else {
item.setText('No selection');
}
}
}
,tbar: [{
text: "Replace selection model"
,handler: function(button) {
var grid = button.up('grid'),
headerCt = grid.headerCt,
checkColumn = headerCt.down('[isCheckerHd]'),
view = grid.view,
previous = grid.selModel,
sm;
// try to clean up
previous.deselectAll();
previous.destroy();
// sel model doesn't clear the listeners it has installed in its
// destroy method... you'll have to chase the listeners that are
// installed by the specific type of sel model you're using
if (previous.onRowMouseDown) {
view.un('itemmousedown', previous.onRowMouseDown, previous);
}
if (previous.onRowClick) {
view.un('itemclick', previous.onRowClick, previous);
}
// clear references
delete grid.selModel;
delete view.selModel;
// create another selModel
grid.selType = 'rowmodel';
//grid.disableSelection = true;
sm = grid.getSelectionModel();
// assign new sel model
view.selModel = sm;
sm.view = view;
// remove checkbox model column
if (checkColumn) {
headerCt.remove(checkColumn);
}
// init sel model is trigerred in view render events, so we must do it
// now if the view is already rendered
if (view.rendered) {
sm.beforeViewRender(view);
sm.bindComponent(view);
}
// finally, refresh the view
view.refresh();
}
}]
// a place to display selection
,bbar: [{
xtype: 'tbtext'
,text: 'No selection'
}]
});

Add new Row in Kendo Grid with some default values

I want to add new Row in Kendo Grid which is having Default value in First Cell.
How can I set the Default Value in that added Row of Kendo Grid
I am adding New Row in Kendo Grid as::
$('#AddSingleSuppliment').click(function () {
grid.addRow();
});
But I want to Set the Value of First cell on the Basis of Value of Clicked DOM element, Like
$('#AddSingleSuppliment').click(function () {
var temVal=$(this).text();
grid.addRow(tempVal);
});
But we can't do it in that Manner.
So please help me on this, For adding New Row in Kendo Grid with one Cell having Value of Button clicked.
Now I am able to Add New Row in Kendo Grid as,
$("#AddSingleSupplement").click( function(){
var tempSupplement = $(this).val();
//alert(tempSupplement);
grid.addRow(tempSupplement);
grid.dataSource._data[0].Description = $(this).text().trim();
});
But the Value is not Directly Shown while adding new Row. It is Shown after we click on some other element.
Please Suggest me wether this one is the Correct way to do this or there is any other way than this.
For dynamic defaults you can wire up your logic on Edit event, something like:
<script>
$('#AddSingleSuppliment').click(function () {
grid.addRow();
});
function onEdit(e)
{
//Custom logic to default value
var name = $("#AddSingleSuppliment").text();
// If addition
if (e.model.isNew()) {
//set field
e.model.set("Name", name); // Name: grid field to set
}
}
</script>
As per Kendo team , Default value cannot be changed dynamically.
However, we can make use the Grid edit event to pre-populate the edit form:
edit: function(e) {
if (e.model.isNew() && !e.model.dirty) {
e.container
.find("input[name=ProductName]") // get the input element for the field
.val("MyCustomValue") // set the value
.change(); // trigger change in order to notify the model binding
}
}

Categories