How can I remove an existing topCalc? - tabulator

Once a column definition has had a topCalc applied, I don't seem to be able to get rid of it. The formatter is removed, but the calculated numbers remain. I tried several ways of clearing it out, but no luck. Below is the most recent attempt. This works fine if is_group is true on the first run. However, once is_group has been false and the topCalcs applied, subsequent runs where is_group is true still have them. I have confirmed that the topCalc properties are being removed from the column definition objects.
Using Tabulator Version 4.9.3.
autoColumns:true,
autoColumnsDefinitions:function(definitions) {
let is_group = false;
if(document.getElementById("cex-item-detail").value == 1) {is_group = true;};
definitions.forEach((column) => {
if(column.field == "fpath") {
column.title = "Item";
column.visible = true;
column.headerFilter = true;
column.width = 600;
} else {
if(column.field == "cost") {
column.title = "Total Cost";
} else {
column.title = column.field.toUpperCase();
}
column.hozAlign = "right";
column.headerHozAlign = "right";
column.formatter = "money";
column.formatterParams = {precision: 0};
if(!is_group) {
column.topCalc = "sum";
column.topCalcFormatter = "money";
column.topCalcFormatterParams = {precision: 0};
} else {
delete column.topCalc;
delete column.topCalcFormatter;
delete column.topCalcFormatterParams;
}
}
});
return(definitions);
}

Related

how to make a function for validating TextInputLayout kotlin

I want to make a function for validation of text inputs(material design) and use it multiple times
I have a working code but I know it is dirty
how to optimize it?
this is my onClick method
fun addItems(view: View) {
val name1 = etName.text.toString().trim()
val quantity1 = etQuantity.text.toString()
val gst1 = etGst.text.toString()
val amount1 = etAmount.text.toString()
fun showToast() {
runOnUiThread(kotlinx.coroutines.Runnable {
Toast.makeText(this, "$name1 Added", Toast.LENGTH_LONG).show()
}) // runnable is used because activity is immediately killed and toast cannot be sowed hence it is to be done on ui tread
finish()
}
if (name1.isNotBlank() && quantity1.isNotBlank() && amount1.isNotBlank()) {
if (quantity1.toInt() != 0) {
if (amount1.toInt() != 0) {
Thread {
val db = Room.databaseBuilder(this, AppDb::class.java, "BookDB")
.build()
val item = ItemEntity()
item.itemName = name1
item.quantity = quantity1
item.amount = amount1
if (boolProcessWithGST) {
if (gst1.isNotBlank()) {
if (gst1.toInt() != 0) {
// process with GST
item.gst = gst1
db.abstractItemDao().saveItems(item)
showToast()
} else runOnUiThread {
tilGST.error = "Tax can't be 0%"
etGst.requestFocus()
} // ui operation only works on main/ui thread
} else runOnUiThread {
tilGST.error = "Disable toggle if no TAX"
etGst.requestFocus()
}
} else {
// process without gst
db.abstractItemDao().saveItems(item)
showToast()
}
}.start()
} else {
tilAmount.error = "Amount can't be 0"
etAmount.requestFocus()
}
} else {
tilQuantity.error = "Quantity can't be 0"
etQuantity.requestFocus()
}
} else Toast.makeText(this, "please fill the required fields", Toast.LENGTH_LONG).show()
}
I want to use the same validation for another onClick in the same activity
I tried making a function but the android studio suggests -> Cascade if should be replaced with when. how to do so?
function I made
private fun isValidInput(): Boolean {
var isValid = true
val name1 = etName.text.toString().trim()
val quantity1 = etQuantity.text.toString()
val gst1 = etGst.text.toString()
val amount1 = etAmount.text.toString()
TransitionManager.beginDelayedTransition(root_layout)
if (name1.isEmpty()) {
tilName.isErrorEnabled = true
tilName.error = "Required"
isValid = false
} else tilName.isErrorEnabled = false
if (quantity1.isEmpty()) {
tilQuantity.isErrorEnabled = true
tilQuantity.error = "Required"
isValid = false
} else if (quantity1.toInt() == 0) {
tilQuantity.isErrorEnabled = true
tilQuantity.error = "can't be 0"
} else tilQuantity.isErrorEnabled = false
if (amount1.isEmpty()) {
tilAmount.isErrorEnabled = true
tilAmount.error = "Required"
isValid = false
}else if (amount1.toInt() == 0) {
tilAmount.isErrorEnabled = true
tilAmount.error = "can't be 0"
} else tilAmount.isErrorEnabled = false
if (gst1.isEmpty()) {
tilGST.isErrorEnabled = true
tilGST.error = "Required"
isValid = false
}else if (gst1.toInt() == 0) {
tilGST.isErrorEnabled = true
tilGST.error = "can't be 0"
} else tilGST.isErrorEnabled = false
return isValid
}
first I recommend using MVVM or any other architectural pattern(MVC, MVP, MVI ... ) to clean your code and achieve separation of concerns principle. in short, you should have a separate class for your application logic(in MVVM its called ViewModel) and repository class for accessing and saving your data like database or API call, and your activity is only responsible for the views. this will make your code much cleaner.
for starter, you can use this guide : Guide to app architecture
but there are tons of other resources out there which you can learn from
for your warning "Cascade if should be replaced with when" you can just hit Alt+enter and let the android studio do it for you. if it's not working you can do it yourself. it means something like this
with if:
if (num == 0) {
//do something
} else if (num < 5) {
//do something
} else {
//do something
}
convert to when looks like this:
when {
num == 0 -> {
//do something
}
num < 5 -> {
//do something
}
else -> {
//do something
}
}
when is called switch/case in other programming languages.

