Monday, 9 October 2023

Monday, 25 September 2023

PCF Control development




1. Install the Node.js
2. Open the Power shell and run node -v
3. Download and Install the Visual Studio Code
4. Install the Power Apps CLI
5. Validate the PowerApps CLI    pac install latest 
6. Create a PCF Project 
    . Create your own folder in your local machine
    . Open a cmd prompt and change the location to above created.
    . Execute the following command syntax is    
          pac pcf init --namespace CRMONCE --name CRMPCFProject --template field

7. run the command     npm install
8. Open the folder in VSCode.
9. run npm run build 
10 run    "npm start"/ "npm start watch"
For continues solution build 


Use below url if you get ssl error
http://127.0.0.1:8181/

To generate package use below command

pac solution init --publisher-name developer --publisher-prefix dev
go to directory
C:\Users\user\Downloads\PCFPackage
pac solution add-reference --path "C:\Users\user\Documents\ProjectPCFControl"
open VS Developer command and run below command
first time below command
msbuild /t:build /restore
next time for production use below command else
msbuild /p:configuration=Release
msbuild

PCF Control Schema

 Control TAG 


Attributes of control tags  

namespace: Provided in the “pac” command earlier. 

constructor: Provided in the “pac” command earlier. 

version: change the versioning if needed; else, we can keep it to default. 

display-name-key: This will be the display name with no spaces for custom control. 

description-key: This description will be shown in D365 for custom control. 

control-type: We will keep the default value 


Property TAG

Attributes of property tags 

name: Provide the name that will be used for custom control. 

display-name-key: Provide the display name with no spaces for custom control. 

description-key: This description will be shown in D365 for custom control. 

of-type: If we are using a single datatype, then there are some supported datatype that can be used for the of-type attribute. 

Valid values are: 


TwoOptions 

Whole.None 

Currency 

DateAndTime.DateAndTime 

DateAndTime.DateOnly 

SingleLine.Email 

SingleLine.Phone 

SingleLine.Text 

SingleLine.TextArea 

SingleLine.Ticker 

SingleLine.URL 

Decimal 

Enum 

FP 

Multiple 

Optionset 

of-type-group: if we are building control that will support multiple data-type, then we need to use the of-type-group attribute.  

Let us define a type-group: 


<type-group name=”line”> 

<type>SingleLine.Email</type> 

<type>SingleLine.Phone</type> 

<type>SingleLine.Text</type> 

<type>SingleLine.URL</type> 

</type-group> 



DataSet TAG

 Attributes of data-set tags 

name: Provide the name of the data setused to get the value in a custom control. 

display-name-key: Provide the display name with no spaces that will be set while importing in App. 

description-key: This description will be shown in D365 for custom control. 


Resources TAG 


Subtags of Resources tags 

code: Provide the relative path for typescript file which contains code for custom control 

css – Provide the CSS files that need to be added. 

resx – Provide the file path that contains static string contents that are needed for the control. 

img – Provide the images that are needed in the project. 

Thursday, 21 September 2023

How to get other controls value in PCF Control

 

 // @ts-ignore
           let XRM:any=window['Xrm'];
           let lastName=XRM.Page.data._formContext.getControl("cr6a2_lastname").getValue();

Wednesday, 20 September 2023

error 'context' is defined but never used no-unused-vars

 

When we run npm run build or npm start command and getting below error  

[4:53:53 PM] [start]  Initializing...

[4:53:53 PM] [start]  Validating manifest...

[4:53:53 PM] [start]  Validating control...

[4:53:55 PM] [start]  Generating manifest types...

[4:53:55 PM] [start]  Generating design types...

[4:53:55 PM] [start]  Running ESLint...

[4:53:59 PM] [start]  Failed:

[pcf-1065] [Error] ESLint validation error:

 43:23  error  'context' is defined but never used  no-unused-vars


Solution: Then ".eslintrc.json" file and add the below configuration under rules.


 "rules": {
      "no-unused-vars": ["warn"],
      "no-undef": ["warn"]
    }

React version not specified in eslint-plugin-react settings. See https://github.com/jsx-eslint/eslint-plugin-react#configuration

When we  build the PCF project and  receive below warning  

Error:

Warning: React version not specified in eslint-plugin-react settings. See https://github.com/jsx-eslint/eslint-plugin-react#configuration .

[4:47:40 PM] [start]  Compiling and bundling control...



