简体   繁体   中英

jQuery - How to populate (data inject) a NESTED SheepIt form

I have a SheepIt form of Vehicles, each of which may have any number (0 - infinite) of Stops. A vehicle has a type, notes and (any number of) stops. A stop has a date, time and location.

This is my SheepIt code:

var sheepit_vehicles = jQuery("#vehicle_types").sheepIt({
            separator: '',
            allowRemoveLast: true,
            allowRemoveCurrent: true,
            allowAdd: true,

            // Limits
            minFormsCount: 1,
            iniFormsCount: 1,
            nestedForms: [
                {
                    id: 'vehicle_types_#index#_stops',
                    options: {
                        separator: "",
                        indexFormat: '#index_stops#',
                        minFormsCount: 2,
                        iniFormsCount: 2,
                        afterAdd: function(source, newForm) {
                            addStop(source, newForm);
                            jQuery(".timepicker").timepicker({interval: 15, timeFormat: 'h:mm p'});
                        }
                    }
                }
            ]
            ,
        data: [{
                'lead_vehicle_id': '34',
                'vehicle_type': '1028',
                'vehicle_note': '',
                'vehicle_stop_dates[#index#][#index_stops#]': ['2018-08-26', '2018-08-26', '2018-08-26']
            }, {
                'lead_vehicle_id': '35',
                'vehicle_type': '1027',
                'vehicle_note': 'ABC',
                'vehicle_stop_dates[#index#][#index_stops#]': ['2018-08-27', '2018-08-27']
            }
        ]
        });

The crux here is that data element at the end. I simply cannot figure out how to format the JSON data element to populate properly.

The file I am using for my jQuery plugin has been modified based upon my previous StackOverflow questions but cna be found here: https://yt074.addons.la/js/jquery.sheepItPlugin-modified.js

The injection (data population) code is the fillForm function, on line 977 of that function. I have included the function itself below:

    function fillForm(form, data)
    {
        var x = 0;

        // For each element, try to get the correct field or fields
        $.each(data, function(index, value) {

            var formId = source.attr('id');
            var formIndex = form.data('formIndex');



            // Replace form Id and form Index with current values
            if (index.indexOf('#form#') != -1 || index.indexOf('#index#') != -1) {
                index = index.replace('#form#', formId);
                index = index.replace('#index#', formIndex);
            } else {
                index = formId + '_' + formIndex + '_' + index;
            }



            /**
             * Search for field (by id, by name, etc)
             */

            // Search by id
            var field = form.find(':input[id="' + index + '"]');

            // Search by name
            if (field.length == 0) {

                // Search by name
                field = form.find(':input[name="' + index + '"]');

                if (field.length == 0) {
                    // Search by name array format
                    field = form.find(':input[name="' + index + '[]"]');
                }

                // Search by name without the form data (Michael Yingling hack for broken radio buttons)
                if(field.length == 0) {
                    var name = index.replace(formId, '').replace('_'+formIndex+'_', '');
                    field = form.find(':input[name="' + name + 's[' + formIndex + ']"]');
                }
            }

            if (field.length == 0) {
                field = form.find('select[id="' + index + '"]');
                if (field.length == 0) {
                    var last_underscore = index.lastIndexOf("_")+1;
                    var token = index.substring(last_underscore, index.indexOf("-", last_underscore));
                    field = form.find('select[id="' + index.replace(token+'-value-trigger', 'trigger-trigger-'+token) + '"]');
                }
            }


            // Field was found
            if (field.length > 0) {

                // Multiple values?
                var mv = false;
                if (typeof(value) == 'object') {
                    mv = true;
                }

                // Multiple fields?
                var mf = false;
                if (field.length > 1) {
                    mf = true;
                }

                if (mf) {

                    if (mv) {

                        var fieldsToFill = [];
                        fieldsToFill['fields'] = [];
                        fieldsToFill['values'] = [];

                        x = 0;
                        for (x in value) {
                             fieldsToFill['fields'].push(field.filter('[value="'+ value[x] +'"]'));
                             fieldsToFill['values'].push(value[x]);
                        }
                        x = 0;
                        for (x in fieldsToFill['fields']) {
                            fillFormField(fieldsToFill['fields'][x] , fieldsToFill['values'][x]);
                        }
                    } else {
                        fillFormField( field.filter('[value="'+ value +'"]', value) );
                    }
                } else {
                    if (mv) {
                        x = 0;
                        for (x in value) {
                            fillFormField(field, value[x]);
                        }
                    } else {
                       fillFormField(field, value);
                    }
                }
            }
            // Field not found in this form try search inside nested forms
            else {
                if ( typeof(form.data('nestedForms')) != 'undefined') {
                    if (form.data('nestedForms').length > 0) {
                        x = 0;
                        for (x in form.data('nestedForms')) {

                            if (index == form.data('nestedForms')[x].attr('id') && typeof(value) == 'object') {
                                form.data('nestedForms')[x].inject(value);
                            }
                        }

                    }
                }
            }

        });


    }

Here is a Fiddle which shows my issue of the Stop dates not populating: https://jsfiddle.net/z31fr2xk/5/

You have these "forms":

  • Parent form — ID: vehicle_types ; Level: 1

  • Child form — ID: vehicle_types_#index#_stops ; Level: 2 (nested in the Level 1's form)

In each form, the SheepIt plugin expects each form field (eg an <input> ) to have its id in this format: {FORM ID}_{INDEX FORMAT}_{DATA KEY} ; eg vehicle_types_#index#_notes for the "Notes" field, where {FORM ID} is vehicle_types , {INDEX FORMAT} is #index# , and {DATA KEY} is notes .

And the plugin will read the {DATA KEY} value, if any, from the data array .

So the data format is:

[{ // Item 1
  '{DATA KEY}': 'value',
  '{DATA KEY}': 'value',
  ...
},
{ // Item 2
  '{DATA KEY}': 'value',
  '{DATA KEY}': 'value',
  ...
},
...]

For every child/nested form, just add a nested array /data as shown below:

[{ // Item 1
  '{DATA KEY}': 'value',
  '{DATA KEY}': 'value',
  ...
  '{CHILD FORM ID}': [{
    '{DATA KEY}': 'value',
    '{DATA KEY}': 'value',
    ...
  },
  ...]
},
...]

The {CHILD FORM ID} is mandatory, and in your case, it is vehicle_types_#index#_stops .

So, for example, the id of the stop date field is vehicle_types_#index#_stops_#index_stops#_stop_date , which means the {DATA KEY} is stop_date .

And with the sample fields (the "Notes" and "Stop Date" fields), your data array would look like this:

[{
  'notes': 'Notes 1',
  'vehicle_types_#index#_stops': [{
    'stop_date': '2018-09-24'
  }, {
    'stop_date': '2018-09-25'
  }]
}, {
  'notes': 'Notes 2',
  'vehicle_types_#index#_stops': [{
    'stop_date': '2018-09-23'
  }]
}]

See the full data and a demo here .

Additional Notes

  • In the demo, I linked only to the modified SheepIt plugin — you linked to both the modified and original versions of the plugin. But note that I did not actually make any modifications to the SheepIt plugin.

  • I corrected the for and id of the "Vehicle Type" field — you used vehicles_#index#_type and I changed it to vehicle_types_#index#_type . Same thing with the "Stop Type" field (in the child/nested form) — you used vehicle_stop_types_#index#_#index_stops# and I changed it to vehicle_types_#index#_stops_#index_stops#_stop_type . There might be other fixes necessary (the hidden fields' id , maybe?), but you would need to do the fixes on your own.. =)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM