Custom resolver React-hook-form - react-hook-form

Can't get errors from resolver using react-hook-form custom resolvers. Trying to validate some fields dynamically. But if I submit form I can get errors fields
export const customResolver = (parameters) => {
return (values, _context, { fields, names }) => {
const transformedParameters = transformParameters(parameters);
const paramsIds = getParamsIds(transformedParameters);
const { name, value } = Object.values(fields)[0];
let errors = {};
if (names && names[0].length <= 3) {
// Validate single field
const textRequired = transformedParameters
.find(({ id }) => id === name)
.values.find(({ name: valueName }) => value === valueName).textRequired;
if (textRequired && !values[`${names} commentary`]) {
errors = {
[`${names} commentary`]: {
type: "required",
message: "Поле необходимо заполнить!",
},
};
}
} else {
// Validate onSubmit method
errors = Object.entries(values).reduce((acc, [id, fieldValue]) => {
if (paramsIds.includes(id) && !fieldValue) {
return {
...acc,
[id]: { type: "required", message: "Поле необходимо заполнить!" },
};
}
return acc;
}, {});
}
return { values, errors };
};
};
What did I do wrong?

Related

Apple Pay using #stripe/stripe-react-native is not working showing some hook call error

When i am trying to implement Apple Pay using #stripe/stripe-react-native then is not working showing some hook call , Code & Error showing below:
import { StripeProvider, useApplePay} from '#stripe/stripe-react-native';
const { presentApplePay, confirmApplePayPayment } = useApplePay();
export default class App (){
handlePayPress = async () => {
const {error, paymentMethod} = await presentApplePay({
cartItems: [
{
label: 'payment label',
amount: '50', // amount as string
type: 'final',
},
],
country: 'US', // enter any country code supported by stripe,
currency: 'USD', // enter any currency supported by stripe,
});
if (error) {
Alert.alert(error.code, error.message);
} else {
const {error: confirmApplePayError} = await confirmApplePayPayment(
clientSecret,
);
confirmApplePayPayment(clientSecret);
if (confirmApplePayError) {
Alert.alert(confirmApplePayError.code, confirmApplePayError.message);
} else {
Alert.alert('Success', 'The payment was confirmed successfully!');
}
}
};
...
...
}
You can create a seperate functional component for that and call in your class component like this
export default class App (){
render() {
return(
<ApplePayFunction data={'your data here'}/>
);
}
}
export default function ApplePayFunction(props) {
const { presentApplePay, confirmApplePayPayment } = useApplePay();
const handlePayPress = async () => {
const { error, paymentMethod } = await presentApplePay({
cartItems: [
{
label: "payment label",
amount: "50", // amount as string
type: "final",
},
],
country: "US", // enter any country code supported by stripe,
currency: "USD", // enter any currency supported by stripe,
});
if (error) {
Alert.alert(error.code, error.message);
} else {
const { error: confirmApplePayError } = await confirmApplePayPayment(
clientSecret
);
confirmApplePayPayment(clientSecret);
if (confirmApplePayError) {
Alert.alert(confirmApplePayError.code, confirmApplePayError.message);
} else {
Alert.alert("Success", "The payment was confirmed successfully!");
}
}
};
// Return UI Views below
return null;
}
Hooks must always be called inside functional components. Code refactor for reference.
import { StripeProvider, useApplePay } from "#stripe/stripe-react-native";
export default function App() {
const { presentApplePay, confirmApplePayPayment } = useApplePay();
const handlePayPress = async () => {
const { error, paymentMethod } = await presentApplePay({
cartItems: [
{
label: "payment label",
amount: "50", // amount as string
type: "final",
},
],
country: "US", // enter any country code supported by stripe,
currency: "USD", // enter any currency supported by stripe,
});
if (error) {
Alert.alert(error.code, error.message);
} else {
const { error: confirmApplePayError } = await confirmApplePayPayment(
clientSecret
);
confirmApplePayPayment(clientSecret);
if (confirmApplePayError) {
Alert.alert(confirmApplePayError.code, confirmApplePayError.message);
} else {
Alert.alert("Success", "The payment was confirmed successfully!");
}
}
};
// Return UI Views below
return null;
}

Ng2-Charts Unexpected change chart's color when data is changed

In my project I use ng2-charts. All works fine and chart is shown as expected (data, labels, chart's colors), but when data is changed then color of chart become grey by default. May someone help to correct problem with chart's color?
Here is my code:
import { ChartDataSets } from 'chart.js';
import { Color, Label } from 'ng2-charts';
...
export class JuridicalBidPrimaryComponent extends BidComponent {
lineChartData: ChartDataSets[];
lineChartLabels: Label[];
lineChartLegend = true;
lineChartType = 'line';
lineChartColors: Color[] = [
{
backgroundColor: 'rgba(148,159,177,0.2)',
borderColor: 'rgba(148,159,177,1)'
},
{
backgroundColor: 'rgba(77,83,96,0.2)',
borderColor: 'rgba(77,83,96,1)'
}];
options: any = {
legend: { position: 'bottom' }
}
constructor(
...//inject services
) {
super();
this.initData();
};
initData(): void {
this.lineChartData = [];
this.lineChartLabels = [];
if (this.cabinetId)
this.getData(this.year);
}
getData(year: number) {
this.isLoading = true;
var limitPromise = this.juridicalLimitService.getPrimary(this.cabinetId, year).catch(error => {
this.notificationService.error(error);
return Observable.throw(error);
});
var analyticsPromise = this.juridicalAnalyticsService.getUsedEnergy(this.cabinetId, year).catch(error => {
this.notificationService.error(error);
return Observable.throw(error);
});
forkJoin([limitPromise, analyticsPromise]).subscribe(data => {
this.limits = data[0];
this.lineChartLabels = data[1].map(e => e.Period);
this.lineChartData.push(
{
data: data[1].map(e => e.Limit),
label: 'Bid'
},
{
data: data[1].map(e => e.Used),
label: 'Used'
}
);
this.isLoading = false;
}, error => {
this.isLoading = false;
});
}
}
export abstract class BidComponent {
cabinetId: number;
isLoading: boolean = false;
#Input("periods") periods: BaseDictionary[];
#Input("cabinetId") set CabinetId(cabinetId: number) {
this.cabinetId = cabinetId;
this.initData();
}
abstract initData(): void;
}
As you can see this component is partial and I use setter to listen of cabinetId changes.
Here is html part:
...
<canvas baseChart width="400" height="150"
[options]="options"
[datasets]="lineChartData"
[labels]="lineChartLabels"
[legend]="lineChartLegend"
[chartType]="lineChartType"
[colors]="lineChartColors"></canvas>
...
And I use this component as:
<app-juridical-bid-primary [cabinetId]="cabinetId"></app-juridical-bid-primary>
I find similar question similar question, but, unfortunately, don't understand answer
After some hours of code testing I find answer. It is needed to correct code from question:
...
import * as _ from 'lodash'; //-- useful library
export class JuridicalBidPrimaryComponent extends BidComponent {
lineChartData: ChartDataSets[] = [];
lineChartLabels: Label[] = [];
...
initData(): void {
/*this.lineChartData = [];
this.lineChartLabels = [];*/ //-- this lines is needed to remove
if (this.cabinetId)
this.getData(this.year);
}
getData(year: number) {
...
forkJoin([limitPromise, analyticsPromise]).subscribe(data => {
this.limits = data[0];
this.lineChartLabels.length = 0;
this.lineChartLabels.push(...data[1].map(e => e.Period));
if (_.isEmpty(this.lineChartData)) {
//-- If data array is empty, then we add data series
this.lineChartData.push(
{
data: data[1].map(e => e.Limit),
label: 'Замовлені величини'
},
{
data: data[1].map(e => e.Used),
label: 'Використано'
}
);
} else {
//-- If we have already added data series then we only change data in data series
this.lineChartData[0].data = data[1].map(e => e.Limit);
this.lineChartData[1].data = data[1].map(e => e.Used);
}
this.isLoading = false;
}, error => {
this.isLoading = false;
});
}
}
As I understand ng2-charts, if we clean dataset (lineChartData) and add new data then the library understand this as create new series and don't use primary settings for the ones. So we have to use previous created series.
I hope it will be useful for anyone who will have such problem as I have.