Solution : Open the ".eslintrc.json" and add below configuration 


"settings": {

      "react": {

        "version": "detect"

      }

    }



The OutputPath property is not set for project PCFPackage.cdsproj

 When we run the below command in VS Developer command 


"msbuild /t:build /restore" or "msbuild /p:configuration=Release"

and get the below error

C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\bin\Microsoft.Common.CurrentVersion.targets(780,5): error : The OutputPath property is not set for project 'PCFPackage.cdsproj'.  Please check to make sure that you have specified a valid combination of Configuration and Platform for this project.  Configuration='Debug'  Platform='AnyCPU'.  You may be seeing this message because you are trying to build a project without a solution file, and have specified a non-default Configuration or Platform that doesn't exist for this project. [C:\Users\user\Downloads\PCFPackage\PCFPackage.cdsproj]


Solution: Add below configuration in .cdsproj file 


<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">

    <DebugSymbols>true</DebugSymbols>

    <DebugType>full</DebugType>

    <Optimize>false</Optimize>

    <OutputPath>bin\Debug\</OutputPath>

    <DefineConstants>DEBUG;TRACE</DefineConstants>

    <ErrorReport>prompt</ErrorReport>

    <WarningLevel>4</WarningLevel>

  </PropertyGroup>

  <PropertyGroup Condition=" '$(Configuration)' == 'Release' ">

    <DebugType>pdbonly</DebugType>

    <Optimize>true</Optimize>

    <OutputPath>bin\Release\</OutputPath>

    <DefineConstants>TRACE</DefineConstants>

    <ErrorReport>prompt</ErrorReport>

    <WarningLevel>4</WarningLevel>

  </PropertyGroup>



Monday, 14 August 2023

Transaction in Dataverse using console application

 public static void DataverseConnector()

        {

            try

            {

                string conn = @"AuthType=OAuth;Username=abcd@org.onmicrosoft.com;Password=password;Url=https://dorg.crm.dynamics.com;TokenCacheStorePath=c:\temp\MyTokenCache2;LoginPrompt=Auto";

                using (ServiceClient serviceClient = new ServiceClient(conn))

                {

                    if (serviceClient.IsReady)

                    {

                        // Create an ExecuteTransactionRequest object.

                        var requestToCreateRecords = new ExecuteTransactionRequest()

                        {

                            // Create an empty organization request collection.

                            Requests = new OrganizationRequestCollection(),

                            ReturnResponses = true

                        };


                        // Create several (local, in memory) entities in a collection. 

                        var listData = new List<string>();

                        listData.Add("Account 1");

                        listData.Add("Account 2");

                        listData.Add("Account 3");

                        listData.Add("Account 4");

                        listData.Add("43b1e6dc-8e3a-ee11-bdf4-000d3a0aab51");

                        // Add a CreateRequest for each entity to the request collection.

                        foreach (var list in listData)

                        {

                            OrganizationRequest organizationRequest = new OrganizationRequest();

                            Entity accEntity;

                            accEntity = new Entity("account");

                            accEntity["name"] = list;

                            if (list == "43b1e6dc-8e3a-ee11-bdf4-000d3a0aab51")

                            {

                                organizationRequest.RequestName = "Update";

                                accEntity["name"] = "Update record";

                                accEntity.Id = new Guid("43b1e6dc-8e3a-ee11-bdf4-000d3a0aab51");

                            }

                            else

                            {

                                organizationRequest.RequestName = "Create";

                            }

                            organizationRequest.Parameters.Add("Target", accEntity);

                            requestToCreateRecords.Requests.Add(organizationRequest);

                        }

                        // Execute all the requests in the request collection using a single web method call.

                        try

                        {

                            var responseForCreateRecords =(ExecuteTransactionResponse)serviceClient.Execute(requestToCreateRecords);

                            // Display the results returned in the responses.

                            foreach (var responseItem in responseForCreateRecords.Responses)

                            {

                                if (responseItem != null)

                                {

                                    if (responseItem.ResponseName == "Create")

                                    {

                                        Console.WriteLine(responseItem.ResponseName + " with account id as " + responseItem.Results["id"].ToString());

                                    }

                                    else if (responseItem.ResponseName == "Update")

                                    {

                                        Console.WriteLine(responseItem.ResponseName);

                                    }

                                }

                            }

                        }

                        catch (FaultException<OrganizationServiceFault> ex)

                        {

                            Console.WriteLine("Create request failed for the account{0} and the reason being: {1}",

                                ((ExecuteTransactionFault)(ex.Detail)).FaultedRequestIndex + 1, ex.Detail.Message);

                            throw;

                        }

                    }

                    else

                    {

                        Console.WriteLine("A web service connection was not established.");

                    }

                }

                // Pause the console so it does not close.

                Console.WriteLine("Press any key to exit.");

                Console.ReadLine();

            }

            catch (Exception ex)

            {

                Console.Write(ex.Message);

            }

            

        }

