tests/Customization/PCF.Tests.ps1

<#
    Integration Test: PCF form controls (defect batch 5: H11, H12, M28)
    Get-XrmFormControls, Add-XrmFormControl, Remove-XrmFormControl on a copy of an account main form.
    The FormXML written must match what the platform stores for a bound control (checked on 52 system forms, 2026-12-04):
    controlDescriptions under <form>, forControl = uniqueid of the field control, default control first, one customControl per form factor.
#>

. "$PSScriptRoot\..\_TestConfig.ps1";

$module = Get-Module PowerDataOps;
$suffix = Get-Random -Minimum 10000 -Maximum 99999;
function Get-DraftFormXml([Guid] $FormId) { return (& $module { param($client, $id) Get-XrmFormXmlInternal -XrmClient $client -FormId $id -Unpublished } $Global:XrmClient $FormId).FormXml; }
function Get-FieldControl([xml] $FormXml, [string] $Field) { return $FormXml.SelectSingleNode("/form/tabs//control[@datafieldname='$Field']"); }
function Get-FieldDescription([xml] $FormXml, [string] $Field) {
    $uniqueId = (Get-FieldControl -FormXml $FormXml -Field $Field).GetAttribute("uniqueid");
    if (-not $uniqueId) { return , @(); }
    return , @($FormXml.SelectNodes("//controlDescription") | Where-Object { $_.GetAttribute("forControl") -ieq $uniqueId });
}

Write-Section "Setup - copy of an account main form";

$sourceForm = @(Get-XrmForms -XrmClient $Global:XrmClient -EntityLogicalName "account" -FormType 2 -Columns "name", "formxml") | Where-Object {
    $_.formxml -match 'datafieldname="donotemail"' -and $_.formxml -match 'datafieldname="industrycode"' -and $_.formxml -match 'datafieldname="telephone1"'
} | Select-Object -First 1;
Assert-Test "Account main form with donotemail, industrycode and telephone1: '$($sourceForm.name)'" { $null -ne $sourceForm };
$formRef = Copy-XrmForm -XrmClient $Global:XrmClient -SourceFormId $sourceForm.Id -NewName "PDO PCF $suffix";
Assert-Test "Form copied" { $null -ne $formRef -and $formRef.Id -ne [Guid]::Empty };

