我想保存AlloyUI FormBuilder
的用户选定和预定义字段。我曾尝试使用JSON.stringify(formBuilder.get('fields'))
,但我收到以下错误:
Uncaught TypeError: Converting circular structure to JSON
如何保存(和恢复)AlloyUI FormBuilder
的字段?
答案 0 :(得分:0)
为了保存AlloyUI FormBuilder
的字段,您可以使用field.getAttributesForCloning()
来获取重要的字段属性。然后,您可以将这些属性组合到一个数组中。最后,您可以将数组转换为JSON以使用JSON.stringify()
保存它:
var fields = [];
formBuilder.get('fields').each(function(field) {
fields.push(field.getAttributesForCloning());
});
fields = JSON.stringify(fields);
如果要恢复字段,可以在JSON上使用JSON.parse()
:
new Y.FormBuilder({
/* ...your code here... */
fields: JSON.parse(fields)
}).render();
这是使用AlloyUI's example FormBuilder
code的可运行示例:
YUI().use('aui-form-builder', function(Y) {
var formBuilder = new Y.FormBuilder({
availableFields: [{
iconClass: 'form-builder-field-icon-text',
id: 'uniqueTextField',
label: 'Text',
readOnlyAttributes: ['name'],
type: 'text',
unique: true,
width: 75
}, {
hiddenAttributes: ['tip'],
iconClass: 'form-builder-field-icon-textarea',
label: 'Textarea',
type: 'textarea'
}, {
iconClass: 'form-builder-field-icon-checkbox',
label: 'Checkbox',
type: 'checkbox'
}, {
iconClass: 'form-builder-field-icon-button',
label: 'Button',
type: 'button'
}, {
iconClass: 'form-builder-field-icon-select',
label: 'Select',
type: 'select'
}, {
iconClass: 'form-builder-field-icon-radio',
label: 'Radio Buttons',
type: 'radio'
}, {
iconClass: 'form-builder-field-icon-fileupload',
label: 'File Upload',
type: 'fileupload'
}, {
iconClass: 'form-builder-field-icon-fieldset',
label: 'Fieldset',
type: 'fieldset'
}],
boundingBox: '#myFormBuilder',
fields: [{
label: 'City',
options: [{
label: 'Ney York',
value: 'new york'
}, {
label: 'Chicago',
value: 'chicago'
}],
predefinedValue: 'chicago',
type: 'select'
}, {
label: 'Colors',
options: [{
label: 'Red',
value: 'red'
}, {
label: 'Green',
value: 'green'
}, {
label: 'Blue',
value: 'blue'
}],
type: 'radio'
}]
}).render();
Y.one('#resetFormBuilder').on('click', function(event) {
var fields = [];
formBuilder.get('fields').each(function(field) {
fields.push(field.getAttributesForCloning());
});
fields = JSON.stringify(fields);
formBuilder.destroy();
event.target.set('style', 'display: none;');
new Y.FormBuilder({
/* ...your code here... */
boundingBox: '#myFormBuilder',
fields: JSON.parse(fields)
}).render();
});
});

<script src="http://cdn.alloyui.com/3.0.1/aui/aui-min.js"></script>
<link href="http://cdn.alloyui.com/3.0.1/aui-css/css/bootstrap.min.css" rel="stylesheet"></link>
<div class="yui3-skin-sam">
<button id="resetFormBuilder" class="btn btn-primary">
Reset <code>FormBuilder</code>
</button>
<div id="wrapper">
<div id="myFormBuilder"></div>
</div>
</div>
&#13;