Friday, 11 August 2023

Disassociate a record in dataverse using console application

  public static void DataverseConnector()

        {

            try

            {

               string conn = @"AuthType=OAuth;Username=user@org.onmicrosoft.com;Password=password;Url=https://orgapp.crm.dynamics.com;TokenCacheStorePath=c:\MyTokenCache2;LoginPrompt=Auto";

                using (ServiceClient serviceClient = new ServiceClient(conn))

                {

                    if (serviceClient.IsReady)

                    {

                        // Retrieve the accounts

                        var query = new QueryByAttribute("account")

                        {

                            ColumnSet = new ColumnSet("name")

                        };

                        query.AddAttributeValue("address1_city", "Redmond");

                        EntityCollection accounts = serviceClient.RetrieveMultiple(query);

                        //Convert the EntityCollection to a EntityReferenceCollection

                        var accountReferences = new EntityReferenceCollection();


                        accounts.Entities.ToList().ForEach(x => {

                            accountReferences.Add(x.ToEntityReference());

                        });


                        // The contact to associate to the accounts

                        var contacttoAssociateWithAccount = new EntityReference("contact",new Guid("edb87117-ce7e-ed11-81ab-000d3ac9cc70"));


                        // The relationship to use

                        var relationship = new Relationship("account_primary_contact");


                        // Use the Associate method

                        serviceClient.Disassociate(contacttoAssociateWithAccount.LogicalName, contacttoAssociateWithAccount.Id, relationship, accountReferences);

                    }

                    else

                    {

                        Console.WriteLine("A web service connection was not established.");

                    }

                }

                // Pause the console so it does not close.

                Console.WriteLine("Press any key to exit.");

                Console.ReadLine();

            }

            catch (Exception ex)

            {

                Console.Write(ex.Message);

            }

            

        }

Associate a record in dataverse using console application

  public static void DataverseConnector()

        {

            try

            {

                string conn = @"AuthType=OAuth;Username=user@org.onmicrosoft.com;Password=password;Url=https://orgapp.crm.dynamics.com;TokenCacheStorePath=c:\MyTokenCache2;LoginPrompt=Auto";

                using (ServiceClient serviceClient = new ServiceClient(conn))

                {

                    if (serviceClient.IsReady)

                    {

                        // Retrieve the accounts

                        var query = new QueryByAttribute("account")

                        {

                            ColumnSet = new ColumnSet("name")

                        };

                        query.AddAttributeValue("address1_city", "Redmond");

                        EntityCollection accounts = serviceClient.RetrieveMultiple(query);

                        //Convert the EntityCollection to a EntityReferenceCollection

                        var accountReferences = new EntityReferenceCollection();


                        accounts.Entities.ToList().ForEach(x => {

                            accountReferences.Add(x.ToEntityReference());

                        });


                        // The contact to associate to the accounts

                        var contacttoAssociateWithAccount = new EntityReference("contact",new Guid("edb87117-ce7e-ed11-81ab-000d3ac9cc70"));


                        // The relationship to use

                        var relationship = new Relationship("account_primary_contact");


                        // Use the Associate method

                        serviceClient.Associate(contacttoAssociateWithAccount.LogicalName, contacttoAssociateWithAccount.Id, relationship, accountReferences);

                    }

                    else

                    {

                        Console.WriteLine("A web service connection was not established.");

                    }

                }

                // Pause the console so it does not close.

                Console.WriteLine("Press any key to exit.");

                Console.ReadLine();

            }

            catch (Exception ex)

            {

                Console.Write(ex.Message);

            }

            

        }