try {
    [xml]$sourceXml = $sourceForm.formxml;
    $originalClassId = (Get-FieldControl -FormXml $sourceXml -Field "donotemail").GetAttribute("classid");

    # ============================================================
    Write-Section "Get-XrmFormControls (H11)";
    # ============================================================
    $getError = $null;
    $before = @();
    try { $before = @(Get-XrmFormControls -XrmClient $Global:XrmClient -FormReference $formRef -Unpublished -ErrorAction Stop); } catch { $getError = $_.Exception.Message; }
    Assert-Test "Reads the form without error, no binding on the test fields ($getError)" { $null -eq $getError -and @($before | Where-Object { $_.FieldName -in "donotemail", "industrycode", "telephone1" }).Count -eq 0 };

    # ============================================================
    Write-Section "Add-XrmFormControl - FormXML written (H12)";
    # ============================================================
    Add-XrmFormControl -XrmClient $Global:XrmClient -FormReference $formRef -FieldName "donotemail" -ControlName "MscrmControls.FieldControls.ToggleControl" -Publish $false;
    $draft = Get-DraftFormXml -FormId $formRef.Id;
    $control = Get-FieldControl -FormXml $draft -Field "donotemail";
    $descriptions = Get-FieldDescription -FormXml $draft -Field "donotemail";
    $description = $descriptions | Select-Object -First 1;
    Assert-Test "One controlDescription under <form>/controlDescriptions, for the uniqueid of the field control" {
        $descriptions.Count -eq 1 -and $description.ParentNode.Name -eq "controlDescriptions" -and $description.ParentNode.ParentNode.Name -eq "form";
    };
    Assert-Test "Field control kept: classid $originalClassId" { $control.GetAttribute("classid") -eq $originalClassId };
    $defaultControl = $description.FirstChild;
    Assert-Test "Default control first: id = classid of the field, datafieldname" { $defaultControl.GetAttribute("id") -eq $originalClassId -and $defaultControl.SelectSingleNode("parameters/datafieldname").InnerText -eq "donotemail" };
    $named = @($description.SelectNodes("customControl[@name]"));
    Assert-Test "One customControl per form factor (0, 1, 2), bound property 'value' = donotemail" {
        ($named | ForEach-Object { $_.GetAttribute("formFactor") }) -join "," -eq "0,1,2" -and
        @($named | Where-Object { $_.GetAttribute("name") -eq "MscrmControls.FieldControls.ToggleControl" -and $_.SelectSingleNode("parameters/value").InnerText -eq "donotemail" }).Count -eq 3;
    };

    # ============================================================
    Write-Section "Static parameters, draft kept (M28)";
    # ============================================================
    Add-XrmFormControl -XrmClient $Global:XrmClient -FormReference $formRef -FieldName "industrycode" -ControlName "MscrmControls.FieldControls.OptionSet" -Parameters @{ "showassingleline" = $true } -Publish $false;
    $draft = Get-DraftFormXml -FormId $formRef.Id;
    Assert-Test "Unpublished binding of donotemail kept by the second call (M28)" { (Get-FieldDescription -FormXml $draft -Field "donotemail").Count -eq 1 };
    $staticNode = (Get-FieldDescription -FormXml $draft -Field "industrycode")[0].SelectSingleNode("customControl[@formFactor='0']/parameters/ShowAsSingleLine");
    Assert-Test "Static parameter named as in the manifest: <ShowAsSingleLine static=`"true`" type=`"TwoOptions`">true</ShowAsSingleLine>" {
        $null -ne $staticNode -and $staticNode.GetAttribute("static") -eq "true" -and $staticNode.GetAttribute("type") -eq "TwoOptions" -and $staticNode.InnerText -eq "true";
    };
    $rows = @(Get-XrmFormControls -XrmClient $Global:XrmClient -FormReference $formRef -Unpublished);
    $industryRows = @($rows | Where-Object { $_.FieldName -eq "industrycode" });
    Assert-Test "Get-XrmFormControls -Unpublished: 3 rows per field, with their parameters" {
        @($rows | Where-Object { $_.FieldName -eq "donotemail" }).Count -eq 3 -and $industryRows.Count -eq 3 -and
        $industryRows[0].ControlId -eq "industrycode" -and $industryRows[0].Parameters["value"] -eq "industrycode" -and $industryRows[0].Parameters["ShowAsSingleLine"] -eq "true";
    };

    # ============================================================
    Write-Section "Errors";
    # ============================================================
    $parameterError = $null;
    try { Add-XrmFormControl -XrmClient $Global:XrmClient -FormReference $formRef -FieldName "industrycode" -ControlName "MscrmControls.FieldControls.OptionSet" -Parameters @{ "nosuch" = 1 } -Publish $false -ErrorAction Stop; } catch { $parameterError = $_.Exception.Message; }
    Assert-Test "Unknown parameter: error listing the properties" { $parameterError -like "*'nosuch' is not a property*ShowAsSingleLine*" };
    $controlError = $null;
    try { Add-XrmFormControl -XrmClient $Global:XrmClient -FormReference $formRef -FieldName "industrycode" -ControlName "Pdo.NoSuchControl$suffix" -Publish $false -ErrorAction Stop; } catch { $controlError = $_.Exception.Message; }
    Assert-Test "Unknown PCF control: error" { $controlError -like "*'Pdo.NoSuchControl$suffix' not found*" };
    $fieldError = $null;
    try { Add-XrmFormControl -XrmClient $Global:XrmClient -FormReference $formRef -FieldName "nosuchfield$suffix" -ControlName "MscrmControls.FieldControls.ToggleControl" -Publish $false -ErrorAction Stop; } catch { $fieldError = $_.Exception.Message; }
    Assert-Test "Field not on the form: error" { $fieldError -like "*'nosuchfield$suffix' not found*" };

    # ============================================================
    Write-Section "Replace, -FormFactors, -WhatIf";
    # ============================================================
    Add-XrmFormControl -XrmClient $Global:XrmClient -FormReference $formRef -FieldName "donotemail" -ControlName "MscrmControls.FieldControls.CheckboxControl" -FormFactors 0 -Publish $false;
    $draft = Get-DraftFormXml -FormId $formRef.Id;
    $replaced = Get-FieldDescription -FormXml $draft -Field "donotemail";
    Assert-Test "Second binding on donotemail replaces the first: one description, Checkbox on Web only, same default control" {
        $replaced.Count -eq 1 -and @($replaced[0].SelectNodes("customControl[@name]")).Count -eq 1 -and
        $replaced[0].SelectSingleNode("customControl[@name]").GetAttribute("name") -eq "MscrmControls.FieldControls.CheckboxControl" -and $replaced[0].FirstChild.GetAttribute("id") -eq $originalClassId;
    };

    $whatIfErrors = $null;
    Add-XrmFormControl -XrmClient $Global:XrmClient -FormReference $formRef -FieldName "telephone1" -ControlName "MscrmControls.FieldControls.PhoneNumberControl" -WhatIf -ErrorVariable whatIfErrors;
    Assert-Test "-WhatIf: no binding written, no error" { (Get-FieldDescription -FormXml (Get-DraftFormXml -FormId $formRef.Id) -Field "telephone1").Count -eq 0 -and $whatIfErrors.Count -eq 0 };

    # ============================================================
    Write-Section "Publish";
    # ============================================================
    Add-XrmFormControl -XrmClient $Global:XrmClient -FormReference $formRef -FieldName "telephone1" -ControlName "MscrmControls.FieldControls.PhoneNumberControl";
    $published = @(Get-XrmFormControls -XrmClient $Global:XrmClient -FormReference $formRef);
    Assert-Test "Published form (table published by the call): telephone1, donotemail and industrycode bound" {
        @($published | Where-Object { $_.FieldName -eq "telephone1" -and $_.ControlName -eq "MscrmControls.FieldControls.PhoneNumberControl" }).Count -eq 3 -and
        @($published | Where-Object { $_.FieldName -eq "donotemail" }).Count -eq 1 -and @($published | Where-Object { $_.FieldName -eq "industrycode" }).Count -eq 3;
    };

    # ============================================================
    Write-Section "Remove-XrmFormControl";
    # ============================================================
    $warnings = $null;
    Remove-XrmFormControl -XrmClient $Global:XrmClient -FormReference $formRef -FieldName "donotemail" -ControlName "Pdo.Other" -Publish $false -WarningVariable warnings -WarningAction SilentlyContinue;
    Assert-Test "Other control name: warning, binding kept" { $warnings.Count -eq 1 -and (Get-FieldDescription -FormXml (Get-DraftFormXml -FormId $formRef.Id) -Field "donotemail").Count -eq 1 };

    Remove-XrmFormControl -XrmClient $Global:XrmClient -FormReference $formRef -FieldName "industrycode" -ControlName "MscrmControls.FieldControls.OptionSet" -Publish $false;
    Remove-XrmFormControl -XrmClient $Global:XrmClient -FormReference $formRef -FieldName "donotemail" -Publish $false;
    $draft = Get-DraftFormXml -FormId $formRef.Id;
    Assert-Test "-ControlName and all controls: industrycode and donotemail unbound, telephone1 kept, field classid unchanged" {
        (Get-FieldDescription -FormXml $draft -Field "industrycode").Count -eq 0 -and (Get-FieldDescription -FormXml $draft -Field "donotemail").Count -eq 0 -and
        (Get-FieldDescription -FormXml $draft -Field "telephone1").Count -eq 1 -and (Get-FieldControl -FormXml $draft -Field "donotemail").GetAttribute("classid") -eq $originalClassId;
    };

    Remove-XrmFormControl -XrmClient $Global:XrmClient -FormReference $formRef -FieldName "telephone1";
    $afterRemove = @(Get-XrmFormControls -XrmClient $Global:XrmClient -FormReference $formRef);
    Assert-Test "Published form: no binding left on the test fields" { @($afterRemove | Where-Object { $_.FieldName -in "donotemail", "industrycode", "telephone1" }).Count -eq 0 };
}
finally {
    Write-Section "Cleanup";
    Remove-XrmForm -XrmClient $Global:XrmClient -FormReference $formRef;
    Assert-Test "Test form deleted" { $null -eq ($Global:XrmClient | Get-XrmRecord -LogicalName "systemform" -Id $formRef.Id -IfExists) };
}

Write-TestSummary;