0

I need to fill form fields with post_meta from an ajax response.

Everything works properly.

I could hard-code the swapping of each piece of data.meta into its form field. But that approach is not reusable.

Is there a way to loop through the data.meta instead?

In some cases, there may not be meta for all the form fields. And in some cases, there may be meta that is not applicable to the form.

This is for a form in a bootstrap modal window.

$.ajax({

    ...

    success: function (data) {

        if (data.status === 'success') {

            $('#title').val(data.title);

            $.each(data.meta, function(key,value) {

                  alert(key + '---' + value[0]); 

                  // if key is a form element, add the value to that element

                  // if key is a form element that is a select dropdown, 
                  //  then mark that option as selected

            });

        }
    }
});

2 Answers 2

1

First, I can count on one finger the number of times A code which was developed in the hope of being "reusable" was actually reused. Write the code to the specification you can test against. "Reusable" is not a specification you can test against until you have a proper idea what will you need in the future, will is always hard for people that are not future tellers ;)

Second, this means that all meta data should be queriable from the outside which is a security/privacy nightmare as you will have an end point that can be used to query intimate data that might never be displayed in the open. This is BTW the reason that you need to explicitly opt-in meta fields in order to be able to use them in the REST API.

0

This works for me and is reusable. It assumes your form field ids match your post_meta keys.

if (data.status === 'success') {

    // populate form with post_meta
    $.each(data.meta, function(key,value) {

        //alert(key + '---' + value[0]);

        var $form_element = $("#" + key);

        if ( $form_element.length > 0 ) {

            // check if $form_element is a selector
            if( $form_element.prop('type') == 'select-one' ) 
                modal.find($form_element).val(value).change();
            else
                modal.find("#" + key).val(value);
                //modal.find($form_element).val(value);


        }

    });

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.