Skip to content
This repository was archived by the owner on Jan 21, 2021. It is now read-only.

Commit d5abf0b

Browse files
authored
Merge pull request #4 from Chrissi2812/feature/is-dirty
[1.x] Add isDirty property
2 parents 1fb814c + 3eb21b8 commit d5abf0b

File tree

2 files changed

+36
-1
lines changed

2 files changed

+36
-1
lines changed

src/InertiaForm.js

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,33 @@
1-
import { guardAgainstReservedFieldName, isArray, isFile, merge, objectToFormData } from './util';
1+
import {
2+
guardAgainstReservedFieldName,
3+
isArray,
4+
isFile,
5+
merge,
6+
objectToFormData,
7+
reservedFieldNames
8+
} from './util';
29

310
class InertiaForm {
411
constructor(data = {}, options = {}) {
512
this.processing = false;
613
this.successful = false;
714
this.recentlySuccessful = false;
15+
this.isDirty = false;
816

917
this.withData(data)
1018
.withOptions(options)
19+
20+
return new Proxy(this, {
21+
set(obj, prop, value) {
22+
obj[prop] = value;
23+
24+
if ((reservedFieldNames.indexOf(prop) === -1) && value !== obj.initial[prop]) {
25+
obj.isDirty = true;
26+
}
27+
28+
return true;
29+
}
30+
})
1131
}
1232

1333
static create(data = {}) {
@@ -33,13 +53,16 @@ class InertiaForm {
3353
this[field] = data[field];
3454
}
3555

56+
this.isDirty = false;
57+
3658
return this;
3759
}
3860

3961
withOptions(options) {
4062
this.__options = {
4163
bag: 'default',
4264
resetOnSuccess: true,
65+
setInitialOnSuccess: false,
4366
};
4467

4568
if (options.hasOwnProperty('bag')) {
@@ -50,6 +73,10 @@ class InertiaForm {
5073
this.__options.resetOnSuccess = options.resetOnSuccess;
5174
}
5275

76+
if (options.hasOwnProperty('setInitialOnSuccess')) {
77+
this.__options.setInitialOnSuccess = options.setInitialOnSuccess;
78+
}
79+
5380
return this;
5481
}
5582

@@ -79,6 +106,8 @@ class InertiaForm {
79106

80107
reset() {
81108
merge(this, this.initial);
109+
110+
this.isDirty = false;
82111
}
83112

84113
setInitialValues(values) {
@@ -172,6 +201,10 @@ class InertiaForm {
172201

173202
if (this.__options.resetOnSuccess) {
174203
this.reset();
204+
} else if (this.__options.setInitialOnSuccess) {
205+
const { _error_bag, ...data } = this.data();
206+
this.setInitialValues(data);
207+
this.isDirty = false;
175208
}
176209
}
177210

src/util/fieldNameValidation.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,14 @@ export const reservedFieldNames = [
99
'errorsFor',
1010
'hasErrors',
1111
'initial',
12+
'isDirty',
1213
'onFail',
1314
'onSuccess',
1415
'patch',
1516
'post',
1617
'processing',
1718
'put',
19+
'recentlySuccessful',
1820
'reset',
1921
'submit',
2022
'successful',

0 commit comments

Comments
 (0)