src/Solutions/Customization/Forms/Add-XrmFormControl.ps1

<#
    .SYNOPSIS
    Add a PCF custom control to a form field.

    .DESCRIPTION
    Add a Power Apps Component Framework (PCF) custom control binding onto a field in a model-driven app form
    by modifying the FormXML of the systemform record.
    The FormXML is read with its unpublished changes, which are kept. The control is written the way the platform stores it:
    a controlDescription under the form, for the uniqueid of the field control, with the default control of the field and one customControl per form factor.
    The bound property and the parameter types are read from the manifest of the control (customcontrol table). A binding that already exists for the field is replaced.

    .PARAMETER XrmClient
    Xrm connector initialized to target instance. Use latest one by default. (Dataverse ServiceClient)

    .PARAMETER FormReference
    EntityReference of the systemform record to modify.

    .PARAMETER FieldName
    Logical name of the field on the form to bind the control to. The control of the form body is used when the field is also in the header.

    .PARAMETER ControlName
    Full unique name of the PCF control (e.g. "MscrmControls.FieldControls.ToggleControl").

    .PARAMETER Parameters
    Hashtable of control parameters with their static values, named as in the manifest of the control. Optional.
    Example: @{ "ShowAsSingleLine" = $true }

    .PARAMETER Publish
    Publish the table of the form after the update. (Default: true)

    .PARAMETER FormFactors
    Form factors the control is used on: 0 = Web, 1 = Phone, 2 = Tablet. (Default: 0, 1, 2)

    .OUTPUTS
    System.Void.

    .EXAMPLE
    $formRef = New-XrmEntityReference -LogicalName "systemform" -Id $formId;
    Add-XrmFormControl -FormReference $formRef -FieldName "industrycode" -ControlName "MscrmControls.FieldControls.OptionSet" -Parameters @{ "ShowAsSingleLine" = $true };

    .LINK
    https://github.com/AymericM78/PowerDataOps/blob/main/documentation/commands/Add-XrmFormControl.md
#>

