Related
I am building an Electron app that gets a certain kind of json file from the user and logs all the data from it. But I am getting an error about getting undefined from the quantity:
Json File:
{
"tiers": [
{
"trades": [
{
"wants": [
{
"item": "minecraft:string",
"quantity": {
"min": 15,
"max": 20
}
}
],
"gives": [
{
"item": "minecraft:emerald"
}
]
},
{
"wants": [
{
"item": "minecraft:emerald"
}
],
"gives": [
{
"item": "minecraft:arrow",
"quantity": {
"min": 8,
"max": 12
}
}
]
}
]
},
{
"trades": [
{
"wants": [
{
"item": "minecraft:gravel",
"quantity": 10
},
{
"item": "minecraft:emerald",
"quantity": 1
}
],
"gives": [
{
"item": "minecraft:flint",
"quantity": {
"min": 6,
"max": 10
}
}
]
},
{
"wants": [
{
"item": "minecraft:emerald",
"quantity": {
"min": 2,
"max": 3
}
}
],
"gives": [
{
"item": "minecraft:bow"
}
]
}
]
}
]
}
And this is the main.js:
const { app, BrowserWindow, ipcMain, dialog, ipcRenderer, globalShortcut } = require('electron');
const { autoUpdater } = require('electron-updater');
const path = require('path');
const Store = require('./classes/Store.js');
const { electron } = require('process');
const { setTimeout } = require('timers');
// import Vue from 'vue';
// import Vuetify from 'vuetify';
// import "vuetify/dist/vuetify.min.css";
// Vue.use(Vuetify);
let win;
let loadingScreen;
const store = new Store({
configName: 'settings',
defaults: {
windowBounds: {
width: 800,
height: 600,
x: 0,
y: 0,
},
isMaximized: false,
fullscreen: false
}
});
function createLoadingScreen() {
loadingScreen = new BrowserWindow(Object.assign({
width: 200,
height: 220,
frame: false,
transparent: true,
icon: 'build/icons/icon.png',
webPreferences: {
worldSafeExecuteJavaScript: true
}
}));
loadingScreen.setResizable(false);
loadingScreen.loadURL('file://' + __dirname + '/extraWindows/loadingScreen/loading.html');
loadingScreen.setOverlayIcon('build/icons/icon.png', "Route");
loadingScreen.on('closed', () => loadingScreen = null);
loadingScreen.webContents.on('did-finish-load', () => {
loadingScreen.show();
});
}
function createWindow() {
let width = store.get('windowBounds.width');
let height = store.get('windowBounds.height');
let x = store.get('windowBounds.x');
let y = store.get('windowBounds.y');
let isMaximized = store.get('isMaximized');
win = new BrowserWindow({
width,
height,
x,
y,
icon: 'build/icons/icon.png',
frame: false,
titleBarStyle: "hidden",
webPreferences: {
enableRemoteModule: true,
nodeIntegration: true,
webSafeExecuteJavaScript: true
},
show: false
})
win.setOverlayIcon('build/icons/icon.png', "Route");
if(isMaximized == true) {
win.maximize();
}
win.loadFile('index.html');
win.on('closed', function() {
win = null;
settingScreen = null;
});
win.webContents.on('did-finish-load', () => {
if(loadingScreen) {
loadingScreen.close();
win.show();
}
})
win.on('resize', () => {
store.set('windowBounds', win.getBounds());
});
win.on('move', () => {
store.set('windowBounds', win.getBounds());
})
win.on('maximize', () => {
store.set('isMaximized', true);
})
win.on('unmaximize', () => {
store.set('isMaximized', false);
})
win.on('show', () => {
win.setFullScreen(store.get('fullscreen'));
})
win.once('ready-to-show', () => {
autoUpdater.checkForUpdatesAndNotify();
})
}
function createSettings() {
settingScreen = new BrowserWindow({
width: 600,
height: 800,
frame: false,
parent: win,
modal: true,
titleBarStyle: "hidden",
webPreferences: {
enableRemoteModule: true,
nodeIntegration: true,
worldSafeExecuteJavaScript: true
},
show: false
})
settingScreen.loadFile('extraWindows/settingsScreen/settings.html');
settingScreen.on('close', (event) => {
event.preventDefault();
settingScreen.hide();
})
}
app.on('ready', () => {
createLoadingScreen();
setTimeout(() => {
createWindow();
createSettings();
}, 5000); // Set to 5000
});
app.on('window-all-closed', () => {
if(process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
if(BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
})
app.whenReady().then(() => {
globalShortcut.register('CmdOrCtrl+O', () => {
win.webContents.send('openFile');
})
globalShortcut.register('CmdOrCtrl+D', () => {
win.webContents.send('closeFile');
})
})
// These are all of the ipc functions needed for Route to work
ipcMain.handle('viewSettings', (event, arg) => {
if(arg === "true") {
settingScreen.show();
} else if(arg === "false") {
settingScreen.hide();
}
});
ipcMain.handle('changeSettings', (event, arg) => {
if(arg === "fullScreen") {
if(win.isFullScreen() == false) {
win.setFullScreen(true);
store.set('fullscreen', true);
} else {
win.setFullScreen(false);
store.set('fullscreen', false);
}
// Fill in the data for fullscreen
} else if(arg === 'themechooser') {
// Fill in the data for themes
}
});
ipcMain.on('appVersion', (event) => {
event.sender.send('appVersion', { version: app.getVersion() });
});
ipcMain.on('restartApp', () => {
autoUpdater.quitAndInstall();
})
autoUpdater.on('updateAvailable', () => {
win.webContents.send('updateAvailable');
});
autoUpdater.on('updateDownloaded', () => {
win.webContents.send('updateDownloaded');
})
And this is the renderer.js:
const { app, ipcRenderer } = require('electron');
const Store = require('./classes/Store.js');
const remote = require('electron').remote;
const dialog = require('electron').remote.dialog;
const fs = require('fs');
const { S_IFDIR } = require('constants');
const { electron } = require('process');
const { version } = require('os');
let currentWindow = remote.getCurrentWindow();
let $ = function(selector) {
return document.querySelector(selector);
}
let projectArray = [];
// There can only be 5 projects max. Might add more.
let projectCount = 0;
document.querySelector('#tradeSetup').addEventListener('click', () => {
//Create a new setup.
alert("This works!");
});
let fileOpenerOptions = {
title: "Open Trade File",
defaultPath: "C:\\",
buttonLabel: "Start Coding",
properties: [ 'openFile' ],
filters: [
{ name: 'Json', extensions: ['json'] },
{ name: 'All FIles', extensions: ['*'] }
]
}
//Top bar buttons
function openFile() {
dialog.showOpenDialog(currentWindow, fileOpenerOptions).then(fileNames => {
if(fileNames == undefined || fileNames == null) {
console.log("No file selected.");
return;
} else {
let projectName = path.basename(fileNames.filePaths[0], path.extname(fileNames.filePaths[0]));
let rawFileData = fs.readFileSync(fileNames.filePaths[0]);
let fileData = JSON.parse(rawFileData);
console.log(fileData);
if(projectCount < 5) {
projectCount++;
createProject(projectName, fileData);
// Run code
} else if (projectCount == 5) {
alert('Support for more projects is not available yet!\nPlease wait until a later update to have more than 5 projects.');
}
}
});
}
function openSettings() {
ipcRenderer.invoke('viewSettings', "true");
}
function closeFile() {
if(document.querySelector('.activeProjectButton') == null) {
console.log("No project to close.");
} else {
let contine = confirm("Is this project the furthest project to the right? If not, please don't close it.\nThis is a bug that is being worked on.");
if(contine == true) {
document.querySelector('.activeProjectButton').remove();
document.querySelector('.activeWorkspace').remove();
projectCount--;
document.querySelectorAll('.inactiveProjectWorkspace').j--;
}
// Add a fun little secret for users
}
}
document.querySelector('#openFile').addEventListener('click', () => {
openFile();
});
document.querySelector('#openSettings').addEventListener('click', () => {
openSettings();
});
document.querySelector('#closeFile').addEventListener('click', () => {
closeFile();
})
// Create and switch projects
function createProject(name, projectData) {
// This is a beta feature for now. It is not finished
// Create the tab
let projectInProduction = document.createElement("button");
projectInProduction.id = "project" + projectCount + "Click";
projectInProduction.classList.add("invisButton");
projectInProduction.classList.add("inactiveProjectButton");
projectInProduction.classList.add("project" + projectCount);
projectInProduction.innerHTML += (name);
// Remove the welcome message
document.querySelector('.unHidden').classList.add('hidden');
document.querySelector('.unHidden').classList.remove('unHidden');
//Create the workspace
let workspaceInProduction = document.createElement("div");
workspaceInProduction.classList.add("inactiveWorkspace");
projectArray.push(projectData);
if(projectArray[projectCount - 1].tiers == null) {
alert("This is not a trade file!\nPlease use a trade file!");
} else {
$('.projects').appendChild(projectInProduction);
$('#jsonProjectContainer').appendChild(workspaceInProduction);
let table = document.createElement('table');
table.innerHTML += '<tr><th colspan="3">Buying</th><th colspan="2">Selling</th></tr>';
table.classList.add('table' + projectCount);
workspaceInProduction.appendChild(table);
let tiers = Object.keys(projectArray[projectCount - 1].tiers).length;
console.log(tiers);
for(let i = 0; i < tiers; i++) {
let tradesC = Object.keys(projectArray[projectCount - 1].tiers[i].trades).length;
for(let j = 0; j < tradesC; j++) {
let wants = Object.keys(projectArray[projectCount - 1].tiers[i].trades[j].wants);
let wantsC = Object.keys(projectArray[projectCount - 1].tiers[i].trades[j].wants).length;
let gives = Object.keys(projectArray[projectCount - 1].tiers[i].trades[j].gives);
for(let k = 0; k < wantsC; k++) {
let wantsItem = projectArray[projectCount - 1].tiers[i].trades[j].wants[k].item;
let wantsMin = projectArray[projectCount - 1].tiers[i].trades[j].wants[k].quantity["min"];
let wantsMax = projectArray[projectCount - 1].tiers[i].trades[j].wants[k].quantity["max"];
let givesItem = projectArray[projectCount - 1].tiers[i].trades[j].gives[0].item;
console.log("Wants: " + wants[k]);
console.log("Min: " + wantsMin);
console.log("Max: " + wantsMax);
console.log("Item: " + wantsItem);
console.log("Gives: " + gives);
console.log("Item: " + givesItem);
}
}
}
}
// Add a onlclick function to make switching projects work
j = projectCount;
document.getElementById('project' + projectCount + 'Click').addEventListener('click', function(j) {
let buttonIndex = j;
let buttonNodes = $('.projects').children;
let workspaceNodes = $('#jsonProjectContainer').children;
for(let i = 0; i < buttonNodes.length; i++) {
if(i == (j - 1)) {
buttonNodes[i].classList.add('activeProjectButton');
buttonNodes[i].classList.remove('inactiveProjectButton');
workspaceNodes[i].classList.add('activeWorkspace');
workspaceNodes[i].classList.remove('inactiveWorkspace');
} else {
buttonNodes[i].classList.remove('activeProjectButton');
buttonNodes[i].classList.add('inactiveProjectButton');
workspaceNodes[i].classList.remove('activeWorkspace');
workspaceNodes[i].classList.add('inactiveWorkspace');
}
}
}.bind(null, j));
}
// Title bar scripts
ipcRenderer.on('openFile', () => {
openFile();
})
ipcRenderer.on('closeFile', () => {
closeFile();
})
// App updates
ipcRenderer.send('appVersion');
ipcRenderer.on('appVersion', (event, arg) => {
ipcRenderer.removeAllListeners('appVersion');
//version.innerText = ;
});
const updateNotifier = document.getElementById('updateNotifier');
const updateAvailability = document.getElementById('updateAvailability');
const restartButton = document.getElementById('restartButton');
ipcRenderer.on('updateAvailable', () => {
ipcRenderer.removeAllListeners('updateAvailable');
updateAvailability.innerText = 'A new version of Route is available. Downloading now...';
updateNotifier.classList.remove('hidden');
});
ipcRenderer.on('update_downloaded', () => {
ipcRenderer.removeAllListeners('updateDownloaded');
updateAvailability.innerText = 'Update downloaded. It will be installed on restart. Restart to continue.';
restartButton.classList.remove('hidden');
updateNotifier.classList.remove('hidden');
});
function restartApp() {
ipcRenderer.send('restartApp');
}
And this is the index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>route - Minecraft Addon Tool</title>
<!-- https://electronjs.org/docs/tutorial/security#csp-meta-tag -->
<meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
<link href="index.css" type="text/css" rel="stylesheet" />
<link href="node_modules/#mdi/font/css/materialdesignicons.min.css" type="text/css" rel="stylesheet" />
</head>
<body>
<script>
// const electron = require('electron').remote;
const path = require('path');
const customTitleBar = require('custom-electron-titlebar');
const Menu = require('electron').remote.Menu;
const MenuItem = require('electron').remote.MenuItem;
let mainTitlebar = new customTitleBar.Titlebar({
backgroundColor: customTitleBar.Color.fromHex('#391B47'),
icon: 'build/icons/icon.png'
});
const menu = new Menu();
menu.append(new MenuItem({
label: 'Github',
click: () => {
currentWindow.webContents.on('new-window', require('electron').shell.openExternal('https://github.com/Gekocaretaker/route'));
}
}));
menu.append(new MenuItem({
label: 'Discord',
click: () => {
console.log("Hiding the link!");
}
}));
menu.append(new MenuItem({
label: 'File',
submenu: [
{
label: 'Open File',
accelerator: 'Ctrl+O',
click: () => {
openFile();
}
},
{
label: 'Close File',
accelerator: 'Ctrl+D',
click: () => {
closeFile();
}
},
{
label: 'New File',
accelerator: 'Ctrl+N',
click: () => {
console.log("This is not yet available.");
}
}
]
}))
mainTitlebar.updateMenu(menu);
</script>
<div class="grid-container">
<div class="buttons">
<div class="tooltip openFileContainer">
<button id="openFile" class="invisButton"><span class="mdi mdi-file mdi-48px"></span></button>
<div>File</div>
</div>
<div class="tooltip settingsContainer">
<button id="openSettings" class="invisButton"><span class="mdi mdi-cog-outline mdi-48px"></span></button>
<div>Settings</div>
</div>
<div class="tooltip closeProjectContainer">
<button id="closeFile" class="invisButton"><span class="mdi mdi-close mdi-48px"></span></button>
<div>Close Project</div>
</div>
</div>
<div class="projects">
<!-- <div class="project1">
<button class="invisButton activeProjectButton" id="project1Click">Project 1</button>
</div> -->
</div>
<div class="jsonEditor">
<!-- <div class="workSpace1 activeWorkSpace">
<h3>This is Workspace 1</h3>
</div> -->
<div id="jsonProjectContainer"></div>
<div class="unHidden">
<p id="welcomeMessage">Hello User! Welcome to Route. I hope you enjoy using this!</p>
</div>
<div id="updateNotifier" class="hidden">
<p id="updateAvailability"></p>
<button id="restartButton" onclick="restartApp()"></button>
</div>
</div>
<div class="sidebar">
<div class="tooltip tradeBuilder">
<button id="tradeSetup" class="invisButton"><span class="mdi mdi-apache-kafka mdi-48px"></span></button>
<div>Basic Trade</div>
</div>
<div class="tooltip whatNext">
<button id="whatsNext" class="invisButton"><span class="mdi mdi-help mdi-48px"></span></button>
<div>Whats Next?</div>
</div>
</div>
</div>
<script src="renderer.js"></script>
</body>
</html>
This is the error:
Uncaught (in promise) TypeError: Cannot read property 'min' of undefined
at createProject (renderer.js:126)
at renderer.js:48
And I am pretty sure the error comes from how I get "min". I have tried using ["min"], ['min'], .min, and as a last resort, [0].
I have the code hosted on github, if needing to be shared.
If you would debug your code, you would notice that the error occurs when j=1 and k=0. Then if you check the object, you notice that at that location there is no question property:
{
"tiers": [
{
"trades": [
{
/* ... */
},
{
"wants": [
{
"item": "minecraft:emerald"
/* no quantity here */
}
],
"gives": [
/* ... */
]
}
]
},
/* ... */
So you'll have to decide what you want to happen when there is no quantity property. You can for instance use the optional chaining operator to use a default value:
let wantsMin = projectArray[projectCount - 1].tiers[i].trades[j].wants[k].quantity.?min || 0;
let wantsMax = projectArray[projectCount - 1].tiers[i].trades[j].wants[k].quantity.?max || 0;
The above would give 0 as value for the min/max values that are missing. But all depends on what you want to happen in this scenario.
This is just an example on how you can circumvent the error, but might not be the right way to deal with it in light of the rest of your code. That is up to you to determine.
This code is to access or process the values that are in nested array.we are iterating with loops and checks the iterating values that either it is an array or not with .isArray if yes we fetch the value ,if no we return the value.
var arr=[['hi'],
['hello',['welcome','bye']],
['world']];
for(var i=0; i<arr.length; i++)
{
for(var j=0; j<arr.length; j++)
{
if(Array.isArray(arr[i][j]))
{
for(var k=0; k<arr.length; k++)
{
console.log(arr[i][j][k]);
}
}
else
{
console.log(arr[i][j]);
}
}
}
I am facing the following issue:
ActionController::RoutingError (uninitialized constant Spree::Api::AramexAddressController::AramexAddressValidator):
app/controllers/spree/api/aramex_address_controller.rb:2:in <class:AramexAddressController>
app/controllers/spree/api/aramex_address_controller.rb:1:in <top (required)>
I included the following in my controllers/spree/api/aramex_address_controller.rb:
class Spree::Api::AramexAddressController < ApplicationController
include AramexAddressValidator
# fetch cities from aramex api
def fetch_cities_from_aramex_address
response = []
zones = Spree::ShippingMethod.where(['LOWER(admin_name) like ?', '%aramex%']).map(&:zones).flatten
if zones.map(&:countries).flatten.map(&:iso).include?(params['country_code'])
response = JSON.parse(fetch_cities(params['country_code']))['Cities']
end
respond_to do |format|
format.json { render :json => response, :status => 200 }
end
end
# Validate address for aramex shipping
def validate_address_with_aramex
begin
zones = Spree::ShippingMethod.where(['LOWER(admin_name) like ?', '%aramex%']).map(&:zones).flatten
final_response = {}
if zones.map(&:countries).flatten.map(&:iso).include?(params[:b_country])
final_response[:b_errors] = confirm_address_validity(params[:b_city], params[:b_zipcode], params[:b_country])
end
if zones.map(&:countries).flatten.map(&:iso).include?(params[:s_country]) && params[:use_bill_address] == "false"
final_response[:s_errors] = confirm_address_validity(params[:s_city], params[:s_zipcode], params[:s_country])
end
rescue
return true
end
respond_to do |format|
format.json { render :json => final_response, :status => 200 }
end
end
# Confirm address validity with Aramex address validatio API
def confirm_address_validity(city, zipcode, country)
response = JSON.parse(validate_address(city, zipcode, country))
if response['HasErrors'] == true
if response['SuggestedAddresses'].present?
response['Notifications'].map{|data| data['Message']}.join(', ') + ', Suggested city name is - ' + response['SuggestedAddresses'].map{|data| data['City']}.join(', ')
else
if response['Notifications'].first['Code'] == 'ERR06'
response['Notifications'].map{|data| data['Message']}.join(', ')
else
cities_response = JSON.parse(fetch_cities(country, city[0..2]))
cities_response['Notifications'].map{|data| data['Message']}.join(', ') + ', Suggested city name is - ' + cities_response['Cities'].join(' ,')
end
end
end
end
end
In my route file I mentioned:
get 'validate_address_with_aramex', to: 'aramex_address#validate_address_with_aramex'
get 'fetch_cities_from_aramex_address', to: 'aramex_address#fetch_cities_from_aramex_address'
I included the following JS call for the submitted Aramex Ajax validation in assets/javascripts/spree/frontend/checkout/address.js:
Spree.ready(function($) {
Spree.onAddress = function() {
var call_aramex = true;
$("#checkout_form_address").on('submit', function(e) {
if ($('#checkout_form_address').valid()) {
var s_country = $("#order_ship_address_attributes_country_id").find('option:selected').attr('iso_code');
var s_zipcode = $("#order_ship_address_attributes_zipcode").val();
var s_city = $("#order_ship_address_attributes_city").val();
var b_country = $("#order_bill_address_attributes_country_id").find('option:selected').attr('iso_code');
var b_zipcode = $("#order_bill_address_attributes_zipcode").val();
var b_city = $("#order_bill_address_attributes_city").val();
if (call_aramex == true && (typeof aramex_countries !== 'undefined') && (aramex_countries.includes(b_country) || aramex_countries.includes(s_country))) {
e.preventDefault();
var error_id = $('#errorExplanation').is(':visible') ? '#errorExplanation' : '#manual_error'
$(error_id).html("").hide()
$.blockUI({
message: '<img src="/assets/ajax-loader.gif" />'
});
$.ajax({
url: "/api/validate_address_with_aramex",
type: 'GET',
dataType: "json",
data: {
s_country: s_country,
s_zipcode: s_zipcode,
s_city: s_city,
b_country: b_country,
b_zipcode: b_zipcode,
b_city: b_city,
use_bill_address: ($("#order_use_billing").is(":checked"))
},
success: function(result) {
$.unblockUI()
if (result.b_errors || result.s_errors) {
if (result.b_errors) {
$(error_id).append('<div>Billing Address ' + result.b_errors + ' </div>')
}
if (result.s_errors) {
$(error_id).append('<div>Shipping Address ' + result.s_errors + ' </div>')
}
if ((result.b_errors && !result.s_errors) && ($("#order_use_billing").is(":unchecked"))) {
$(".js-summary-edit").trigger("click")
}
$(error_id).show();
$('html, body').animate({
scrollTop: '0px'
}, 300);
} else {
call_aramex = false;
$('#checkout_form_address').submit()
}
},
error: function(xhr, status, error) {
$(error_id).append('Oops Something Went Wrong but you can process order')
$(error_id).show();
$.unblockUI()
$('html, body').animate({
scrollTop: '0px'
}, 300);
$('#checkout_form_address').submit()
}
});
}
}
})
var getCountryId, order_use_billing, update_shipping_form_state;
if (($('#checkout_form_address')).is('*')) {
($('#checkout_form_address')).validate({
rules: {
"order[bill_address_attributes][city]": {
required: true,
maxlength: function(element) {
return maxCharLimit($("#order_bill_address_attributes_country_id").val(), 22)
}
},
"order[bill_address_attributes][firstname]": {
required: true,
maxlength: function(element) {
return maxCharLimit($("#order_bill_address_attributes_country_id").val(), 15)
}
},
"order[bill_address_attributes][lastname]": {
required: true,
maxlength: function(element) {
return maxCharLimit($("#order_bill_address_attributes_country_id").val(), 17)
}
},
"order[bill_address_attributes][address1]": {
required: true,
maxlength: function(element) {
return maxCharLimit($("#order_bill_address_attributes_country_id").val(), 32)
}
},
"order[bill_address_attributes][address2]": {
maxlength: function(element) {
return maxCharLimit($("#order_bill_address_attributes_country_id").val(), 32)
}
},
"order[bill_address_attributes][zipcode]": {
maxlength: function(element) {
return maxCharLimit($("#order_bill_address_attributes_country_id").val(), 10)
}
},
"order[ship_address_attributes][city]": {
required: true,
maxlength: function(element) {
return maxCharLimit($("#order_ship_address_attributes_country_id").val(), 22)
}
},
"order[ship_address_attributes][firstname]": {
required: true,
maxlength: function(element) {
return maxCharLimit($("#order_ship_address_attributes_country_id").val(), 15)
}
},
"order[ship_address_attributes][lastname]": {
required: true,
maxlength: function(element) {
return maxCharLimit($("#order_ship_address_attributes_country_id").val(), 17)
}
},
"order[ship_address_attributes][address1]": {
required: true,
maxlength: function(element) {
return maxCharLimit($("#order_ship_address_attributes_country_id").val(), 32)
}
},
"order[ship_address_attributes][address2]": {
maxlength: function(element) {
return maxCharLimit($("#order_ship_address_attributes_country_id").val(), 32)
}
},
"order[ship_address_attributes][zipcode]": {
maxlength: function(element) {
return maxCharLimit($("#order_ship_address_attributes_country_id").val(), 10)
}
}
}
});
getCountryId = function(region) {
return $('#' + region + 'country select').val();
};
isCountryUsOrCa = function(country_id) {
return ["38", "232"].includes(country_id)
}
maxCharLimit = function(country_id, limit) {
if (["38", "232"].includes(country_id)) {
return limit;
} else {
return 255;
}
};
Spree.updateState = function(region) {
var countryId;
var cityId
countryId = getCountryId(region);
if (countryId != null) {
if (region == 'b') {
cityId = '#order_bill_address_attributes_city'
countryInputId = "#order_bill_address_attributes_country_id"
} else {
cityId = '#order_ship_address_attributes_city'
countryInputId = "#order_ship_address_attributes_country_id"
}
fill_cities($(countryInputId).find('option:selected').attr('iso_code'), cityId)
if (Spree.Checkout[countryId] == null) {
return $.get(Spree.routes.states_search, {
country_id: countryId
}, function(data) {
Spree.Checkout[countryId] = {
states: data.states,
states_required: data.states_required
};
return Spree.fillStates(Spree.Checkout[countryId], region);
});
} else {
return Spree.fillStates(Spree.Checkout[countryId], region);
}
}
};
fill_cities = function(country_code, cityId) {
$.ajax({
url: "/api/fetch_cities_from_aramex_address",
type: 'GET',
dataType: "json",
data: {
country_code: country_code
},
success: function(data) {
$(cityId).autocomplete({
source: data,
});
},
error: function() {}
});
}
Spree.fillStates = function(data, region) {
var selected, stateInput, statePara, stateSelect, stateSpanRequired, states, statesRequired, statesWithBlank;
statesRequired = data.states_required;
states = data.states;
statePara = $('#' + region + 'state');
stateSelect = statePara.find('select');
stateInput = statePara.find('input');
stateSpanRequired = statePara.find('[id$="state-required"]');
if (states.length > 0) {
selected = parseInt(stateSelect.val());
stateSelect.html('');
statesWithBlank = [{
name: '',
id: ''
}].concat(states);
$.each(statesWithBlank, function(idx, state) {
var opt;
opt = ($(document.createElement('option'))).attr('value', state.id).html(state.name);
if (selected === state.id) {
opt.prop('selected', true);
}
return stateSelect.append(opt);
});
stateSelect.prop('disabled', false).show();
stateInput.hide().prop('disabled', true);
statePara.show();
stateSpanRequired.show();
if (statesRequired) {
stateSelect.addClass('required');
}
stateSelect.removeClass('hidden');
return stateInput.removeClass('required');
} else {
stateSelect.hide().prop('disabled', true);
stateInput.show();
if (statesRequired) {
stateSpanRequired.show();
stateInput.addClass('required');
} else {
stateInput.val('');
stateSpanRequired.hide();
stateInput.removeClass('required');
}
statePara.toggle(!!statesRequired);
stateInput.prop('disabled', !statesRequired);
stateInput.removeClass('hidden');
return stateSelect.removeClass('required');
}
};
($('#bcountry select')).change(function() {
$('label.error').hide()
if (isCountryUsOrCa($("#order_bill_address_attributes_country_id").val())) {
$('#checkout_form_address').valid();
}
return Spree.updateState('b');
});
($('#scountry select')).change(function() {
$('label.error').hide()
if (isCountryUsOrCa($("#order_bill_address_attributes_country_id").val())) {
$('#checkout_form_address').valid();
}
return Spree.updateState('s');
});
Spree.updateState('b');
order_use_billing = $('input#order_use_billing');
order_use_billing.change(function() {
return update_shipping_form_state(order_use_billing);
});
update_shipping_form_state = function(order_use_billing) {
if (order_use_billing.is(':checked')) {
($('#shipping .inner')).hide();
return ($('#shipping .inner input, #shipping .inner select')).prop('disabled', true);
} else {
($('#shipping .inner')).show();
($('#shipping .inner input, #shipping .inner select')).prop('disabled', false);
return Spree.updateState('s');
}
};
return update_shipping_form_state(order_use_billing);
}
};
return Spree.onAddress();
});
Why am I am facing the issue mentioned at the top?
maybe you can try this:
namespace :spree do
namespace :api do
resources :aramex_address, only: [] do
get :validate_address_with_aramex
get :fetch_cities_from_aramex_address
end
end
end
words of advice I think it's better if you rename the fetch_cities_from_aramex_address with show method, so it still follow rails convenience
well here is the issue of constant lookup. Your constant that is AramexAddressValidator is missing because of the way you wrote class Spree::Api::AramexAddressController < ApplicationController
So if your module AramexAddressValidator is inside some scope use that scope also while including this module
For Ex. if its inside spree/aramex_address_validator use
include Spree::AramexAddressValidator
I'm seeking a solution for the toastr.js "error" that causes the webpage, if scrolled down, to jump up again when a new toastr is displayed
GitHub page containing the script
I've tried to change the top to auto, but that wasn't an accepted parameter, because nothing showed up then.
Isn't there any way to make it appear where the mouse is at the moment?
.toast-top-center {
top: 12px;
margin: 0 auto;
left: 43%;
}
this has the calling code:
<p><span style="font-family:'Roboto','One Open Sans', 'Helvetica Neue', Helvetica, sans-serif;color:rgb(253,253,255); font-size:16px ">
xxxxxxxxxxxxx
</span></p>
This is the function code:
<script type='text/javascript'> function playclip() {
toastr.options = {
"debug": false,
"positionClass": "toast-top-center",
"onclick": null,
"fadeIn": 800,
"fadeOut": 1000,
"timeOut": 5000,
"extendedTimeOut": 1000
}
toastr["error"]("This link is pointing to a page that hasn't been written yet,</ br> sorry for the inconvenience?"); } </script>
And this is the script itself:
/*
* Toastr
* Copyright 2012-2015
* Authors: John Papa, Hans Fjällemark, and Tim Ferrell.
* All Rights Reserved.
* Use, reproduction, distribution, and modification of this code is subject to the terms and
* conditions of the MIT license, available at http://www.opensource.org/licenses/mit-license.php
*
* ARIA Support: Greta Krafsig
*
* Project: https://github.com/CodeSeven/toastr
*/
/* global define */
(function (define) {
define(['jquery'], function ($) {
return (function () {
var $container;
var listener;
var toastId = 0;
var toastType = {
error: 'error',
info: 'info',
success: 'success',
warning: 'warning'
};
var toastr = {
clear: clear,
remove: remove,
error: error,
getContainer: getContainer,
info: info,
options: {},
subscribe: subscribe,
success: success,
version: '2.1.3',
warning: warning
};
var previousToast;
return toastr;
////////////////
function error(message, title, optionsOverride) {
return notify({
type: toastType.error,
iconClass: getOptions().iconClasses.error,
message: message,
optionsOverride: optionsOverride,
title: title
});
}
function getContainer(options, create) {
if (!options) { options = getOptions(); }
$container = $('#' + options.containerId);
if ($container.length) {
return $container;
}
if (create) {
$container = createContainer(options);
}
return $container;
}
function info(message, title, optionsOverride) {
return notify({
type: toastType.info,
iconClass: getOptions().iconClasses.info,
message: message,
optionsOverride: optionsOverride,
title: title
});
}
function subscribe(callback) {
listener = callback;
}
function success(message, title, optionsOverride) {
return notify({
type: toastType.success,
iconClass: getOptions().iconClasses.success,
message: message,
optionsOverride: optionsOverride,
title: title
});
}
function warning(message, title, optionsOverride) {
return notify({
type: toastType.warning,
iconClass: getOptions().iconClasses.warning,
message: message,
optionsOverride: optionsOverride,
title: title
});
}
function clear($toastElement, clearOptions) {
var options = getOptions();
if (!$container) { getContainer(options); }
if (!clearToast($toastElement, options, clearOptions)) {
clearContainer(options);
}
}
function remove($toastElement) {
var options = getOptions();
if (!$container) { getContainer(options); }
if ($toastElement && $(':focus', $toastElement).length === 0) {
removeToast($toastElement);
return;
}
if ($container.children().length) {
$container.remove();
}
}
// internal functions
function clearContainer (options) {
var toastsToClear = $container.children();
for (var i = toastsToClear.length - 1; i >= 0; i--) {
clearToast($(toastsToClear[i]), options);
}
}
function clearToast ($toastElement, options, clearOptions) {
var force = clearOptions && clearOptions.force ? clearOptions.force : false;
if ($toastElement && (force || $(':focus', $toastElement).length === 0)) {
$toastElement[options.hideMethod]({
duration: options.hideDuration,
easing: options.hideEasing,
complete: function () { removeToast($toastElement); }
});
return true;
}
return false;
}
function createContainer(options) {
$container = $('<div/>')
.attr('id', options.containerId)
.addClass(options.positionClass);
$container.appendTo($(options.target));
return $container;
}
function getDefaults() {
return {
tapToDismiss: true,
toastClass: 'toast',
containerId: 'toast-container',
debug: false,
showMethod: 'fadeIn', //fadeIn, slideDown, and show are built into jQuery
showDuration: 300,
showEasing: 'swing', //swing and linear are built into jQuery
onShown: undefined,
hideMethod: 'fadeOut',
hideDuration: 1000,
hideEasing: 'swing',
onHidden: undefined,
closeMethod: false,
closeDuration: false,
closeEasing: false,
closeOnHover: true,
extendedTimeOut: 1000,
iconClasses: {
error: 'toast-error',
info: 'toast-info',
success: 'toast-success',
warning: 'toast-warning'
},
iconClass: 'toast-info',
positionClass: 'toast-top-right',
timeOut: 5000, // Set timeOut and extendedTimeOut to 0 to make it sticky
titleClass: 'toast-title',
messageClass: 'toast-message',
escapeHtml: false,
target: 'body',
closeHtml: '<button type="button">×</button>',
closeClass: 'toast-close-button',
newestOnTop: true,
preventDuplicates: false,
progressBar: false,
progressClass: 'toast-progress',
rtl: false
};
}
function publish(args) {
if (!listener) { return; }
listener(args);
}
function notify(map) {
var options = getOptions();
var iconClass = map.iconClass || options.iconClass;
if (typeof (map.optionsOverride) !== 'undefined') {
options = $.extend(options, map.optionsOverride);
iconClass = map.optionsOverride.iconClass || iconClass;
}
if (shouldExit(options, map)) { return; }
toastId++;
$container = getContainer(options, true);
var intervalId = null;
var $toastElement = $('<div/>');
var $titleElement = $('<div/>');
var $messageElement = $('<div/>');
var $progressElement = $('<div/>');
var $closeElement = $(options.closeHtml);
var progressBar = {
intervalId: null,
hideEta: null,
maxHideTime: null
};
var response = {
toastId: toastId,
state: 'visible',
startTime: new Date(),
options: options,
map: map
};
personalizeToast();
displayToast();
handleEvents();
publish(response);
if (options.debug && console) {
console.log(response);
}
return $toastElement;
function escapeHtml(source) {
if (source == null) {
source = '';
}
return source
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(/</g, '<')
.replace(/>/g, '>');
}
function personalizeToast() {
setIcon();
setTitle();
setMessage();
setCloseButton();
setProgressBar();
setRTL();
setSequence();
setAria();
}
function setAria() {
var ariaValue = '';
switch (map.iconClass) {
case 'toast-success':
case 'toast-info':
ariaValue = 'polite';
break;
default:
ariaValue = 'assertive';
}
$toastElement.attr('aria-live', ariaValue);
}
function handleEvents() {
if (options.closeOnHover) {
$toastElement.hover(stickAround, delayedHideToast);
}
if (!options.onclick && options.tapToDismiss) {
$toastElement.click(hideToast);
}
if (options.closeButton && $closeElement) {
$closeElement.click(function (event) {
if (event.stopPropagation) {
event.stopPropagation();
} else if (event.cancelBubble !== undefined && event.cancelBubble !== true) {
event.cancelBubble = true;
}
if (options.onCloseClick) {
options.onCloseClick(event);
}
hideToast(true);
});
}
if (options.onclick) {
$toastElement.click(function (event) {
options.onclick(event);
hideToast();
});
}
}
function displayToast() {
$toastElement.hide();
$toastElement[options.showMethod](
{duration: options.showDuration, easing: options.showEasing, complete: options.onShown}
);
if (options.timeOut > 0) {
intervalId = setTimeout(hideToast, options.timeOut);
progressBar.maxHideTime = parseFloat(options.timeOut);
progressBar.hideEta = new Date().getTime() + progressBar.maxHideTime;
if (options.progressBar) {
progressBar.intervalId = setInterval(updateProgress, 10);
}
}
}
function setIcon() {
if (map.iconClass) {
$toastElement.addClass(options.toastClass).addClass(iconClass);
}
}
function setSequence() {
if (options.newestOnTop) {
$container.prepend($toastElement);
} else {
$container.append($toastElement);
}
}
function setTitle() {
if (map.title) {
var suffix = map.title;
if (options.escapeHtml) {
suffix = escapeHtml(map.title);
}
$titleElement.append(suffix).addClass(options.titleClass);
$toastElement.append($titleElement);
}
}
function setMessage() {
if (map.message) {
var suffix = map.message;
if (options.escapeHtml) {
suffix = escapeHtml(map.message);
}
$messageElement.append(suffix).addClass(options.messageClass);
$toastElement.append($messageElement);
}
}
function setCloseButton() {
if (options.closeButton) {
$closeElement.addClass(options.closeClass).attr('role', 'button');
$toastElement.prepend($closeElement);
}
}
function setProgressBar() {
if (options.progressBar) {
$progressElement.addClass(options.progressClass);
$toastElement.prepend($progressElement);
}
}
function setRTL() {
if (options.rtl) {
$toastElement.addClass('rtl');
}
}
function shouldExit(options, map) {
if (options.preventDuplicates) {
if (map.message === previousToast) {
return true;
} else {
previousToast = map.message;
}
}
return false;
}
function hideToast(override) {
var method = override && options.closeMethod !== false ? options.closeMethod : options.hideMethod;
var duration = override && options.closeDuration !== false ?
options.closeDuration : options.hideDuration;
var easing = override && options.closeEasing !== false ? options.closeEasing : options.hideEasing;
if ($(':focus', $toastElement).length && !override) {
return;
}
clearTimeout(progressBar.intervalId);
return $toastElement[method]({
duration: duration,
easing: easing,
complete: function () {
removeToast($toastElement);
clearTimeout(intervalId);
if (options.onHidden && response.state !== 'hidden') {
options.onHidden();
}
response.state = 'hidden';
response.endTime = new Date();
publish(response);
}
});
}
function delayedHideToast() {
if (options.timeOut > 0 || options.extendedTimeOut > 0) {
intervalId = setTimeout(hideToast, options.extendedTimeOut);
progressBar.maxHideTime = parseFloat(options.extendedTimeOut);
progressBar.hideEta = new Date().getTime() + progressBar.maxHideTime;
}
}
function stickAround() {
clearTimeout(intervalId);
progressBar.hideEta = 0;
$toastElement.stop(true, true)[options.showMethod](
{duration: options.showDuration, easing: options.showEasing}
);
}
function updateProgress() {
var percentage = ((progressBar.hideEta - (new Date().getTime())) / progressBar.maxHideTime) * 100;
$progressElement.width(percentage + '%');
}
}
function getOptions() {
return $.extend({}, getDefaults(), toastr.options);
}
function removeToast($toastElement) {
if (!$container) { $container = getContainer(); }
if ($toastElement.is(':visible')) {
return;
}
$toastElement.remove();
$toastElement = null;
if ($container.children().length === 0) {
$container.remove();
previousToast = undefined;
}
}
})();
});
}(typeof define === 'function' && define.amd ? define : function (deps, factory) {
if (typeof module !== 'undefined' && module.exports) { //Node
module.exports = factory(require('jquery'));
} else {
window.toastr = factory(window.jQuery);
}
}));
Change your code to be like this:
<a href="#" style="color: rgb(255,0,0,0)" onclick="playclip(); return false;" >xxxxxxxxxxxxx </a>
However, I would reconsider using this type of javascript invokation. Take a look at this "javascript:void(0);" vs "return false" vs "preventDefault()"
i'm using Angularjs NgTable, with pagination inside of a tab provided by Angularjs Material. this works fine. i've used it in many parts of my project and realoaded it many times in differents parts.
but in this case, i can't reload the tables. and don't know what is the problem or how shoud do the reload.
i have in DistribucionController this functions:
$scope.listaFacturaTierra = function () {
var idFactura = $stateParams.idFactura;
$facturaTierra = distribucionService.getStockTierra(idFactura);
$facturaTierra.then(function (datos) {
$scope.facturaTierra = datos.data;
var data = datos;
$scope.tableFacturaTierra = new NgTableParams({
page: 1,
count: 8
}, {
total: data.length,
getData: function (params) {
data = $scope.facturaTierra;
params.total(data.length);
if (params.total() <= ((params.page() - 1) * params.count())) {
params.page(1);
}
return data.slice((params.page() - 1) * params.count(), params.page() * params.count());
}});
});
};
$scope.listaFacturaBebelandia = function () {
var idFactura = $stateParams.idFactura;
$facturaBebelandia = distribucionService.getStockBebelandia(idFactura);
$facturaBebelandia.then(function (datos) {
var data = datos.data;
$scope.facturaBebelandia = datos.data;
$scope.tableFacturaBebelandia = new NgTableParams({
page: 1,
count: 10
}, {
total: data.length,
getData: function (params) {
data = $scope.facturaBebelandia;
params.total(data.length);
if (params.total() <= ((params.page() - 1) * params.count())) {
params.page(1);
}
return data.slice((params.page() - 1) * params.count(), params.page() * params.count());
}});
});
};
$scope.listaFacturaLibertador = function () {
var idFactura = $stateParams.idFactura;
$facturaLibertador = distribucionService.getStockLibertador(idFactura);
$facturaLibertador.then(function (datos) {
var data = datos.data;
$scope.facturaLibertador = datos.data;
$scope.tableFacturaLibertador = new NgTableParams({
page: 1,
count: 10
}, {
total: data.length,
getData: function (params) {
data = $scope.facturaLibertador;
params.total(data.length);
if (params.total() <= ((params.page() - 1) * params.count())) {
params.page(1);
}
return data.slice((params.page() - 1) * params.count(), params.page() * params.count());
}});
});
};
they are displayed fine, and the pagination is working as well.
i add elements using Angularjs Material ngDialog using 3 functions the make the process.
Show the principal modal:
$scope.distribuirModal = function (producto) {
$rootScope.modalProducto = producto;
ngDialog.open({
template: 'views/modals/distribucion/modal-distribuir.html',
className: 'ngdialog-theme-advertencia',
showClose: false,
controller: 'DistribucionController',
closeByDocument: false,
closeByEscape: false
});
};
make the processs of the data, and show a modal of confirmation:
$scope.confirmarDistribuir = function (modalDistribuir) {
var control = 0;
control = modalDistribuir.tierra + modalDistribuir.bebelandia + modalDistribuir.libertador;
if (control === $rootScope.modalProducto.cantidadTotal) {
if (modalDistribuir.tierra !== null) {
$scope.wrapper.stockTierra.idProducto = $rootScope.modalProducto;
$scope.wrapper.stockTierra.cantidad = modalDistribuir.tierra;
}
if (modalDistribuir.bebelandia !== null) {
$scope.wrapper.stockBebelandia.idProducto = $rootScope.modalProducto;
$scope.wrapper.stockBebelandia.cantidad = modalDistribuir.bebelandia;
}
if (modalDistribuir.libertador !== null) {
$scope.wrapper.stockLibertador.idProducto = $rootScope.modalProducto;
$scope.wrapper.stockLibertador.cantidad = modalDistribuir.libertador;
}
ngDialog.open({
template: 'views/modals/distribucion/confirmacion-distribuir.html',
className: 'ngdialog-theme-advertencia',
showClose: false,
controller: 'DistribucionController',
closeByDocument: false,
closeByEscape: false,
data: {
'wrapper': $scope.wrapper,
'producto': $rootScope.modalProducto
}
});
} else {
$scope.alerts.push({
type: 'danger',
msg: 'La cantidad total de productos a distribuir debe ser igual a la cantidad total de productos en almacen.'
});
}
};
in this modal i execute a function that save the data on my API
$scope.finalizarDistribucion = function () {
$scope.sendWrapper = {
stockTierra: null,
stockBebelandia: null,
stockLibertador: null
};
if ($scope.ngDialogData.wrapper.stockTierra.idProducto !== null && $scope.ngDialogData.wrapper.stockTierra.cantidad) {
$scope.sendWrapper.stockTierra = $scope.ngDialogData.wrapper.stockTierra;
}
if ($scope.ngDialogData.wrapper.stockBebelandia.idProducto !== null && $scope.ngDialogData.wrapper.stockBebelandia.cantidad) {
$scope.sendWrapper.stockBebelandia = $scope.ngDialogData.wrapper.stockBebelandia;
}
if ($scope.ngDialogData.wrapper.stockLibertador.idProducto !== null && $scope.ngDialogData.wrapper.stockLibertador.cantidad) {
$scope.sendWrapper.stockLibertador = $scope.ngDialogData.wrapper.stockLibertador;
}
$distribute = distribucionService.add($scope.sendWrapper);
$distribute.then(function (datos) {
if (datos.status === 200) {
ngDialog.closeAll();
toaster.pop({
type: 'success',
title: 'Exito',
body: 'Se ha distribuido con exito los productos.',
showCloseButton: false
});
}
});
$scope.$emit('updateTables', $scope.ngDialogData.producto);
$scope.$emit('updateStock', {});
};
in this function i do two $emit
the first one update my object Producto in my ProductoController and send a $broadcast to update my principal table
$scope.$on('updateTables', function (event, object) {
var idFactura = parseInt($stateParams.idFactura);
object.estadoDistribucion = true;
$updateProducto = _productoService.update(object);
$updateProducto.then(function (datos) {
if (datos.status === 200) {
$rootScope.$broadcast('updateTableProducto', {'idFactura': idFactura});
}
});
});
this last works fine, reload the table without problems.
the second $emit is the problem, it must reload the another 3 tables
$scope.$on('updateStock', function () {
var idFactura = parseInt($stateParams.idFactura);
$facturaTierra = distribucionService.getStockTierra(idFactura);
$facturaTierra.then(function (datos) {
$scope.facturaTierra = datos.data;
$scope.tableFacturaTierra.reload();
});
$facturaBebelandia = distribucionService.getStockBebelandia(idFactura);
$facturaBebelandia.then(function (datos) {
$scope.facturaBebelandia = datos.data;
$scope.tableFacturaBebelandia.reload();
});
$facturaLibertador = distribucionService.getStockLibertador(idFactura);
$facturaLibertador.then(function (datos) {
$scope.facturaLibertador = datos.data;
$scope.tableFacturaLibertador.reload();
});
});
but my parameters of ngTable are undefined and the reload fails.
have somebody any idea what i'm doing wrong?
Finally after try many times i got the answer.
First in my ProductoController i did a $broadcast to my DistribucionController
$rootScope.$on('updateTableProducto', function (event, object) {
$list = _productoService.searchByIdFactura(object.idFactura);
$list.then(function (datos) {
$scope.productosFactura = datos.data;
$rootScope.$broadcast('updateStock', {});
$scope.tableProductosFactura.reload();
});
});
then on i receive this $broadcast on my another controller using
$scope.$on('updateStock', function (event, object) {
var idFactura = parseInt($stateParams.idFactura);
$facturaTierra = distribucionService.getStockTierra(idFactura);
$facturaTierra.then(function (datos) {
$scope.facturaTierra = datos.data;
$scope.tableFacturaTierra.reload();
});
$facturaBebelandia = distribucionService.getStockBebelandia(idFactura);
$facturaBebelandia.then(function (datos) {
$scope.facturaBebelandia = datos.data;
$scope.tableFacturaBebelandia.reload();
});
$facturaLibertador = distribucionService.getStockLibertador(idFactura);
$facturaLibertador.then(function (datos) {
$scope.facturaLibertador = datos.data;
$scope.tableFacturaLibertador.reload();
});
});
NOTE: if i write $rootScope.on it execute 3 times. so in $scope just make one loop.
I hope this will be helpul to someone.
I'm having an issue with Kendo Grid in Angular where the custom drop down I've implemented will not open when tab navigating to that column. The built in text and number editor fields are editable on tab navigation but my custom drop down will not expand. I have to click on it to get the drop down effect.
My goal here is to allow the user to log an an entire row of data without having to take their hands off the keyboard.
My column is defined like so:
gridColumns.push({
field: currentField.FieldName.replace(/ /g, "_"),
title: currentField.FieldName,
editor: $scope.dropDownAttEditor,
template: function (dataItem) {
return $scope.dropDownTemplate(dataItem, currentField.FieldName);
}
});
My gridOptions are defined as follows:
$scope.gridOptions = {
dataSource: new kendo.data.DataSource({
transport: {
read: {
url: appconfig.basePath + '/api/DrillHoleManager/DrillHoleInterval',
type: 'POST',
contentType: 'application/json'
},
update: {
url: appconfig.basePath + '/api/DrillHoleManager/DrillHoleIntervalUpdate',
type: 'POST',
contentType: 'application/json'
},
parameterMap: function (data, operation) {
if (operation === "read") {
data.DrillHoleId = $scope.entity.Id;
data.DrillHoleIntervalTypeId = $stateParams.ddhinttypeid;
// convert the parameters to a json object
return kendo.stringify(data);
}
if (operation === 'update') {
// build DrillHoleIntervalDto object with all ATT/CMT values to send back to server
var drillHoleInterval = { Id: data.Id, Name: data.Name, From: data.From, To: data.To };
drillHoleInterval.Attributes = [];
drillHoleInterval.Comments = [];
var attributeFields = $.grep($scope.currentFields, function (e) { return e.DrillHoleTabFieldType == DrillHoleTabFieldTypeEnum.IntervalAttribute });
$.each(attributeFields, function (idx, attributeField) {
drillHoleInterval.Attributes.push({
Id: attributeField.AttributeDto.Id,
LookupId: data[attributeField.FieldName.replace(/ /g, "_")]
});
});
var commentFields = $.grep($scope.currentFields, function (e) { return e.DrillHoleTabFieldType == DrillHoleTabFieldTypeEnum.IntervalComment });
$.each(commentFields, function (idx, commentField) {
drillHoleInterval.Comments.push({
Id: commentField.CommentDto.Id,
Value: ((data[commentField.FieldName.replace(/ /g, "_")] != "") ? data[commentField.FieldName.replace(/ /g, "_")] : null)
});
});
return kendo.stringify(drillHoleInterval);
}
// ALWAYS return options
return options;
}
},
schema: { model: { id : "Id" }},
serverPaging: false,
serverSorting: false,
serverFiltering: false
//,autoSync: true
}),
columns: gridColumns,
dataBound: onDataBound,
autoBind: false,
navigatable: true,
scrollable: false,
editable: true,
selectable: true,
edit: function (e) {
var grid = $("#ddhintgrid").data("kendoGrid");
//grid.clearSelection();
grid.select().removeClass('k-state-selected');
// select the row currently being edited
$('[data-uid=' + e.model.uid + ']').addClass('k-state-selected');
e.container[0].focus();
}
};
Here is a custom event to handle the 'Tab' keypress. The point of this is I want a new record automatically added to the grid if the user presses 'Tab' at the end of the last line:
$("#ddhintgrid").keydown(function (e) {
if (e.key == "Tab") {
var grid = $("#ddhintgrid").data("kendoGrid");
var data = grid.dataSource.data();
var selectedItem = grid.dataItem(grid.select());
var selectedIndex = null
if (selectedItem != null) {
selectedIndex = grid.select()[0].sectionRowIndex;
if (selectedIndex == data.length - 1) { // if the bottom record is selected
// We need to manually add a new record here so that the new row will automatically gain focus.
// Using $scope.addRecord() here will add the new row but cause the grid to lose focus.
var newRecord = { From: grid.dataSource.data()[selectedIndex].To };
var currentCmtFields = $.grep($scope.currentFields, function (e) { return e.DrillHoleTabFieldType == DrillHoleTabFieldTypeEnum.IntervalComment; });
$.each(currentCmtFields, function (idx, currentCmtField) {
newRecord[currentCmtField.FieldName.replace(/ /g, "_")] = null;
});
grid.dataSource.insert(data.length, newRecord);
// edit the new row
grid.editRow($("#ddhintgrid tr:eq(" + (data.length) + ")"));
}
}
}
});
Here is my template for the drop down column:
$scope.dropDownTemplate = function (dataItem, fieldName) {
var currentLookups = $.grep($scope.currentFields, function (e) { return e.FieldName == fieldName; })[0].AttributeDto.Lookups;
var selectedLookup = $.grep(currentLookups, function (e) { return e.Id == dataItem[fieldName.replace(/ /g, "_")]; })[0];
// With the custom dropdown editor when going from null to a value the entire lookup object (id, name) is placed in the
// dataItem[field_name] instead of just the id. We need to replace this object with just the id value and return the name of
// the lookup to the template.
if (typeof selectedLookup == 'undefined' && dataItem[fieldName.replace(/ /g, "_")] != null) {
selectedLookup = angular.copy(dataItem[fieldName.replace(/ /g, "_")]);
dataItem[fieldName.replace(/ /g, "_")] = selectedLookup.Id;
}
if (selectedLookup != null && selectedLookup != '') {
return selectedLookup.Name;
}
else {
return '';
}
};
And finally here is the custom editor for the drop down column:
$scope.dropDownAttEditor = function (container, options) {
var editor = $('<input k-data-text-field="\'Name\'" k-data-value-field="\'Id\'" k-data-source="ddlDataSource" data-bind="value:' + options.field + '"/>')
.appendTo(container).kendoDropDownList({
dataSource: $.grep($scope.currentFields, function (e) { return e.FieldName == options.field.replace(/_/g, ' '); })[0].AttributeDto.Lookups,
dataTextField: "Name",
dataValueField: "Id"
});
};
I know this is a lot to take in but if you have any questions just let me know.
My ultimate goal is that I want the user to be able to navigate the grid using the 'Tab' key and edit every field without having to use the mouse.