DrupalGap icon indicating copy to clipboard operation
DrupalGap copied to clipboard

Custom Node Creation Forms with Fields

Open mkinnan opened this issue 8 years ago • 1 comments

Is the approach I have taken below the correct method to handle form fields for node creation? Or am I missing something?

In attempting to create my own custom node add pages, I have reviewed the example: http://docs.drupalgap.org/7/Entities/Editing_Entities

The example works great for creating/editing a node with only a title. When adding in additional fields such as body, one might think to do the following:

function my_module_form(form, form_state, node) {
  try {

    form.elements['title'] = {
      type: 'textfield',
      title: t('Title'),
      required: true,
      default_value: node.title
    };
    
    form.elements['body'] = {
      type: 'textarea',
      title: t('Description'),
      required: true,
      default_value: node.body
    };

    form.elements['submit'] = {
      type: 'submit',
      value: t('Save')
    };
    
    return form;
  
  }
  catch (error) { console.log('my_module_form - ' + error); }
}

The issue with that for the body form element is that when hook_form_submit is called, Drupal is expecting the format of form.values to be:

{
   "title":"A Test",
   "body":{
      "und":[
         {
            "value":"a bunch of text"
         }
      ]
   }
}

but what is returned from my custom form is:

{
   "title":"A Test",
   "body":{
      "und":{
         "0":"a bunch of text"
      }
   }
}

which causes the node creation to fail. So, instead I create a different identity for my body:

form.elements['my_custom_body'] = {
  type: 'textarea',
  title: t('Description'),
  required: true,
  default_value: node.body
};

and rebuild the form.values object before passing to node_save:

function my_module_form_submit(form, form_state) {
  try {
    
    var data_to_save = {
      language: form_state.values.language,
      type: form_state.values.type,
      title: form_state.values.title,
      body: { und: [ { value: form_state.values.my_module_body } ] }
    };
  
    node_save(data_to_save, {
      success: function(result) {
        drupalgap_goto('node/' + result.nid, { reloadPage: true });
      }
    });
  
  }
  catch (error) { console.log('my_module_form_submit - ' + error); }
}

mkinnan avatar Jun 28 '17 01:06 mkinnan

@mkinnan I often use the same technique that you use with the data_to_save example. Essentially build a simple form, with simple inputs, then in the submit handler build the complex JSON that Drupal is expecting.

signalpoint avatar Jun 29 '17 00:06 signalpoint