function Add-XrmFormControl {
    [CmdletBinding(SupportsShouldProcess)]
    [OutputType([System.Void])]
    param
    (
        [Parameter(Mandatory = $false, ValueFromPipeline)]
        [Microsoft.PowerPlatform.Dataverse.Client.ServiceClient]
        $XrmClient = $Global:XrmClient,

        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [Microsoft.Xrm.Sdk.EntityReference]
        $FormReference,

        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [string]
        $FieldName,

        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [string]
        $ControlName,

        [Parameter(Mandatory = $false)]
        [Hashtable]
        $Parameters,

        [Parameter(Mandatory = $false)]
        [bool]
        $Publish = $true,

        [Parameter(Mandatory = $false)]
        [ValidateRange(0, 2)]
        [int[]]
        $FormFactors = @(0, 1, 2)
    )
    begin {
        $StopWatch = [System.Diagnostics.Stopwatch]::StartNew();
        Trace-XrmFunction -Name $MyInvocation.MyCommand.Name -Stage Start -Parameters ($MyInvocation.MyCommand.Parameters);
    }
    process {
        $form = Get-XrmFormXmlInternal -XrmClient $XrmClient -FormId $FormReference.Id -Unpublished;
        $formXml = $form.FormXml;

        # Control of the field: the form body first, the header otherwise
        $controlNode = $formXml.SelectSingleNode("/form/tabs//control[@datafieldname='$FieldName']");
        if (-not $controlNode) {
            $controlNode = $formXml.SelectSingleNode("//control[@datafieldname='$FieldName']");
        }
        if (-not $controlNode) {
            throw "Field '$FieldName' not found in the form XML.";
        }

        # Manifest of the PCF control: bound property and parameter types
        $customControlRecord = $XrmClient | Get-XrmRecord -LogicalName "customcontrol" -AttributeName "name" -Value $ControlName -Columns "manifest" -IfExists;
        if (-not $customControlRecord) {
            throw "PCF control '$ControlName' not found (customcontrol table).";
        }
        [xml]$manifest = [string]$customControlRecord.Record["manifest"];
        $properties = @($manifest.SelectNodes("//property"));
        $boundProperty = $properties | Where-Object { $_.GetAttribute("usage") -eq "bound" } | Select-Object -First 1;
        if (-not $boundProperty) {
            throw "PCF control '$ControlName' has no bound property: it cannot be bound to the field '$FieldName'.";
        }
        $staticParameters = @();
        if ($Parameters) {
            foreach ($key in $Parameters.Keys) {
                $property = $properties | Where-Object { $_.GetAttribute("name") -ieq $key } | Select-Object -First 1;
                if (-not $property) {
                    throw "Parameter '$key' is not a property of '$ControlName'. Properties: $(($properties | ForEach-Object { $_.GetAttribute('name') }) -join ', ').";
                }
                $value = $Parameters[$key];
                if ($value -is [bool]) {
                    $value = $value.ToString().ToLowerInvariant();
                }
                else {
                    $value = [System.Convert]::ToString($value, [System.Globalization.CultureInfo]::InvariantCulture);
                }
                $staticParameters += [PSCustomObject]@{ Name = $property.GetAttribute("name"); Type = $property.GetAttribute("of-type"); Value = $value };
            }
        }

        $uniqueId = $controlNode.GetAttribute("uniqueid");
        if (-not $uniqueId) {
            $uniqueId = "{$([Guid]::NewGuid())}";
            $controlNode.SetAttribute("uniqueid", $uniqueId);
        }

        # Existing binding of the field: replaced, its default control kept
        $defaultClassId = $controlNode.GetAttribute("classid");
        $descriptionsNode = $formXml.DocumentElement.SelectSingleNode("controlDescriptions");
        if ($descriptionsNode) {
            $existingDescriptions = @($descriptionsNode.SelectNodes("controlDescription")) | Where-Object { $_.GetAttribute("forControl") -ieq $uniqueId };
            foreach ($existingDescription in $existingDescriptions) {
                $existingDefault = $existingDescription.SelectSingleNode("customControl[@id]");
                if ($existingDefault) {
                    $defaultClassId = $existingDefault.GetAttribute("id");
                }
                $descriptionsNode.RemoveChild($existingDescription) | Out-Null;
            }
        }
        else {
            $descriptionsNode = $formXml.CreateElement("controlDescriptions");
            $formXml.DocumentElement.AppendChild($descriptionsNode) | Out-Null;
        }

        $description = $formXml.CreateElement("controlDescription");
        $description.SetAttribute("forControl", $uniqueId);

        $defaultControl = $formXml.CreateElement("customControl");
        $defaultControl.SetAttribute("id", $defaultClassId);
        $defaultParameters = $formXml.CreateElement("parameters");
        $dataFieldNode = $formXml.CreateElement("datafieldname");
        $dataFieldNode.InnerText = $FieldName;
        $defaultParameters.AppendChild($dataFieldNode) | Out-Null;
        $defaultControl.AppendChild($defaultParameters) | Out-Null;
        $description.AppendChild($defaultControl) | Out-Null;

        foreach ($formFactor in $FormFactors) {
            $customControlNode = $formXml.CreateElement("customControl");
            $customControlNode.SetAttribute("formFactor", [string]$formFactor);
            $customControlNode.SetAttribute("name", $ControlName);
            $parametersNode = $formXml.CreateElement("parameters");

            $boundNode = $formXml.CreateElement($boundProperty.GetAttribute("name"));
            $boundNode.InnerText = $FieldName;
            $parametersNode.AppendChild($boundNode) | Out-Null;

            foreach ($staticParameter in $staticParameters) {
                $parameterNode = $formXml.CreateElement($staticParameter.Name);
                $parameterNode.SetAttribute("static", "true");
                if ($staticParameter.Type) {
                    $parameterNode.SetAttribute("type", $staticParameter.Type);
                }
                $parameterNode.InnerText = $staticParameter.Value;
                $parametersNode.AppendChild($parameterNode) | Out-Null;
            }

            $customControlNode.AppendChild($parametersNode) | Out-Null;
            $description.AppendChild($customControlNode) | Out-Null;
        }
        $descriptionsNode.AppendChild($description) | Out-Null;

        $updateRecord = New-XrmEntity -LogicalName "systemform" -Id $FormReference.Id -Attributes @{
            "formxml" = $formXml.OuterXml;
        };
        $XrmClient | Update-XrmRecord -Record $updateRecord;

        if ($Publish) {
            $XrmClient | Publish-XrmComponent -ComponentName "entity" -ComponentId $form.EntityLogicalName | Out-Null;
        }
    }
    end {
        $StopWatch.Stop();
        Trace-XrmFunction -Name $MyInvocation.MyCommand.Name -Stage Stop -StopWatch $StopWatch;
    }
}

Export-ModuleMember -Function Add-XrmFormControl -Alias *;