Search code examples
dynamics-crmpowerappspowerapps-modeldriven

Modify text in a Form in a model-driven app


We do have a choice array in a form in a model-driven app. At the choice creation window I can only enter plain text.

I now want to modify the text color based on the text, like if the text is 'Red' I want change the text color to red and/or a red circle image to make it more visible.

I have created a webresource jscript with which I can read the text at the onload event for the form

var formContext = test.getFormContext();
var text= formContext.getAttribute("il_statuscolor").getText();
console.log(text);

This works fine, but I can't find any function to set the text.

Any ideas?

Edit: Just to clarify, it works perfectly fine in a view (based on this tutorial: https://learn.microsoft.com/en-us/powerapps/maker/data-platform/display-custom-icons-instead) but I need it in a form.


Solution

  • Although Arun Vinoth answer pointed me in the right direction an im thankfully for that, here is a complete answer You need to call 'form_onload' as 'onload' for the form with execution context as the first parameter.

    function form_onload(executionContext) {
        var formContext = executionContext.getFormContext();
        var wrControl = formContext.getControl("WebResource_Ampelfarbe");
        if (wrControl) {
            wrControl.getContentWindow().then(
                function (contentWindow) {
                    contentWindow.showAmpelfarbe(Xrm, formContext);
                }
            )
        }
    }
    

    Where 'WebResource_Ampelfarbe' needs to be the name of your web resource and 'showAmpelfarbe' is the function in the html web resource you want to call.

    The following is the content of the html web resource for the tab 'source' which will create a colored box depending on the content.

    <html><head>
    <script>
    function showAmpelfarbe(xrm, formContext) {
        // Optionally set Xrm and formContext as global variables on the page.
        window.Xrm = xrm;
        window._formContext = formContext;
          
        // Add script logic here that uses xrm or the formContext.
        var ampel_value = formContext.getAttribute("il_statuscolor").getValue();
        ampel_color = '';
        if (ampel_value == 100000000) {
            ampel_color = "red";
        }else if (ampel_value == 100000001) {
            ampel_color = "yellow";
        }else if (ampel_value == 100000002) {
            ampel_color = "green";
        }
        document.body.style.backgroundColor = ampel_color;
    }
    
    </script>
    
    <meta></head><body onfocusout="parent.setEmailRange();" style="overflow-wrap: break-word;">