Can I run `stencil push` command without prompt?

I'm trying to configure bitbucket pipelines with bigcommerce stencil.
The problem is the stencil push command asks some questions. I would like to auto-respond those questions.
Is that possible?
These are the questions prompted:
* Would you like to apply your theme to your store at http://xxxxxxx/? (y/N)
* Which variation would you like to apply?
- Light
- Bold
- Warm
You will need to make changes to the existing stencil-cli to make this work.
Stencil-cli uses the Commander package. My solution was to create an additional flag that would skip all the prompts if you supplied a variant name. This was created from stencil-cli version 1.13.1 so you may need to modify the example.
Inside /bin/stencil-push:
#!/usr/bin/env node
require('colors');
const apiHost = 'https://api.bigcommerce.com';
const dotStencilFilePath = './.stencil';
const options = { dotStencilFilePath };
const pkg = require('../package.json');
const Program = require('commander');
const stencilPush = require('../lib/stencil-push');
const versionCheck = require('../lib/version-check');
Program
.version(pkg.version)
.option('--host [hostname]', 'specify the api host', apiHost)
.option('-f, --file [filename]', 'specify the filename of the bundle to upload')
.option('-a, --activate [variationname]', 'specify the variation of the theme to activate')
.parse(process.argv);
if (!versionCheck()) {
return;
}
stencilPush(Object.assign({}, options, {
apiHost: Program.host || apiHost,
bundleZipPath: Program.file,
activate: Program.activate,
}), (err, result) => {
if (err) {
console.log('not ok'.red + ` -- ${err}`);
console.log('Please try again. If this error persists, please visit https://github.com/bigcommerce/stencil-cli/issues and submit an issue.');
} else {
console.log('ok'.green + ` -- ${result}`);
}
});
Inside /lib/stencil-push.js:
'use strict';
const _ = require('lodash');
const async = require('async');
const Bundle = require('./stencil-bundle');
const fs = require('fs');
const Inquirer = require('inquirer');
const os = require('os');
const ProgressBar = require('progress');
const themeApiClient = require('./theme-api-client');
const themePath = process.cwd();
const themeConfig = require('./theme-config').getInstance(themePath);
const uuid = require('uuid4');
const utils = {};
const Wreck = require('wreck');
const bar = new ProgressBar('Processing [:bar] :percent; ETA: :etas', {
complete: '=',
incomplete: ' ',
total: 100,
});
module.exports = utils;
function validateOptions(options, fields) {
options = options || {};
fields = fields || [];
fields.forEach(field => {
if (!_.has(options, field)) {
throw new Error(`${field} is required!`);
}
});
return options;
}
utils.readStencilConfigFile = (options, callback) => {
options = validateOptions(options, ['dotStencilFilePath']);
fs.readFile(options.dotStencilFilePath, { encoding: 'utf8' }, (err, data) => {
if (err) {
err.name = 'StencilConfigReadError';
return callback(err);
}
callback(null, Object.assign({}, options, {
config: JSON.parse(data),
}));
});
};
utils.getStoreHash = (options, callback) => {
options = validateOptions(options, ['config.normalStoreUrl']);
Wreck.get(`${options.config.normalStoreUrl}/admin/oauth/info`, { json: true, rejectUnauthorized: false }, (error, response, payload) => {
if (error) {
error.name = 'StoreHashReadError';
return callback(error);
}
if (response.statusCode !== 200 || !payload.store_hash) {
const err = new Error('Failed to retrieve store hash');
err.name = 'StoreHashReadError';
return callback(err);
}
callback(null, Object.assign({}, options, { storeHash: payload.store_hash }));
});
};
utils.getThemes = (options, callback) => {
const config = options.config;
themeApiClient.getThemes({
accessToken: config.accessToken,
apiHost: options.apiHost,
clientId: config.clientId,
storeHash: options.storeHash,
}, (error, result) => {
if (error) {
return callback(error);
}
callback(null, Object.assign({}, options, {
themes: result.themes,
}));
});
};
utils.generateBundle = (options, callback) => {
let bundle;
if (options.bundleZipPath) {
return async.nextTick(callback.bind(null, null, options));
}
bundle = new Bundle(themePath, themeConfig, themeConfig.getRawConfig(), {
dest: os.tmpdir(),
name: uuid(),
});
bundle.initBundle((err, bundleZipPath) => {
if (err) {
err.name = 'BundleInitError';
return callback(err);
}
callback(null, Object.assign(options, { bundleZipPath: options.bundleZipPath || bundleZipPath }));
});
};
utils.uploadBundle = (options, callback) => {
const config = options.config;
themeApiClient.postTheme({
accessToken: config.accessToken,
apiHost: options.apiHost,
bundleZipPath: options.bundleZipPath,
clientId: config.clientId,
storeHash: options.storeHash,
}, (error, result) => {
if (error) {
error.name = 'ThemeUploadError';
return callback(error);
}
callback(null, Object.assign({}, options, {
jobId: result.jobId,
themeLimitReached: !!result.themeLimitReached,
}));
});
};
utils.notifyUserOfThemeLimitReachedIfNecessary = (options, callback) => {
if (options.themeLimitReached) {
console.log('warning'.yellow + ` -- You have reached your upload limit. In order to proceed, you'll need to delete at least one theme.`);
}
return async.nextTick(callback.bind(null, null, options));
};
utils.promptUserToDeleteThemesIfNecessary = (options, callback) => {
if (!options.themeLimitReached) {
return async.nextTick(callback.bind(null, null, options));
}
const questions = [{
choices: options.themes.map(theme => ({
disabled: theme.is_active || !theme.is_private,
name: theme.name,
value: theme.uuid,
})),
message: 'Which theme(s) would you like to delete?',
name: 'themeIdsToDelete',
type: 'checkbox',
validate: (val) => {
if (val.length > 0) {
return true;
} else {
return 'You must delete at least one theme';
}
},
}];
Inquirer.prompt(questions, (answers) => {
callback(null, Object.assign({}, options, answers));
});
};
utils.deleteThemesIfNecessary = (options, callback) => {
const config = options.config;
if (!options.themeLimitReached) {
return async.nextTick(callback.bind(null, null, options));
}
async.parallel(options.themeIdsToDelete.map(themeId => {
return cb => {
themeApiClient.deleteThemeById(Object.assign({
accessToken: config.accessToken,
apiHost: options.apiHost,
clientId: config.clientId,
storeHash: options.storeHash,
themeId,
}, options), cb);
}
}), err => {
if (err) {
err.name = 'ThemeDeletionError';
return callback(err);
}
callback(null, options);
})
};
utils.uploadBundleAgainIfNecessary = (options, callback) => {
if (!options.themeLimitReached) {
return async.nextTick(callback.bind(null, null, options));
}
utils.uploadBundle(options, callback);
};
utils.notifyUserOfThemeUploadCompletion = (options, callback) => {
console.log('ok'.green + ' -- Theme Upload Finished');
return async.nextTick(callback.bind(null, null, options));
};
utils.markJobProgressPercentage = percentComplete => {
bar.update(percentComplete / 100);
};
utils.markJobComplete = () => {
utils.markJobProgressPercentage(100);
console.log('ok'.green + ' -- Theme Processing Finished');
};
utils.pollForJobCompletion = () => {
return async.retryable({
interval: 1000,
errorFilter: err => {
if (err.name === "JobCompletionStatusCheckPendingError") {
utils.markJobProgressPercentage(err.message);
return true;
}
return false;
},
times: Number.POSITIVE_INFINITY,
}, utils.checkIfJobIsComplete);
};
utils.checkIfJobIsComplete = (options, callback) => {
const config = options.config;
themeApiClient.getJob({
accessToken: config.accessToken,
apiHost: options.apiHost,
clientId: config.clientId,
storeHash: options.storeHash,
bundleZipPath: options.bundleZipPath,
jobId: options.jobId,
}, (error, result) => {
if (error) {
return callback(error);
}
utils.markJobComplete();
callback(null, Object.assign({}, options, result));
});
};
utils.promptUserWhetherToApplyTheme = (options, callback) => {
if (options.activate) {
callback(null, Object.assign({}, options, { applyTheme: true }));
} else {
const questions = [{
type: 'confirm',
name: 'applyTheme',
message: `Would you like to apply your theme to your store at ${options.config.normalStoreUrl}?`,
default: false,
}];
Inquirer.prompt(questions, answers => {
callback(null, Object.assign({}, options, { applyTheme: answers.applyTheme }));
});
};
};
utils.getVariations = (options, callback) => {
if (!options.applyTheme) {
return async.nextTick(callback.bind(null, null, options));
}
themeApiClient.getVariationsByThemeId({
accessToken: options.accessToken,
apiHost: options.apiHost,
clientId: options.clientId,
themeId: options.themeId,
storeHash: options.storeHash,
}, (error, result) => {
if (error) {
return callback(error);
};
if (options.activate !== true && options.activate !== undefined) {
const findVariation = result.variations.find(item => item.name === options.activate);
callback(null, Object.assign({}, options, { variationId: findVariation.uuid }));
} else if (options.activate === true) {
callback(null, Object.assign({}, options, { variationId: result.variations[0].uuid }));
} else {
callback(null, Object.assign({}, options, result));
};
});
};
utils.promptUserForVariation = (options, callback) => {
if (!options.applyTheme) {
return async.nextTick(callback.bind(null, null, options))
}
if (options.variationId) {
callback(null, options);
} else {
const questions = [{
type: 'list',
name: 'variationId',
message: 'Which variation would you like to apply?',
choices: options.variations.map(variation => ({ name: variation.name, value: variation.uuid })),
}];
Inquirer.prompt(questions, answers => {
console.log(answers);
callback(null, Object.assign({}, options, answers));
});
};
};
utils.requestToApplyVariationWithRetrys = () => {
return async.retryable({
interval: 1000,
errorFilter: err => {
if (err.name === "VariationActivationTimeoutError") {
console.log('warning'.yellow + ` -- Theme Activation Timed Out; Retrying...`);
return true;
}
return false;
},
times: 3,
}, utils.requestToApplyVariation);
};
utils.requestToApplyVariation = (options, callback) => {
if (!options.applyTheme) {
return async.nextTick(callback.bind(null, null, options));
}
themeApiClient.activateThemeByVariationId({
accessToken: options.accessToken,
apiHost: options.apiHost,
clientId: options.clientId,
storeHash: options.storeHash,
variationId: options.variationId,
}, (error, result) => {
if (error) {
return callback(error);
}
callback(null, Object.assign({}, options, result));
});
};
utils.notifyUserOfCompletion = (options, callback) => {
callback(null, 'Stencil Push Finished');
};
This allowed me to use something like stencil push --activate bold to specify a variation and skip all of the prompts.
As of version 1.15.1 this seems to be available with the -a, --activate [variationname] switch for stencil push
> stencil push -a "My Variant" worked for me
Thanks Nikita Puza!
It works like a charm. I applied the changes on stencil 1.14.1 version and the source code looks exactly the same.
The only difference is the second file is called stencil-push.utils.js instead of stencil-push.js