Retrieve data from dataverse in paging using console application

  public static void DataverseConnector()

        {

            try

            {

               string conn = @"AuthType=OAuth;Username=user@org.onmicrosoft.com;Password=password;Url=https://orgapp.crm.dynamics.com;TokenCacheStorePath=c:\MyTokenCache2;LoginPrompt=Auto";

                using (ServiceClient serviceClient = new ServiceClient(conn))

                {

                    if (serviceClient.IsReady)

                    {

                        RetriveRecords(serviceClient);

                    }

                    else

                    {

                        Console.WriteLine("A web service connection was not established.");

                    }

                }

                // Pause the console so it does not close.

                Console.WriteLine("Press any key to exit.");

                Console.ReadLine();

            }

            catch (Exception ex)

            {

                Console.Write(ex.Message);

            }

            

        }

        private static void RetriveRecords(ServiceClient serviceClient)

        {

            int queryCount = 3;

            int pageNumber = 1;

            int recordCount = 0;

            QueryExpression pagequery = convertFecthXMLToQueryExpression(serviceClient);

            pagequery.PageInfo = new PagingInfo();

            pagequery.PageInfo.Count = queryCount;

            pagequery.PageInfo.PageNumber = pageNumber;

            // The current paging cookie. When retrieving the first page, 

            // pagingCookie should be null.

             pagequery.PageInfo.PagingCookie = null;

            Console.WriteLine("Retrieving account records in pages...\n");

            while (true)

            {

                // Retrieve the page.

                EntityCollection results = serviceClient.RetrieveMultiple(pagequery);

                if (results.Entities != null)

                {

                    // Retrieve all records from the result set.

                    foreach (var acct in results.Entities)

                    {

                        Console.WriteLine("{0}.\t{1}", ++recordCount, acct["name"]);

                    }

                }

                // Check for more records, if it returns true.

                if (results.MoreRecords)

                {

                    Console.WriteLine("\n****************\nPage number {0}\n****************", pagequery.PageInfo.PageNumber);

                    // Increment the page number to retrieve the next page.

                    pagequery.PageInfo.PageNumber++;

                    // Set the paging cookie to the paging cookie returned from current results.

                    pagequery.PageInfo.PagingCookie = results.PagingCookie;

                }

                else

                {

                    // If no more records are in the result nodes, exit the loop.

                    break;

                }

            }

        }

        private static QueryExpression convertFecthXMLToQueryExpression(ServiceClient serviceClient)

        {

            var query = @"<fetch mapping='logical'><entity name='account'><attribute name='accountid'/><attribute name='name'/><attribute name='numberofemployees'/></entity></fetch>";

            FetchXmlToQueryExpressionRequest fetchToQueryExpRequest = new FetchXmlToQueryExpressionRequest();

            fetchToQueryExpRequest.FetchXml = query;

            FetchXmlToQueryExpressionResponse fetchXmlToQueryExpressionResponse = (FetchXmlToQueryExpressionResponse)serviceClient.Execute(fetchToQueryExpRequest);

            QueryExpression myquery = fetchXmlToQueryExpressionResponse.Query;

            return myquery;

        }


other way to fetch item using FetchXML in paging


https://learn.microsoft.com/en-us/power-apps/developer/data-platform/org-service/page-large-result-sets-with-fetchxml



Thursday, 10 August 2023

Delete a record from Dataverse table using console application

 public static void DataverseConnector()

        {

            try

            {

                string conn = @"AuthType=OAuth;Username=user@org.onmicrosoft.com;Password=password;Url=https://orgapp.crm.dynamics.com;TokenCacheStorePath=c:\MyTokenCache2;LoginPrompt=Auto";

                using (ServiceClient serviceClient = new ServiceClient(conn))

                {

                    if (serviceClient.IsReady)

                    {

                       serviceClient.Delete("account", new Guid("a17f700a-6d37-ee11-bdf4-000d3a0aab51"));                       

                    }

                    else

                    {

                        Console.WriteLine("A web service connection was not established.");

                    }

                }

                // Pause the console so it does not close.

                Console.WriteLine("Press any key to exit.");

                Console.ReadLine();

            }

            catch (Exception ex)

            {

                Console.Write(ex.Message);

            }

            

        }

