Friday, December 30, 2011

Simplify with an XML data model - Part 2

Part 2: Setting the form values from XML (Bi-directional binding).

Binding should work two ways, updating the model from the form fields and updating the form fields from the model. Let’s update the code so the form is populated with data when the page is loaded.
Interactive Example:


First lets add some initial data to the model:
     var xmlString = "<root><primary>yes</primary><sex>female</sex><address><street number=\"123\">Main Street</street><state>MA</state></address></root>";
Now lets make a function to set the model from the XML DOM:
    function setFormValue(element, xpath, xmlDom){
        //Get the node from the model
        var node = getNode(xpath, xmlDom);
        
        //Set the element's value
        if (element.type == 'text') {
            element.value = node.textContent;
        } else if (element.type == 'select-one') {
            for ( var i = 0; i < element.options.length; i++) {
                if (element.options[i].value == node.textContent) {
                    element.options[i].selected = true;
                    break;
                }
            }
        } else if (element.type == 'checkbox' || element.type == 'radio') {
            if(node.textContent == element.value){
                element.checked = true;
            }else{
                element.checked = false;
            }
        }
    }
Finally, we’ll add the call to set the form in the bind function:
    //Binds an element to the corresponding XPath expression
    function bind(element, xpath, xmlDom) {
        
        //Set the element's value from the node
        setFormValue(element, xpath, xmlDom);
        
        // Method to update and pretty print the model
        var setModelValue = function() {
            setXmlValue(element, xpath, xmlDom);
            document.getElementById("dataModelPrettyPrint").innerHTML = printXml(xmlDom.documentElement, 0);
        };

        // Add form event handlers to update the model
        element.onchange = setModelValue;
        if (element.type == 'text') {
            element.onkeyup = setModelValue;
        }

    }

That’s all! Now we have a basic bi-directional binding between the model and the form.


You can view this example here.
As always you can download all the source for these examples as a zip.
Remember you will need the Sarrissa library.

The next part will deal with dynamically creating the XML data model by ensuring the node paths exist. Simplify with an XML data model - Part 3

No comments:

Post a Comment