Monday, 6 February 2023

Set field required using code in model driven app

 Below is code which automate the column configuration based on settings

We have to create a table "validationtable" and some columns for settings of the columns

Entityname

ColumnName

IsRequired

IsHidden

IsDisabled


Then call below function on the form on which you want to use these settings applied

add some data in ValidationTable and execute open new form where the code is registered. 

function bindClientControl(formcontext) {
    var frmcontext = formcontext.getFormContext();
    var fetchXML='?fetchXml=<fetch version="1.0" mapping="logical" no-lock="false" count="100" distinct="true"><entity name="cr6a2_validationtable"><attribute name="cr6a2_validationtableid"/><attribute name="cr6a2_name"/><order attribute="cr6a2_name" descending="false"/><attribute name="cr6a2_columnname"/><attribute name="cr6a2_isdisabled"/><attribute name="cr6a2_ishidden"/><attribute name="cr6a2_isrequired"/><filter type="and"><condition attribute="cr6a2_name" operator="eq" value="'+frmcontext.data.entity._entityType+'"/></filter></entity></fetch>';
    Xrm.WebApi.retrieveMultipleRecords("cr6a2_validationtable", fetchXML).then(
        function success(result) {
            for (var i = 0; i < result.entities.length; i++) {
                if (frmcontext.getControl(result.entities[i].cr6a2_columnname) != null) {
                       frmcontext.getControl(result.entities[i].cr6a2_columnname).setDisabled(result.entities[i].cr6a2_isdisabled);
                       frmcontext.getControl(result.entities[i].cr6a2_columnname).setVisible(result.entities[i].cr6a2_ishidden);
                    if(result.entities[i].cr6a2_isrequired==true)
                    {
                       frmcontext.getAttribute(result.entities[i].cr6a2_columnname).setRequiredLevel("required");
                    }
                    else
                    {
                       frmcontext.getAttribute(result.entities[i].cr6a2_columnname).setRequiredLevel("none");
                    }
                }


                console.log(result.entities[i].cr6a2_columnname);
            }                    
            // perform additional operations on retrieved records
        },
        function (error) {
            console.log(error.message);
            // handle error conditions
        }
    );
}

No comments:

Post a Comment