RetrieveMultiple records from dataverse using console application

 public static void DataverseConnector()

        {

            try

            {

               string conn = @"AuthType=OAuth;Username=user@org.onmicrosoft.com;Password=password;Url=https://orgapp.crm.dynamics.com;TokenCacheStorePath=c:\MyTokenCache2;LoginPrompt=Auto";

                using (ServiceClient serviceClient = new ServiceClient(conn))

                {

                    if (serviceClient.IsReady)

                    {

                      var  query = @"<fetch mapping='logical'><entity name='account'><attribute name='accountid'/><attribute name='name'/><attribute name='numberofemployees'/></entity></fetch>";

                       var recordColl= serviceClient.RetrieveMultiple(new FetchExpression(query));

                        foreach (var accountrecord in recordColl.Entities)

                        {

                              Console.WriteLine(accountrecord.Id);

                              Console.WriteLine(accountrecord["name"]);

                              Console.WriteLine(accountrecord["numberofemployees"]);

                        }

                    }

                    else

                    {

                        Console.WriteLine("A web service connection was not established.");

                    }

                }

                // Pause the console so it does not close.

                Console.WriteLine("Press any key to exit.");

                Console.ReadLine();

            }

            catch (Exception ex)

            {

                Console.Write(ex.Message);

            }

            

        }

retrieve a record from dataverse table using console application

  public static void DataverseConnector()

        {

            try

            {

               string conn = @"AuthType=OAuth;Username=user@org.onmicrosoft.com;Password=password;Url=https://orgapp.crm.dynamics.com;TokenCacheStorePath=c:\MyTokenCache2;LoginPrompt=Auto";

                using (ServiceClient serviceClient = new ServiceClient(conn))

                {

                    if (serviceClient.IsReady)

                    {

                      var columnSet = new ColumnSet("name","numberofemployees");

                      var accountrecord= serviceClient.Retrieve("account", new Guid("a17f700a-6d37-ee11-bdf4-000d3a0aab51"),columnSet);

                        Console.WriteLine(accountrecord.Id);

                        Console.WriteLine(accountrecord["name"]);

                        Console.WriteLine(accountrecord["numberofemployees"]);

                    }

                    else

                    {

                        Console.WriteLine("A web service connection was not established.");

                    }

                }


                // Pause the console so it does not close.

                Console.WriteLine("Press any key to exit.");

                Console.ReadLine();

            }

            catch (Exception ex)

            {

                Console.Write(ex.Message);

            }

            

        }

update a record in dataverse using console application

  public static void DataverseConnector()

        {

            try

            {

                string conn = @"AuthType=OAuth;Username=user@org.onmicrosoft.com;Password=password;Url=https://orgapp.crm.dynamics.com;TokenCacheStorePath=c:\MyTokenCache2;LoginPrompt=Auto";

                using (ServiceClient serviceClient = new ServiceClient(conn))

                {

                    if (serviceClient.IsReady)

                    {

                        //Use Entity class with entity logical name

                        var account = new Entity("account");

                        account.Id = new Guid("a17f700a-6d37-ee11-bdf4-000d3a0aab51");

                        // set attribute values

                        // string primary name

                        account["name"] = "Contoso2";

                        // Boolean (Two option)

                        account["creditonhold"] = false;

                        // DateTime

                        account["lastonholdtime"] = new DateTime(2017, 1, 1);

                        // Double

                        account["address1_latitude"] = 47.642311;

                        account["address1_longitude"] = -122.136841;

                        // Int

                        account["numberofemployees"] = 500;

                        // Money

                        account["revenue"] = new Money(new decimal(5000000.00));

                        // Picklist (Option set)

                        account["accountcategorycode"] = new OptionSetValue(1); //Preferred customer

                        //Create the account

                       serviceClient.Update(account);

                      //  Console.WriteLine("Record ID is {0}.", accountid);

                    }

                    else

                    {

                        Console.WriteLine("A web service connection was not established.");

                    }

                }


                // Pause the console so it does not close.

                Console.WriteLine("Press any key to exit.");

                Console.ReadLine();

            }

            catch (Exception ex)

            {

                Console.Write(ex.Message);

            }

            

        }