stripe create user firebase cloud functions

I am attempting to create a stripe user upon user creation for firebase, I keep receiving this error (error displayed below). the code for the function is also displayed below. if I need to post the database structure I will do so, I currently do not have any structure for stripe customer (this might be where issue occurs). if anyone can assist I would greatly appreciate it.
Error:
Error: Reference.child failed: First argument was an invalid path = "/stripe_customers/${data.uid}/customer_id". Paths must be non-empty strings and can't contain ".", "#", "$", "[", or "]"
at Object.exports.validatePathString (/user_code/node_modules/firebase-admin/node_modules/#firebase/database/dist/cjs/src/core/util/validation.js:282:15)
at Object.exports.validateRootPathString (/user_code/node_modules/firebase-admin/node_modules/#firebase/database/dist/cjs/src/core/util/validation.js:293:13)
at Reference.child (/user_code/node_modules/firebase-admin/node_modules/#firebase/database/dist/cjs/src/api/Reference.js:72:30)
at Database.ref (/user_code/node_modules/firebase-admin/node_modules/#firebase/database/dist/cjs/src/api/Database.js:60:54)
at stripe.customers.create.then (/user_code/index.js:41:29)
at tryCatcher (/user_code/node_modules/stripe/node_modules/bluebird/js/release/util.js:16:23)
at Promise._settlePromiseFromHandler (/user_code/node_modules/stripe/node_modules/bluebird/js/release/promise.js:512:31)
at Promise._settlePromise (/user_code/node_modules/stripe/node_modules/bluebird/js/release/promise.js:569:18)
at Promise._settlePromise0 (/user_code/node_modules/stripe/node_modules/bluebird/js/release/promise.js:614:10)
at Promise._settlePromises (/user_code/node_modules/stripe/node_modules/bluebird/js/release/promise.js:693:18)
at Async._drainQueue (/user_code/node_modules/stripe/node_modules/bluebird/js/release/async.js:133:16)
at Async._drainQueues (/user_code/node_modules/stripe/node_modules/bluebird/js/release/async.js:143:10)
at Immediate.Async.drainQueues (/user_code/node_modules/stripe/node_modules/bluebird/js/release/async.js:17:14)
at runCallback (timers.js:672:20)
at tryOnImmediate (timers.js:645:5)
at processImmediate [as _immediateCallback] (timers.js:617:5)
Functions:
'use strict';
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const logging = require('#google-cloud/logging')();
admin.initializeApp(functions.config().firebase);
const stripe = require('stripe')(functions.config().stripe.token);
const currency = functions.config().stripe.currency || 'USD';
//[START chargecustomer]
//charge the stripe customer whenever an amount is written to the realtime database
exports.createStripeCharge = functions.database.ref('/stripe_customers/{userId}/charges/{id}').onWrite((event) => {
const val = event.data.val();
if (val === null || val.id || val.error) return null;
return admin.database().ref(`/stripe_customers/${event.params.userId}/customer_id`).once('value').then((snapshot) => {
return snapshot.val();
}).then((customer) => {
const amount = val.amount;
const idempotency_key = event.params.id;
let charge = {amount, currency, customer};
if (val.source !== null) charge.source = val.source;
return stripe.charges.create(charge, {idempotency_key});
}).then((response) => {
return event.data.adminRef.set(response);
}).catch((error) => {
return event.data.adminRef.child('error').set(userFacingMessage(error));
}).then(() => {
return reportError(error, {user: events.params.userId});
});
});
// [end chargecustomer]]
// when user is created register them with stripe
exports.createStripeCustomer = functions.auth.user().onCreate((event) => {
const data = event.data;
return stripe.customers.create({
email: data.email,
}).then((customer) => {
return admin.database().ref(`/stripe_customers/${data.uid}/customer_id`).set(customer.id);
});
});
// add a payment source (card) for a user by writing a stripe payment source token to realtime database
exports.addPaymentSource =. functions.database.ref('/stripe_customers/{userId}/sources/{pushId}/token').onWrite((event) => {
const source = event.data.val();
if (sourve === null) return null;
return admin.database.ref(`/stripe_customers/${event.params.userId}/customer_id`).once('value').then((snapshot) => {
return snapshot.val();
}).then((customer) => {
return stripe.customers.createSource(customer, {source});
}).then((response) => {
return event.data.adminRef.parent.set(response);
}, (error) => {
return event.data.adminRef.parent.child('error').set(userFacingMessage(error));
}).then(() => {
return reportError(error, {user: event.params.userId});
});
});
// when a user deletes their account, clean up after the
exports.cleanupUser = functions.auth.user().onDelete((event) => {
return admin.database().ref(`/stripe_customers/${event.data.uid}`).once('value').then((snapshot) => {
return snapshot.val();
}).then((customer) => {
return stripe.customers.del(customer.customer_id);
}).then(() => {
return admin.database().ref(`/stripe_customers/${event.data.uid}`).remove();
});
});
function reportError(err, context = {}) {
const logName = 'errors';
const lof = logging.log(logName);
const metadata = {
resource: {
type: 'cloud_function',
labels: {function_name: process.env.FUNCTION_NAME},
},
};
const errorEvent = {
message: err.stack,
serviceContext: {
service: process.env.FUNCTION_NAME,
resourceType: 'cloud_function',
},
context: context,
};
return new Promise((resolve, reject) => {
log.write(log.entry(metadata, errorEvent), (error) => {
if (error) {
reject(error);
}
resolve();
});
});
}
// end [reportError]
// sanitize the error message for the user
function userFacingMessage(error) {
returnerror.type ? error.message : 'an error occurred, developers have been altered';
}
Database Structure:
In your code you have this:
ref('/stripe_customers/${event.params.userId}/customer_id')
this ${event.params.userId} should give you the value of the wildcard, but since you are using ' it is including the $ in the path also. So you need to change it like this:
ref(`/stripe_customers/${event.params.userId}/customer_id`)
by changing ' to `

Kendo UI Treelist rows disappears after editing

I use Kendo UI in ASP .NET MVC app. I have Kendo Treelist. Sometimes, after editing a row, all rows disappear, and I see only root element without child rows. Is it Kendo bug?Or I can prevent it? And when rows have disappeared, I refresh page, do the same changes and save treelist - the treelist works correctly.
var parsedXmlDataInJson = #Html.Raw(#ViewBag.XmlData); //jsonarray data
$( document ).ready(function() {
});
function ShowMessage(message,timeout) //пока сообщению пользователю в левом верхнем углу
{
var divMessage = $('#toggler');
if(divMessage.css('display') != 'none')
{
divMessage.clearQueue();
divMessage.stop();
divMessage.css('display','none');
}
if (timeout == 0)
divMessage.text(message).toggle('slow');
else
divMessage.text(message).toggle('slow').delay(timeout).toggle('slow');
}
var treelistds = new kendo.data.TreeListDataSource({ //CRUD for dataSource
transport: {
read: function(e) {
e.success(parsedXmlDataInJson);
},
update: function(e) {
var updatedItem = e.data;
$.each(parsedXmlDataInJson, function(indx, value) {
if (value.id == updatedItem.Id) {
value = updatedItem;
return false;
}
});
e.success();
},
create: function(e) {//Works for root element when editing only once - it's broke my treelist.
e.data.Id = GetId();
parsedXmlDataInJson.push(e.data);
e.success(e.data);
},
destroy: function(e) {
var updatedItem = e.data;
$.each(parsedXmlDataInJson, function(indx, value) {
if (value.id == updatedItem.Id) {
parsedXmlDataInJson.splice(indx, 1);
}
});
e.success();
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return {
models: kendo.stringify(options.models)
};
}
}
},
batch: false,
schema: {
model: {
id: "Id",
parentId: "parentId",
fields: {
Id: {
type: "number",
editable: true,
nullable: false
},
parentId: {
field: "parentId",
nullable: true
}
}
}
}
});
$("#treeList").kendoTreeList({
resizable: true,
dataSource: treelistds,
toolbar: ["create"],
columns: [{
field: "typeAndAttributes",
width:400
}, {
field: "text",
title: "Текст",
}, {
field: "cData",
title: "CDATA",
}, { //my custom command
command: ["edit", "destroy", "createchild", {
name: "commentOut",
text: "commentOut",
click: function(e) {
var dataItem = this.dataItem($(e.target).closest("tr")); ///my custom command
dataItem.commentedOut = !dataItem.commentedOut;
var isCommentedOut = dataItem.commentedOut;
var childNotes = this.dataSource.childNodes(dataItem);
childNotes.forEach(function(childModel, i) //
{
childModel.commentedOut = isCommentedOut;
SetChildrenIsCommentedOut(childModel, isCommentedOut);
})
//обновляем цвет и текст кнопок у всех элементов вызывая dataBound
$("#treeList").data("kendoTreeList").refresh();
},
}, ]
}],
messages: {
commands: {
edit: "Изменить",
destroy: "Удалить",
createchild: "Добавить"
}
},
dataBound: function(e) {
this.autoFitColumn(3);
Databound(e.sender, e.sender.table.find("tr"));
},
editable: true,
editable: {
mode: "popup",
template: kendo.template($("#popup-editor").html()),
window: {
width:800
}
},
edit: function(e) { //invokes when popup open
$("#date").kendoDateTimePicker({
});
$("#cDataEditor").kendoEditor({
tools: [
"formatting", "bold", "italic", "underline", "insertUnorderedList",
"insertOrderedList", "indent", "outdent", "createLink", "unlink"
],
resizable: {
content: true,
toolbar: true,
max:350
}
});
//my custom logic. Popup contains many fileds splitted from one model field
if (!e.model.isNew()) { //split typeAndAttrubites to popup's fileds
var fileds = e.model.typeAndAttributes.split(';').
filter(function(v) {
return v !== ''
});
e.container.find("#type").val(fileds[0]);
var length = fileds.length;
for (i = 1; i < length; i++) {
var keyAndValue = fileds[i].split('=');
if (keyAndValue[0] != "id")
e.container.find("#" + keyAndValue[0].trim()).val(keyAndValue[1].trim());
else
e.container.find("#xmlId").val(keyAndValue[1].trim());
}
}
},
save: function(e) { //invokes when saving
var splitter = "; ";
var inputValue = $("input[id='type']").val().trim();
if (e.model.type !== undefined) {
e.model.typeAndAttributes = e.model.type;
} else {
e.model.typeAndAttributes = inputValue;
}
var allInputs = $(":input[data-appointment=attributes]");
allInputs.each(function(index, input) { //collect inputs in one filed
var attrName;
var attrValue;
if (input.id != "id") {
attrName = input.id;
e.model[attrName];
} else {
attrName = "id";
attrValue = e.model["xmlId"];
}
//значение изменили и оно не пустое
if (attrValue !== undefined && attrValue !== "") {
if (attrValue == false)
return true;
e.model.typeAndAttributes += splitter + attrName + "=" + attrValue;
}
//my custom logic
else if (input.value.trim() && input.value != "on") {
e.model.typeAndAttributes += splitter + attrName + "=" + input.value.trim();
}
})
}
});
//рекурсивно помечаем ряды как закомментированные или нет
function SetChildrenIsCommentedOut(dataItem, isCommentedOut) {
var childNotes = $("#treeList").data("kendoTreeList").dataSource.childNodes(dataItem);
childNotes.forEach(function(childModel, i) {
childModel.commentedOut = isCommentedOut;
SetChildrenIsCommentedOut(childModel, isCommentedOut);
})
}
//Раскрашивает строки соответственно значению закомментировано или нет
function Databound(sender, rows) {
rows.each(function(idx, row) {
var dataItem = sender.dataItem(row);
if (dataItem.commentedOut) {
//обозначаем ряд как закомментированный
$(row).css("background", "#DCFFE0");
$(row).find("[data-command='commentout']").html("Раскомментировать");
} else {
//обозначаем ряд как незакомментированный
$(row).css("background", "");
$(row).find("[data-command='commentout']").html("Закомментировать");
}
})
}
});
var currentId = 0;
function GetId() { //генерирование Id для новых записей
var dataSource = $("#treeList").data("kendoTreeList").dataSource;
do {
currentId++;
var dataItem = dataSource.get(currentId);
} while (dataItem !== undefined)
return currentId;
}

Resources