Prepopulating Form Data

⚠️ The annual cost of maintaining the server where this website is hosted, the domain, and keeping it up-to-date is approximately €3,000 per year. Help us with a small donation to cover these expenses. Support Now!

0 / 10000

You can prepopulate forms with information from system objects, custom objects, and form data.

To Get Data from System Objects

You can use the server module form.js copyObjectToForm method to get data from an existing form object. You can also use the metadata attributes for a system or custom object to prefill form data.

To Get Data from Other Forms

You can use the FormModel.js copyFrom function to get data from an existing form object. Usually, if you have used app.getForm to get a copy of a form model, it makes more sense to use the function. You can also transfer form data from one form to another directly. In the following example, if a customer decides to use the shipping address for billing, the values from one form are copied to the other.
server.get(
    'EditProfile',
    server.middleware.https,
    csrfProtection.generateToken,
    userLoggedIn.validateLoggedIn,
    function (req, res, next) {
        var accountModel = getModel(req);
        var profileForm = server.forms.getForm('profile'); //gets the profile.xml form definition and converts it to a JSON object.
        profileForm.clear();                               //clears the JSON object
        profileForm.customer.firstname.value = accountModel.profile.firstName;    //copies data from one field to another
        profileForm.customer.lastname.value = accountModel.profile.lastName;
        profileForm.customer.phone.value = accountModel.profile.phone;
        profileForm.customer.email.value = accountModel.profile.email;
        res.render('account/profile', {
            profileForm: profileForm,                                          //adds the JSON object to the data for the template
            breadcrumbs: [
                {
                    htmlValue: Resource.msg('global.home', 'common', null),
                    url: URLUtils.home().toString()
                },
                {
                    htmlValue: Resource.msg('page.title.myaccount', 'account', null),
                    url: URLUtils.url('Account-Show').toString()
                }
            ]
        });
        next();
    }
    );

To Copy Values from One Object to Another

To copy values from one custom object to another, don't use the dw.web.FormGroup copyFrom() and copyTo() methods. The copyTo() method requires a form submit to set values in the custom object. Instead, use Javascript to directly copy the values, as in this example:

let testObject = { name:"default name", subject:"default subject", message:"default message" };
let output = {};
Object.keys( testObject ).forEach( function( key ) {
   output[key] = testObject[key];
});