Unable to delete Mutiple Comp from listbox with Extendscript

I can't perform multiple delette from my listbox although I made the listbox mutiselect Why ??
I need your help . You can see the full Script down there.
(function(){
$.win = new Window("palette");
var win = $.win;
win.orientation = "column";
win.alignChildren = ["center", "top"];
win.spacing = 10;
win.margins = 16;
var listbox1 = win.add("listbox", undefined, undefined, { name: "listbox1", multiselect: true, columnTitles: "Max", showHeaders: true });
listbox1.preferredSize.width = 136;
listbox1.preferredSize.height = 208;
var button1 = win.add("button", undefined, undefined, { name: "button1" });
button1.text = "Search";
var button2 = win.add("button", undefined, undefined, { name: "button2" });
button2.text = "Delete";
win.show();
var myNewArray = [];
button1.onClick = function Search() {
var compsArray = new Array();
var myProj = app.project;
myNewArray = [];
listbox1.removeAll();
for (var i = 1; i <= myProj.numItems; i++) {
if (myProj.item(i) instanceof CompItem) {
myNewArray = compsArray[compsArray.length] = myProj.item(i);
listbox1.add("item", myNewArray.name);
}
}
}
button2.onClick = function deletecomps() {
for (var s = 1; s <= app.project.numItems; s ++) {
if ((app.project.item(s) instanceof CompItem) && (app.project.item(s).name.match(listbox1.selection))) {
myComp = app.project.item(s);
break;
}
}
app.project.item(s).remove ();
}
})();
You can see an image to clarify the script in AE
Your problem is that listbox1.selection in line 34
if ((app.project.item(s) instanceof CompItem) && (app.project.item(s).name.match(listbox1.selection))) {
is an array, and you're trying to match it to a string returned by app.project.item(s).name which is never going to match.
Also, what are you trying to achieve with the lines
myComp = app.project.item(s);
break;
Here's the onClick function, but it works. It loops through the selection, and looks for a matching project item, based on the text of the listbox matching the comp's name. This is dangerous, because identical comp names would create false positives. I strongly suggest you don't use this technique in production code, because it will definitely cause problems for your users.
Also I'd turn the part wherre you populate the list into a separate function, and call it after you click delete, so that the list is refreshed, because at the moment the list stays the same, even after the comp is deleted.
button2.onClick = function deletecomps() {
for (var b= 0; b < listbox1.selection.length; b++){
for (var s = 1; s <= app.project.numItems; s ++) {
if ((app.project.item(s) instanceof CompItem) && (app.project.item(s).name.match(listbox1.selection[b].text))) {
app.project.item(s).remove ();
}
}
}
}

Hide a product in Kentico 10

I am performing CRUD operations for products of e-commerce site in kentico 10.I can add and update products using below API
SKUInfoProvider.SetSKUInfo(updateProduct);
Also there is an API for deleting product
SKUInfoProvider.DeleteSKUInfo(updateProduct);
But I do not wish to delete the product from database,rather just disable them so that they do not show up to the end users and still stay in the database .
I tried to set SKUEnabled as false but still user can see the product.So, I used below code to hide the products
ProductNode.SetValue("DocumentPublishTo", DateTime.Now.AddDays(-1));
But my code setup adds a new product with above disabled property.Here is my code
foreach (DataRow dr in dt.Rows)
{
manufacturer = GetManufacturer(Convert.ToString(dr["MANUFACTURER_NAME"]));
department = GetDepartment(Convert.ToString(dr["CATEGORY_OF_PRODUCT_1"]));
var sku = new SKUInfo
{
SKUNumber = Convert.ToString(dr["MANUFACTURER_PART_NUMBER"]),
SKUName = Convert.ToString(dr["MANUFACTURER_PART_NUMBER"]),
SKUDescription = Convert.ToString(dr["TECHNICAL_SPECIFICATIONS"]).Trim('"'),
SKUShortDescription = Convert.ToString(dr["SHORT_DESCRIPTION"]).Trim('"'),
SKUPrice = ValidationHelper.GetDouble(dr["RESELLER_BUY_INC"], 0),
SKURetailPrice = ValidationHelper.GetDouble(dr["RRP_INC"], 0),
SKUEnabled = false,
SKUSiteID = siteId,
SKUProductType = SKUProductTypeEnum.Product,
SKUManufacturerID = manufacturer.ManufacturerID,
SKUDepartmentID = department.DepartmentID,
SKUHeight = ValidationHelper.GetDouble(dr["HEIGHT"], 0),
SKUWidth = ValidationHelper.GetDouble(dr["WIDTH"], 0),
SKUWeight = ValidationHelper.GetDouble(dr["WEIGHT"], 0),
SKUDepth = ValidationHelper.GetDouble(dr["LENGTH"], 0),
SKUAvailableItems = 1,
SKUSellOnlyAvailable = true
};
try
{
SKUInfo updateProduct = SKUInfoProvider.GetSKUs()
.WhereEquals("SKUNumber", sku.SKUNumber)
.FirstObject;
sku.SKUPrice += sku.SKUPrice * 0.015;
if (updateProduct != null)
{
updateProduct.SKUNumber = sku.SKUNumber; updateProduct.SKUName = sku.SKUName;
SKUInfoProvider.SetSKUInfo(updateProduct);
}
else
{
SKUInfoProvider.SetSKUInfo(sku);
}
if (!sku.SKUEnabled)
{
SKUTreeNode productDoc = (SKUTreeNode)SKUTreeNode.New(productDocumentType.ClassName, tree);
if (sku.SKUEnabled == false)
{
productDoc.DocumentPublishTo = DateTime.Now.AddDays(-1);
}
productDoc.DocumentSKUName = Convert.ToString(dr["MANUFACTURER_PART_NUMBER"]);
productDoc.DocumentSKUDescription = sku.SKUDescription;
productDoc.NodeSKUID = sku.SKUID;
productDoc.DocumentCulture = cultureCode;
productDoc.DocumentName = Convert.ToString(dr["MANUFACTURER_PART_NUMBER"]);
}
}
catch (Exception ex)
{
error += "error";
}
}
Please provide the possible solution.There ain't no property such as DocumentPublishTo in SKUInfo,hence I used it with SKUTreeNode which you can find in code setup.
SKUTreeNode productDoc = (SKUTreeNode)SKUTreeNode.New(productDocumentType.ClassName, tree);
if (sku.SKUEnabled == false)
{
productDoc.DocumentPublishTo = DateTime.Now.AddDays(-1);
}
You need to get the node for the SKU, not create a new one. from the documentation :
SKUTreeNode productDoc = (SKUTreeNode)tree.SelectNodes()
.Path("/Products/NewProduct")
.OnCurrentSite()
.CombineWithDefaultCulture()
.FirstObject;
productDoc.DocumentPublishTo = DateTime.Now.AddDays(-1)

Telerik RadComboBox Items not getting checked

I have a search page where i select some parameters and hit submit I store sessions and get results in radgrid.And on the double click of the row i go to the edit page..
I am capturing radcombobox.text into a session..example Session["Status]=active,inactive,old
I am retrieving the session on !postback to keep the values back from edit page..
Sample code...
I tried the below code to get the items in combobox get chked when they return from edit page...
Not sure why its not checking the items in RadCombobox.Please advise
if (Session["Status"] != null)
{
ddlStatus.Text = Session["Status"].ToString();
string status = Session["Status"].ToString();
string[] words = status.Split(',');
foreach (RadComboBoxItem item in ddlStatus.Items)
{
string strtext = item.Text.ToString();
if (strtext.Length > 0)
{
if(ddlStatus.Items.Any(x => words.Equals(x)))
{
item.Checked = true;
}
else
{
item.Checked = false;
}
}
}
I just tried your code all you have to do just modify the foreach to be :
foreach (RadComboBoxItem item in ddlStatus.Items.ToList())
{
// if(ddlStatus.Items.Any(x => words.Equals(x)))
if(words.Contains(item.Text))
{
item.Checked = true;
}
else
{
item.Checked = false;
}
}
and it would work.

Dropdown field - first item should be blank - For more than one field (Sharepoint)

I was looking for a solution to the problem of getting a blank default when using a lookup in a field in Sharepoint. Kit Menke's solution to "Dropdown field - first item should be blank" question works perfectly for my first field with a lookup. But I can't make it work if have more that one field in the same list where I need to insert a blank for each lookup field (works only for the first field). I tried adding a new "Web Part" and applying the same code to the second field, but doesn't work. Any ideas? Thanks in advance
Follow-up to my answer here: Dropdown field - first item should be blank
Version 2.0 allows you to add the names of your dropdowns to dropdownNames in the MyCustomExecuteFunction function. As with the first one, this will work only with required single select lookup fields. Also, in order to edit the page again and update your Content Editor Web Part you may have to choose a value for your dropdowns otherwise you get the dreaded An unexpected error has occurred.. Good luck! :D
<script type="text/javascript">
function GetDropdownByTitle(title) {
var dropdowns = document.getElementsByTagName('select');
for (var i = 0; i < dropdowns.length; i++) {
if (dropdowns[i].title === title) {
return dropdowns[i];
}
}
return null;
}
function GetOKButtons() {
var inputs = document.getElementsByTagName('input');
var len = inputs.length;
var okButtons = [];
for (var i = 0; i < len; i++) {
if (inputs[i].type && inputs[i].type.toLowerCase() === 'button' &&
inputs[i].id && inputs[i].id.indexOf('diidIOSaveItem') >= 0) {
okButtons.push(inputs[i]);
}
}
return okButtons;
}
function AddValueToDropdown(oDropdown, text, value, optionnumber){
var options = oDropdown.options;
var option = document.createElement('OPTION');
option.appendChild(document.createTextNode(text));
option.setAttribute('value',value);
if (typeof(optionnumber) == 'number' && options[optionnumber]) {
oDropdown.insertBefore(option,options[optionnumber]);
}
else {
oDropdown.appendChild(option);
}
oDropdown.options.selectedIndex = 0;
}
function WrapClickEvent(element, newFunction) {
var clickFunc = element.onclick;
element.onclick = function(event){
if (newFunction()) {
clickFunc();
}
};
}
function MyCustomExecuteFunction() {
// **** ADD YOUR REQUIRED SINGLE SELECT FIELDS HERE ***
var dropdownNames = [
'Large Lookup Field',
'My Dropdown Field'
];
var dropdownElements = [];
for (var d = 0; d < dropdownNames.length; d++) {
// find the dropdown
var dropdown = GetDropdownByTitle(dropdownNames[d]);
// comment this IF block out if you don't want an error displayed
// when the dropdown can't be found
if (null === dropdown) {
alert('Unable to get dropdown named ' + dropdownNames[d]);
continue;
}
AddValueToDropdown(dropdown, '', '', 0);
// collect all of our dropdowns
dropdownElements.push(dropdown);
}
// add a custom validate function to the page
var funcValidate = function() {
var isValid = true;
var message = "";
for (var d = 0; d < dropdownElements.length; d++) {
if (0 === dropdownElements[d].selectedIndex) {
// require a selection other than the first item (our blank value)
if (isValid) {
isValid = false;
} else {
message += "\n"; // already had one error so we need another line
}
message += "Please choose a value for " + dropdownNames[d] + ".";
}
}
if (!isValid) {
alert(message);
}
return isValid;
};
var okButtons = GetOKButtons();
for (var b = 0; b < okButtons.length; b++) {
WrapClickEvent(okButtons[b], funcValidate);
}
}
_spBodyOnLoadFunctionNames.push("MyCustomExecuteFunction");
</script>
How about prepending a null option to the select menu of sharepoint.Like,
$('#idOfSelectMenu').prepend('<option value="" selected>(None)</option>');
I used this approach and append this code only in the NewForm.aspx because in EditForm.aspx it will override the selected option.

Resources