Create a record in Dataverse in Console Apllication c#

  public static void DataverseConnector()

        {

            try

            {

               string conn = @"AuthType=OAuth;Username=user@org.onmicrosoft.com;Password=password;Url=https://orgapp.crm.dynamics.com;TokenCacheStorePath=c:\MyTokenCache2;LoginPrompt=Auto";

                using (ServiceClient serviceClient = new ServiceClient(conn))

                {

                    if (serviceClient.IsReady)

                    {

                        //Use Entity class with entity logical name

                        var account = new Entity("account");

                        // set attribute values

                        // string primary name

                        account["name"] = "Contoso";

                        // Boolean (Two option)

                        account["creditonhold"] = false;

                        // DateTime

                        account["lastonholdtime"] = new DateTime(2017, 1, 1);

                        // Double

                        account["address1_latitude"] = 47.642311;

                        account["address1_longitude"] = -122.136841;

                        // Int

                        account["numberofemployees"] = 500;

                        // Money

                        account["revenue"] = new Money(new decimal(5000000.00));

                        // Picklist (Option set)

                        account["accountcategorycode"] = new OptionSetValue(1); //Preferred customer

                        //Create the account

                        Guid accountid= serviceClient.Create(account);

                        Console.WriteLine("Record ID is {0}.", accountid);

                    }

                    else

                    {

                        Console.WriteLine("A web service connection was not established.");

                    }

                }


                // Pause the console so it does not close.

                Console.WriteLine("Press any key to exit.");

                Console.ReadLine();

            }

            catch (Exception ex)

            {

                Console.Write(ex.Message);

            }

            finally

            {

                Console.Write("test");

            }

        }

Connect dataverse in Console Application c#

  Install "Microsoft.PowerPlatform.Dataverse.Client"


Using Microsoft.PowerPlatform.Dataverse.Client;

 public static void DataverseConnector()

        {

            try

            {

               string conn = @"AuthType=OAuth;Username=user@org.onmicrosoft.com;Password=password;Url=https://orgapp.crm.dynamics.com;TokenCacheStorePath=c:\MyTokenCache2;LoginPrompt=Auto";


                using (ServiceClient serviceClient = new ServiceClient(conn))

                {

                    if (serviceClient.IsReady)

                    {

                        WhoAmIResponse response =(WhoAmIResponse)serviceClient.Execute(new WhoAmIRequest());

                        Console.WriteLine("User ID is {0}.", response.UserId);

                    }

                    else

                    {

                        Console.WriteLine("A web service connection was not established.");

                    }

                }


                // Pause the console so it does not close.

                Console.WriteLine("Press any key to exit.");

                Console.ReadLine();

            }

            catch (Exception ex)

            {

                Console.Write(ex.Message);

            }

            finally

            {

                Console.Write("test");

            }

        }


Tuesday, 1 August 2023

Steps to create Patch and deployment on Higher environment

 Dev- Original Solution-Create Clone Patch.

-Include Component in Patch and update the solution.

-Export patch Solution.

QA-Import in QA.

DEV-Select Origional Solution.

-Click on Clone Solution it will merge the patch in original solution.

-Export the original Solution.

QA-Import the Solution in QA and it will merge the patch in Original solution.

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
        }
    );
}

Auto save form in model driven app

 Auto save form in model driven app on change event on controls

Call below method on any control's change event

function autoSavedData(formcontext)
{
    var frmcontext = formcontext.getFormContext();
    frmcontext.data.entity.save("no");
//below parameter can be passed in save mehtod as per requirement
//no
//saveandclose
// saveandnew
}

Friday, 3 February 2023

Bind Team Members in Lookup field in Model Driven app

 We have can bind for a specific team's members in Lookup field in Model driven app/dataverse using code


Upload the below code on Web Resources  and add on page load event and pass the formcontext parameter



function bindLookUpField(formcontext)

{

    var frmcontext= formcontext.getFormContext();

    var viewId = "GUID";

    var entityName = "systemuser";

    var viewDisplayName = "Team Members";

    frmcontext.getControl("InternaleLookupFieldName").addPreSearch(function () {

    var fechxml='<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="true">'+

    '<entity name="systemuser">'+

    '<attribute name="fullname" />'+

    '<attribute name="systemuserid" />'+

    '<order attribute="fullname" descending="false" />'+

    '<link-entity name="teammembership" from="systemuserid" to="systemuserid" visible="false" intersect="true">'+

    '<link-entity name="team" from="teamid" to="teamid" alias="ac">'+

    '<filter type="and">'+

    '<condition attribute="name" operator="eq" value="Team Name" />'+

    '</filter>'+

    '</link-entity>'+

    '</link-entity>'+

    '</entity>'+

    '</fetch>';

    var layoutXml = "<grid name='resultset' object='1' jump='systemuserid' select='1' icon='1' preview='1'>" +

                    "<row name='result' id='cr6a2_teamsmember'>" +

                    "<cell name='fullname' width='150' />" +

                    "</row>" +

                    "</grid>";

   frmcontext.getControl("InternaleLookupFieldName").addCustomView(viewId, entityName, viewDisplayName, fechxml, layoutXml, true);

    });

    

}