backgrid.js delete selected - javascript

I am trying to add a delete button to a datagrid (using backgrid.js http://backgridjs.com/)
I have a select row
var grid = new Backgrid.Grid({
columns: [{
// name is a required parameter, but you don't really want one on a select all column
name: "id",
// Backgrid.Extension.SelectRowCell lets you select individual rows
cell: "select-row",
}].concat(columns),
collection: contacts
});
a button:
<button id= "button" type="button">Delete</button>
and:
$('#button').click(function () {
});
but how do i get the selected row id ? and send it to the server, to delete data from DB?

There's an entry on the documentation describing Grid#getSelectedModels.

Related

Datatable Search Function Does Not Filter The Table On Multiple Values

I'm building an excel filter with datatable. I have collected the values of the table rows and pushed it into the filter dropdown.
screenshot of the dropdown.
Datatable code:
datatable = $("#datatable").DataTable({
searching: true,
columns: [
{ title: "itemID", defaultContent: "" },
{ title: "Name", defaultContent: "" },
{ title: "Age", defaultContent: "" },
{ title: "Country", defaultContent: "" },
{ title: "E-mail", defaultContent: "" },
{ title: "Address", defaultContent: "" },
{ title: "Fax", defaultContent: "" },
{ title: "Employee ID", defaultContent: "" },
{ title: "Occupation", defaultContent: "" },
{ title: "Phone", defaultContent: "" },
{ title: "", defaultContent: "" }
],
// Initialize the datatable header.
initComplete: function () {
var table = this.api();
var headers = $(this[0]).find("thead tr").children();
// For each header, append an input so it can be used for filtering the table.
$(headers).each(
column =>
(table
.column(column)
// Append the filter div and the arrow down icon.
.header().innerHTML += `<i class="arrow down"></i><div class="filter"></div>`)
);
}
});
On click of the arrow to open the dropdown filter:
var thObject = $(this).closest("th");
var filterGrid = $(thObject).find(".filter");
filterGrid.empty();
filterGrid.append(
'<div><input id="search" type="text" placeholder="Search"></div><div><input id="all" type="checkbox" checked>Select All</div>'
);
// Loop through all the datatable rows.
datatable.rows().every(function (rowIdx, tableLoop, rowLoop) {
// Get current td value of this column.
var currentTd = this.data()[$(thObject).index()];
// Get the tr tag of this row.
var row = this.table().rows().context[0].aoData[rowIdx].nTr;
var div = document.createElement("div");
// filterValues is a local variable to store all the filter values and to avoid duplication.
if (filterValues.indexOf(currentTd) == -1) {
div.classList.add("grid-item");
// if the row is visible, then the checkbox is checked.
var str = $(row).is(":visible") ? "checked" : "";
// For this div, append an input field of type checkbox, set its attribute to "str" (checked or not), with the value of the td.
div.innerHTML = '<input type="checkbox" ' + str + " >" + currentTd;
// filterGrid is a local variable, which is the div of the filter in the header.
filterGrid.append(div);
filterValues.push(currentTd);
}
});
filterGrid.append(
'<div><input id="close" type="button" value="Close"/><input id="ok" type="button" value="Ok"/></div>'
);
filterGrid.show();
Here is the code on click on the okay button after selecting values to filter the datatable:
var $okBtn = filterGrid.find("#ok");
var checkedValues = [];
$okBtn.click(function () {
// checkedValues is a local variable to store only the checkboxes that has been checked from the dropdown fiter.
// Empty the array.
checkedValues = [];
// filterGrid is the dropdown jquery object.
filterGrid
// find all the checked checkboxes in the filterGrid.
// ".grid-item" is a class of div that contains a checkbox and a td's value of the current datatable column.
.find(".grid-item input[type='checkbox']:checked")
// The result is an array.
// For each index in this array, push it to checkedValues array (store the values).
.each(function (index, checkbox) {
checkedValues.push($(checkbox).parent().text());
});
// Show relative data in one page.
datatable
// In datatable, search in this specific column by the index of the thObject (the header element) to search in the right tds.
.column($(thObject).index())
// Call search function (datatable built in function) to search in the table for all the selected values.
// Search function allows strings, so call the checkedValues array, join all the values together(exmp. "name1|name2|name3") to allow multi search.
// Draw the new table.
// "^"- Start of string or start of line depending on multiline mode.
// "$"- End of string or end of line.
.search("^(" + checkedValues.join("|") + ")$", true, false, true)
.draw();
// Hide the dropdown filter.
filterGrid.hide();
return false;
});
After filtering the table couple of times, it stops filtering the table. I'm pretty sure that it is something wrong in the search datatable function, But I can't understand what is the exact issue (there are no error messages).
link to js fiddle.
I would be glad if someone can help.
Thank you!
I have posted the question on the datatable forum and here is the answer:
1: Uncheck 8 in the Item ID column
2: Check the name8 option in the Name
Is the problem you are seeing that the row with name8 is not being shown?
The column searches are an AND search so if one column searches filters out a row a column search in another column won't display the row. A search plugin can be created to perform an OR search if this is what you are looking for.

I want to create a purchase order after the "approve" button is clicked on a sales order

I want a purchase order to be generated when a person clicks the approve button on a sales order. I have the script deployed to sales order records and the event type to trigger when the approve button is clicked. However, this code won't create a purchase order because i have an invalid field value for the sublist item value.
I've used both the internal Id and the string name of the item as values and i get the same "invalid field value" error. Anyone know what's wrong?
function beforeSubmit(context) {
var sRecord = context.newRecord;
var user = runtime.getCurrentUser();
//get line count
var itemCount = sRecord.getLineCount({
sublistId: 'item'
});
for (var i = 0; i<itemCount; i++){
var pOrder = record.create({
type: record.Type.PURCHASE_ORDER,
isDynamic: true
});
//get item internal id
var itemId = sRecord.getSublistValue({
sublistId : 'item',
fieldId : 'item',
line : i
});
//get qty
var qty = sRecord.getSublistValue({
sublistId : 'item',
fieldId : 'quantity',
line : i
});
//get vendor of item
var vendor = search.lookupFields({
type : 'item',
id : itemId,
columns : ['vendorname']
});
//add vendor to record
pOrder.setValue('vendorname', vendor);
//selects new line
pOrder.selectNewLine({sublistId: 'item'});
//add item to sublist
pOrder.setCurrentSublistValue({
sublistId : 'item',
fieldId : 'item',
value : itemId
});
//add quantity to sublist
pOrder.setCurrentSublistValue({
sublistId : 'item',
fieldId : 'quantity',
value : qty
});
pOrder.commitLine({sublistId: 'item'});
pOrder.save();
}
}
The entity field is required on the purchase order record. The vendorname field on the item record does not store a vendor record, and even if it did, there isn't a corresponding vendorname field on the PO. This value from the item record is used to identify the vendor's name/code for the item itself, in the event they have a different name.
As written, this code functions at least situationally if the entity field is set on the PO. If you've set a Preferred Vendor or if using the multiple vendors feature have configured a preferred vendor there, you could lookup the appropriate entity field directly from the Item record still.
An easy way to achieve what this script appears to be doing without scripting for Inventory and Non-inventory for sale items is to use the Drop Ship Item checkbox or the Special Order Item checkbox on these item records. Selecting either for each eligible item will allow automatic creation of po's for the line items of your Sales Order. Search Special Order Items in the Netsuite Help for more information on the differences and how to setup either.

yii2 checkbox column selected rows - how to get parameters on selected rows using gridview

How to get parameters using gridview checkbox on selected rows.
I have button for multiple action in header of gridview.
Html::button('<i class="glyphicon glyphicon-download-alt"></i>', ['type'=>'button', 'title'=>Yii::t('app', 'Bulk Reject'), 'class'=>'btn btn-success', 'onclick'=>'var keys = $("#pjax-list-'.$model->id.'").yiiGridView("getSelectedRows"); alert(keys ? "Reject " + keys + " selected applicant(s)" : "No rows selected for download");']),
I get result number of selected rows. If i select 4 rows. I get below result in alert box.
1,2,3,4
I get only keys of selected rows like this 1,2,3,4... in alert box.
How to get active models data using in gridview. like pk id.
I have method in controller
public function actionDoreject($userid, $jobid) {
.....
}
I want to get userid and jobid parameters like this doreject/userid=$model->userid&jobid=$model->jobid
I figured out how to get these parameters using javascript.
Further more I added property checkboxOptions like below:
'columns' => [
['class' => '\kartik\grid\CheckboxColumn',
'checkboxOptions' => function ($model, $key, $index, $column) {
return ['data-uid' => $model->user_id, 'data-jid'=>$model->job_id];
}],
[
view source code of checkbox after using checkboxOptions
<input type="checkbox" name="selection[]" value="1" data-uid="6" data-jid="1">
How to get selected rows data attributes? I get error if I try to get attributes using this code $("#pjax-list-'.$model->id.'").yiiGridView("getSelectedRows").attr("data-uid")
Or is there any simple way to solve this issue?

Adding check boxes to allow multiple Delete & edit from my html table

I have the following table inside my asp.net mvc view:-
#foreach (var item in Model) {
<tr id="#item.TMSServerID">
<td>
#Html.ActionLink("Edit", "Edit","Server", new { id=item.TMSServerID },null) |
#if (!item.IsAlreadyAssigned()){
#Ajax.ActionLink("Delete",
"Delete", "Server",
new { id = item.TMSServerID },
new AjaxOptions
{ Confirm = "Are You sure You want to delete (" + item.Technology.Tag.ToString() + ")",
HttpMethod = "Post",
OnSuccess = "deletionconfirmation",
OnFailure = "deletionerror"
})}
</td>
<td>
#Html.ActionLink(item.Technology.Tag,"Details","Server",new { id = item.TMSServerID},null)
</td>
<td class="hidden-phone" >
#item.status
</td>
The table allow edit,delete single item at a time. But now I want to do the following:-
Add a checkbox beside each row.
Add a Ajax delete button to delete selected items
Add a Transfer ajax button, which allow editing the selected items status.
So I am trying to achieve the following:-
How can I pass the item id + item timestamp field , using ajax button , as I need to check if the selected items has been modified by another user?
How I can remove the selected row from the html table incase the delete operation successed ?
Thanks
add a check box on each first cell of the table with ModelID as the value of each checkbox.
inside your foreach, include this:
<td>
<input type="checkbox" name="TMSServerID" value="1" />
</td>
add this into tha parameter of your controller: Int32[] idList, something like this:
public void CheckForIds(Int32[] idList)
{
//Manipulate idList
}
and in your button event, call the controller method.
You might want to take a look at this for your reference:
http://byatool.com/mvc/asp-net-mvc-how-to-handle-multiple-checkboxes-with-viewsactions-jquery-too/

Add edit/delete button at the end of the table row

I've inline create of row in table in my index view.when user click on add row button it pre-append new editable row to the table .
at the end of the row there is button for save the data of the new row.when user click on save I disable the textboxes and checkboxes and
remove the button of create, what I need is instead add to this row the button of edit and delete, which is default for all table rows, how should I do that?
Here is the code for disable the row fields:
//Hide the create button
$('#btnsubmit').remove();
//Change the name property to disabled
$('input').attr('readonly', true);
$('#name').css("border", "none");
Here is the defult button for all the rows(if i press on create and refresh the page I will see the button also in this new saved row but I want to
add them when the row is added and the page was not refreshed...
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
#Html.ActionLink("Delete", "Delete", new { id = item.Id })
</td>
This is how I add the new row with the create button when user click on create new row
var html = '<tr><td>#Html.TextBox("name")</td><td>#Html.CheckBox("checkBox1")</td><td>#Html.CheckBox("checkBox2")</td><td>#Html.CheckBox("checkBox3")</td><td><input id="btnsubmit" type="submit" value="Create" class="btn btn-default" /></td><td></tr>';
function addRow() {
if ($('#btnsubmit').length == 0) {
//Append new row to the table
jQuery(html).prependTo('#data-table');
UPDATE
this is the example of the table which for every row there is edit/delete button
UPDATE 2
I try to add the following but the button is not added when click on create
$('#btnsubmit').click(function () {
$.post("/Roles/Create", { name : $("name").val() }, function(NewID){
var oTD = $("#btnsubmit").parent();
oTD.append("<a href='/Roles/Edit/"+ NewID +"'>Edit</a>");
oTD.append("<a href='/Roles/Delete/"+ NewID +"'>Delete</a>");
});
You will have to return the ID in response of ajax call and add append anchor with the returned ID
function SaveData()
{
$.post("/[Controllar]/Savedata", { firstname : $("txtFirst").val(), lastname : $("txtLast").val() }, function(NewID){
var oTD = $("#btnsubmit").parent();
oTD.append("<a href='/[ControllarName]/Edit/"+ NewID +"'>Edit</a>");
oTD.append("<a href='/[ControllarName]/Detail/"+ NewID +"'>Detail</a>");
oTD.append("<a href='/[ControllarName]/Delete/"+ NewID +"'>Delete</a>");
//Hide the create button
$('#btnsubmit').remove();
//Change the name property to disabled
$('input').attr('readonly', true);
$('#name').css("border", "none");
});
}

Categories