Autoform -- Edit Object as JSON (like MeteorToys)


#1

Is there a way to have an object appear in Autoform as a JSON text, where we can edit and then it gets converted back to Object before updating collection? We are using an admin panel (flow-db-admin) and want to edit User.profile, which may have different fields depending on the user.


#2

Here’s how I did it. My object name is “days”. My form is an update form with id “updateMarker”. My simple schema type for days is [Object]. There’s probably an easier/better way, but here goes:

  1. Make the field ready for text in the autoform:
    such as…

{{> afFieldInput name='days' type='textarea'}}

  1. Create these two hooks and attach them to autoform id at top level client js:

    var hooksObject = {
    before: {
    update: function(doc) {
    doc.$set.days = JSON.parse(doc.$set.days);
    return doc;
    }
    },
    docToForm: function(doc, ss) {
    doc.days = JSON.stringify(doc.days);
    return doc;
    }
    };
    AutoForm.hooks({
    ‘updateMarker’: hooksObject
    });

The docToForm-hook stringifies it on the way in. The before-hook changes it back to JSON on the way out.


#3

Thanks a lot @jaclynn for your response.

I tried docToForm (and even used the browser debugger) and it never got triggered. Did you do anything special?
Also, is there a reason why you didn’t you use formToDoc instead of ‘before’ hook?


[SOLVED] Trying to add Autoform Hooks into Yogiben:Admin
#4

Here is what we did, as we couldn’t use the before hook (not using method):

AutoForm.addHooks(['formId'], {
 formToDoc: function(doc) {
  doc.profile = JSON.parse(doc.profile);
  return doc;
 },
 docToForm: function(doc) {
  doc.profile = JSON.stringify(doc.profile, null, 2);
  return doc;
 },
 formToModifier: function(modifier) {
  modifier.$set.profile = JSON.parse(modifier.$set.profile);
  return modifier;
 }
});

Note sure if we need the formToDoc, but formToModifier is definitely needed.

Thanks @jaclynn!


#5

The formToDoc hook didn’t work for me. I replaced my before-block with formToModifier like you used, and it still works fine. I remember trying it earlier and thinking it didn’t work, but it does, so that’s probably the appropriate way given the documentation. Sorry for late reply. Wrote the post last night, then fell asleep. Glad it all works now.


#6

I need to do something similar. I tried

 formToModifier: function(modifier) {
  modifier.$set.name = 'someRandomName;
  return modifier;
 }

and it worked as it should. However, I’m having tourble editing fields that are within an object. HOw exaclty do I get that done?

Eg, my mongo record to be persisted is:

{
name: someRandomName,
address: {
       Street: X
       ...
       ...
      }
}

How exctly do I edit the street name? Also, is there a way to $unset an entire object that I do not wist to be persisted in the db?