Skip to content

Commit 20a4d90

Browse files
committed
Allow setFieldValue to accept a dotted path ...
e.g. you can do setFieldValue('replicator.1.foo', 'bar') to update the foo field on the second replicator set to bar This uses the eventual underscore 'set' method from jashkenas/underscore#2961. Once it's merged we can call the method directly and not need to include these files.
1 parent 5ff2732 commit 20a4d90

File tree

3 files changed

+43
-1
lines changed

3 files changed

+43
-1
lines changed

resources/js/bootstrap/globals.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { marked } from 'marked';
22
import { translate, translateChoice } from '../translations/translator';
3+
import { default as set } from './set';
34

45
export function cp_url(url) {
56
url = Statamic.$config.get('cpUrl') + '/' + url;
@@ -34,6 +35,10 @@ export function data_get(obj, path, fallback=null) {
3435
return value !== undefined ? value : fallback;
3536
};
3637

38+
export function data_set(obj, path, value) {
39+
set(obj, path.split('.'), value);
40+
}
41+
3742
export function clone(value) {
3843
if (value === undefined) return undefined;
3944

resources/js/bootstrap/set.js

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import isObject from 'underscore/modules/isObject.js';
2+
import toPath from 'underscore/modules/_toPath.js';
3+
import contains from 'underscore/modules/contains.js';
4+
5+
6+
var arrayIndex = /^\d+$/;
7+
8+
// Internal function of `set`.
9+
function deepSet(obj, path, value) {
10+
var key = path[0];
11+
12+
if (path.length === 1) {
13+
obj[key] = value;
14+
return;
15+
}
16+
17+
if (!isObject(obj[key])) {
18+
var nextKey = path[1];
19+
obj[key] = arrayIndex.test(nextKey) ? [] : {};
20+
}
21+
22+
return deepSet(obj[key], path.slice(1), value);
23+
}
24+
25+
// Set the value on `path` of `object`.
26+
// If any property in `path` does not exist it will be created.
27+
// Returns mutated object (`obj`).
28+
export default function set(obj, path, value) {
29+
path = toPath(path);
30+
31+
if (!isObject(obj) || !path.length) return obj;
32+
if (contains(path, '__proto__')) throw new Error('Prototype assignment attempted');
33+
34+
deepSet(obj, path, value);
35+
36+
return obj;
37+
}

resources/js/components/publish/Container.vue

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ export default {
111111
mutations: {
112112
setFieldValue(state, payload) {
113113
const { handle, value } = payload;
114-
state.values[handle] = value;
114+
data_set(state.values, handle, value);
115115
},
116116
setValues(state, values) {
117117
state.values = values;

0 commit comments

Comments
 (0)