How to set the value of Liferay 7.4 Forms fields from JavaScript on a page?

Jamie Sammons, modified 2 Years ago. New Member Post: 1 Join Date: 6/1/23 Recent Posts

What I want to know is how to set the value of Liferay Forms fields from JavaScript on a page.

In Liferay 7.1 this could be done simply, eg:

    var textfield2 = document.querySelector('[id*="$Text49276926$"]');
    textfield2.value = "Hello from JS control";

This still works initially in 7.4, but as soon as the user clicks anywhere on the page, the new value is overwritten by the old value.

I believe that it is ReactJS that is doing this.

What I want to know is whether you can see any problems with using the example JS below, that does work?

Or is there a "ReactJS" way of updating form fields, ie by doing an import of ReactJS libraries and using some functionality from them?

var mutationObserver = new MutationObserver(function(mutations) {
    console.log("HELLO ANDY");
    var textfield2 = document.querySelector('[id*="$Text49276926$"]');
    setNativeValue(textfield2, "DOES THIS WORK????");
});

mutationObserver.observe(document.body, {childList: true, subtree: true});

function setNativeValue(element, value) {
    let lastValue = element.value;
    element.value = value;
    let event = new Event("input", { target: element, bubbles: true });
    let tracker = element._valueTracker;
    if (tracker) {
        tracker.setValue(lastValue);
        console.log("in here");
    }
    element.dispatchEvent(event);
}

/* The above JS was taken from first answer on https://stackoverflow.com/questions/30683628/react-js-setting-value-of-input

This links to https://github.com/facebook/react/issues/11488 where the above technique is described as a hack.

This, https://dev.to/poeticgeek/in-react-component-controls-you-4ed8, explains how React uses a 'valueTracker' and gives the above technique as one solution.

This, https://www.pluralsight.com/guides/how-to-use-react-to-set-the-value-of-an-input, explains how to use React to set the value of an input, but it is for a React component that is created in a particluar way, whereas we are stuck with however LR Forms creates its React components.
*/