New-UDTable: Allow Add/Edit/Delete of data?

Edit: This post actually helped me improve the deletion by having it be buttons and include a prompt to ensure users want to delete the object). Still trying to figure out how to add a row as well as edit an existing row within the page.

I am trying to build a dashboard to allow staff to view/modify the contents of a CSV file. In this case, it’s printer files that define the printers available to a virtual desktop.

The CSV is one or more lines containing the hostname, printer IP, printer name, and printer driver to use.

A sanitized example:

Hostname,PrinterIP,PrinterName,PrinterDriver
PC001,10.0.0.63,Printer01,HP LaserJet 4
PC001,10.0.0.83,Printer02,Xerox VersaLink C400 PCL6
PC001,10.0.0.58,Printer03,Xerox Phaser 6600DN PCL6

Of note, the first printer in the file becomes the default in Windows for the user. So I have the following main goals:

  • Add a new row
  • Allow selecting a default (or re-ordering the list dynamically to place a new item in the first row)
  • Change a value within a row (e.g. change the “Printer Name” or “Printer IP” on a row)
  • Delete an existing row

I’ve had some success with the updating the default printer or deleting a row using the below code, however, users have to reclick on the “Submit” button to modify/update the table. More importantly, I’m stumped how to set the table to allow for adding a row or to modify an existing value in one of the existing rows. I am not particularly proud of the below code at all, so if there is a better approach, I am completely open.

(Code modified with updated ‘Delete’ handling)

New-UDPage -Name 'Printer Info' -Content {
    New-UDTypography -Text 'Enter endpoint name'
    New-UDForm -Content {
        New-UDTextbox -Id 'Endpoint' -Placeholder 'Endpoint Name'
    } -OnSubmit {
        $CsvRootPath = 'D:\Files\PrinterFiles'
        Try{
            $CsvFile = Join-Path $CsvRootPath "$($EventData.Endpoint).csv"
            [Array]$RawData = Import-Csv $CsvFile -ErrorAction Stop
            $DefaultPrinter = ($RawData | Select-Object -First 1).PrinterName
            $FormattedData = $RawData.ForEach({
                $Obj = [PSCustomObject]@{
                    DefaultPrinter = $null
                    Hostname = $_.Hostname
                    PrinterName = $_.PrinterName
                    PrinterIP = $_.PrinterIP
                    PrinterDriver = $_.PrinterDriver
                }
                If($_.PrinterName -eq $DefaultPrinter){
                    $Obj.DefaultPrinter = 'True'
                }
                $Obj #Returns object to $FormattedData parent array
            })
            $Columns = @(
                New-UDTableColumn -Property Hostname -Title 'Endpoint Name'
                New-UDTableColumn -Property PrinterName -Title 'Printer Name'
                New-UDTableColumn -Property PrinterIP -Title 'Printer IP'
                New-UDTableColumn -Property PrinterDriver -Title 'Printer Driver'
                New-UDTableColumn -Property DefaultPrinter -Title 'Default Printer'
                New-UDTableColumn -Property Delete -Title Delete -Render {
                    New-UDButton -Id 'btnDeletePrinter' -Text 'Delete' -OnClick {
                        Show-UDModal -Content {
                            $PrinterName = $eventdata.PrinterName
                            New-UDForm -Content {
                                New-UDCheckBox -Label "Check box and press submit to confirm deletion of [$PrinterName], click outside of this box to cancel."  -Id 'Confirmation'
                            } -OnSubmit {
                                If ((Get-UDElement -Id 'Confirmation').checked -eq $true) {
                                    Show-UDToast -Message "Deleting $PrinterName"
                                    $Output = $RawData.Where({$_.PrinterName -notin $PrinterName})
                                    $Output | Export-Csv $CsvFile -NoTypeInformation -Force
                                    Start-sleep -Seconds 2
                                    Hide-UDModal
                                }
                                Else {
                                    Show-UDToast -Title 'Checkbox' -Message "NOT deleting $topic."
                                    Start-sleep -Seconds 2
                                    Hide-UDModal
                                }
                            }                        
                        } -FullWidth -MaxWidth 'md'
                    }
                }
            )
            Set-UDElement -Id 'ElementJobOutput' -Content {
                New-UDCard -Id 'CardJobOutput' -Title "Printer Info [$($EventData.Endpoint.ToUpper())]" -Content {                
                    New-UDTable -Id 'TablePrinterInfo' -Data $FormattedData -Columns $Columns -ShowSelection
                }
                Set-UDElement -Id 'SubmitButton' -Content {
                    New-UDButton -Id "btnUpdateDefaultPrinter" -Text "Set Default Printer" -OnClick {
                        $Rows = Get-UDElement -Id 'TablePrinterInfo'
                        If($Rows.SelectedRows.Count -eq 0){
                            Show-UDToast -Message "Must select one printer" -CloseOnClick -Position center -Duration 10000
                        } Elseif($Rows.SelectedRows.Count -gt 1){
                            Show-UDToast -Message "Cannot set more than one default printer" -CloseOnClick -Position center -Duration 10000
                        } Elseif($Rows.SelectedRows.Count -eq 1) {
                            Show-UDToast -Message "Updating [$($EventData.Endpoint.ToUpper())] default printer to [$($Rows.SelectedRows.PrinterName)]" -Duration 2500
                            $NewDefaultPrinter = $Rows.SelectedRows.PrinterName
                            $NewDefaultArray = $RawData.ForEach({
                                $Obj = [PSCustomObject]@{
                                    DefaultPrinter = $null
                                    Hostname = $_.Hostname
                                    PrinterName = $_.PrinterName
                                    PrinterIP = $_.PrinterIP
                                    PrinterDriver = $_.PrinterDriver
                                }
                                If($_.PrinterName -eq $NewDefaultPrinter){
                                    $Obj.DefaultPrinter = 'True'
                                }
                                $Obj
                            })

                            $Sorted = $NewDefaultArray | Group-Object DefaultPrinter | Sort-Object Name -Descending
                            # Create sorted Array for export
                            $ExportArray = Foreach ($Item in $Sorted){
                                $Item.Group
                            }
                            # Export to CSV file
                            $ExportArray | Export-Csv $CsvFile -NoTypeInformation

                        } 
                        
                    }
                    
                }
            }
        } Catch {
            Set-UDElement -Id 'ElementJobOutput' -Content {
                "$($Error[0].exception.message)"
            }
        }        
    }
    New-UDElement -Id 'ElementJobOutput' -Tag 'div' # New empty element to be updated/displayed after user clicks 'Submit'
    New-UDElement -Id 'SubmitButton' -Tag 'div2'
}
1 Like

We don’t have this built into the table but you might be able to use table selection to allow for editing.

You could create a form below the table that has the fields you wish to edit and then when the user selects a row, that form is populated with the current data. You could also use a similar for for adding and then refresh the table after the row has been edited.

I realize it’s not a great experience but might suffice for the mean time.

Do you have an example I can build from? The part I’m struggling to understand is automatically refreshing the data without having to resubmit the form since I am using New-UDElement and Set-UDElement. When using New/Set, the Sync-UDElement command doesn’t seem to behave the same versus when using the New-UDDynamic cmdlet.

I’ll have to put something together. I don’t have an example on hand.

Here’s an example of a CSV editor. It allows you to upload a file, then you can select and edit rows as well as add rows.

New-UDDashboard -Title "Hello, World!" -Content {
    New-UDUpload -OnUpload {
        $Csv = [IO.Path]::GetTempFileName()
        $Data = $Body | ConvertFrom-Json 
        $bytes = [System.Convert]::FromBase64String($Data.Data)
        [System.IO.File]::WriteAllBytes($Csv, $bytes)
        $Session:CsvPath = $Csv

        Sync-UDElement -Id 'table'
    } -Text 'Upload CSV'

    New-UDButton -Text "Add Row" -OnClick {
        $Session:ShowAdd = $true 
        Sync-UDElement -Id 'addEditor'
    }

    New-UDDynamic -Id 'table' -Content {
        if ($Session:CsvPath)
        {
            $Csv = Import-Csv -Path $Session:CsvPath
            New-UDTable -Data $Csv -ShowSelection -OnRowSelection {
                if ($EventData.Selected)
                {
                    $Session:SelectedRow = $EventData
                    Sync-UDElement -Id 'editor'
                }

            } -DisableMultiSelect
        }
    }

    New-UDDynamic -Id 'editor' -Content {
        if ($Session:SelectedRow)
        {
            New-UDCard -Title "Edit row $($Session:SelectedRow.Id)" -Content {
                New-UDForm -Content {
                    $Csv = Import-Csv -Path $Session:CsvPath
                    $RowData = $Csv[$Session:SelectedRow.Id]
                    $RowData | Get-Member -MemberType Properties | ForEach-Object {
                        New-UDTextbox -Id $_.Name -Label $_.Name -Value $RowData.$($_.Name)
                    }
                } -OnSubmit {
                    $Csv = Import-Csv -Path $Session:CsvPath
                    $Csv[$Session:SelectedRow.Id] = $EventData 
                    $Csv | Export-Csv -Path $Session:CsvPath
                    $Session:SelectedRow = $null

                    Sync-UDElement -Id 'editor'
                    Sync-UDElement -Id 'table'
                } -OnCancel {
                    $Session:SelectedRow = $null
                    Sync-UDElement -Id 'editor'
                }
            }
        }
    }

    New-UDDynamic -Id 'addEditor' -Content {
        if ($Session:ShowAdd)
        {
            New-UDCard -Title "Add Row" -Content {
                New-UDForm -Content {
                    $Csv = Import-Csv -Path $Session:CsvPath
                    $RowData = $Csv[0]
                    $RowData | Get-Member -MemberType Properties | ForEach-Object {
                        New-UDTextbox -Id $_.Name -Label $_.Name 
                    }
                } -OnSubmit {
                    $Csv = Import-Csv -Path $Session:CsvPath
                    $Csv += $EventData 
                    $Csv | Export-Csv -Path $Session:CsvPath
                    $Session:ShowAdd = $false

                    Sync-UDElement -Id 'addEditor'
                    Sync-UDElement -Id 'table'
                } -OnCancel {
                    $Session:ShowAdd = $false
                    Sync-UDElement -Id 'addEditor'
                }
            }
        }
    }
}

1 Like

@adam, thank you so much for the example. I was able to take that bit of code and work it for my needs. I’ve now got every one of my bullet points working except deleting a row. The logic I am using worked previously when I created the table via New/Set-UDElement, but for whatever reason the dynamic version now always returns the last row of the CSV file when using the delete button. So no matter which ‘Delete’ button I click, it always removes the last row and I can’t figure out where I am going wrong. Any ideas?

This is the relevant section

New-UDButton -Id 'btnDeletePrinter' -Text 'Delete' -OnClick {
    # How do I get the printer name from the row where the Delete button was clicked? #
    # Does not work, $EventData scoping issue? I have it working from when I was using New/Set-UDElement, but unsure why this isn't working here #
    $PrinterName = $EventData.PrinterName
    Show-UDModal -Content {
        New-UDForm -Content {
            New-UDCheckBox -Label "Check box and press submit to confirm deletion of [TBD as `$PrinterName>], click outside of this box to cancel."  -Id 'Confirmation'
        } -OnSubmit {
            If ((Get-UDElement -Id 'Confirmation').checked -eq $true) {
                $Output = $Session:FormattedData.Where({$_.PrinterName -notin $PrinterName})
                $Output | Export-Csv $Session:CsvPath -NoTypeInformation -Force
                Sync-UDElement -Id 'table'
                Hide-UDModal
            }
            Else {
                Show-UDToast -Title 'Checkbox' -Message "NOT deleting $topic."
                Start-sleep -Seconds 2
                Hide-UDModal
            }
        }                        
    } -FullWidth -MaxWidth 'md'
}

And here is the full code for the page:

$PagePrinterInfo = New-UDPage -Name 'Get Printer Info - Dynamic' -Content {
    New-UDTypography -Text 'Enter endpoint hostname'
    New-UDForm -Content {
        New-UDTextbox -Id 'Endpoint' -Placeholder 'Endpoint Hostname'
    } -OnSubmit {
        $Properties = "HostName","PrinterIP","PrinterName","PrinterDriver"
        $Session:Endpoint = $EventData.Endpoint
        New-UDDynamic -Id 'table' -Content {
            $CsvRootPath = 'D:\Files\PrinterFiles'
            $Session:CsvPath = Join-Path $CsvRootPath "$($Session:Endpoint).csv"
            if ($Session:CsvPath) {
                [Array]$RawData = Import-Csv $Session:CsvPath -ErrorAction Stop
                $DefaultPrinter = ($RawData | Select-Object -First 1).PrinterName
                $Session:FormattedData = $RawData.ForEach({
                    $Obj = [PSCustomObject]@{
                        DefaultPrinter = $null
                        Hostname = $_.Hostname
                        PrinterName = $_.PrinterName
                        PrinterIP = $_.PrinterIP
                        PrinterDriver = $_.PrinterDriver
                    }
                    If($_.PrinterName -eq $DefaultPrinter){ # Set 'Default Printer' in output
                        $Obj.DefaultPrinter = 'True'
                    }

                    $Obj #Returns object to $FormattedData parent array
                })

                # Create Table from Data #
                $Columns = @(
                    New-UDTableColumn -Property Hostname -Title 'Endpoint Name'
                    New-UDTableColumn -Property PrinterName -Title 'Printer Name'
                    New-UDTableColumn -Property PrinterIP -Title 'Printer IP'
                    New-UDTableColumn -Property PrinterDriver -Title 'Printer Driver'
                    New-UDTableColumn -Property DefaultPrinter -Title 'Default Printer'
                    New-UDTableColumn -Property Delete -Title Delete -Render {
                        New-UDButton -Id 'btnDeletePrinter' -Text 'Delete' -OnClick {
                            # How do I get the printer name from the row where the Delete button was clicked? #
                            # Does not work, $EventData scoping issue? I have it working from when I was using New/Set-UDElement, but unsure why this isn't working here #
                            $PrinterName = $EventData.PrinterName
                            Show-UDModal -Content {
                                New-UDForm -Content {
                                    New-UDCheckBox -Label "Check box and press submit to confirm deletion of [TBD as `$PrinterName>], click outside of this box to cancel."  -Id 'Confirmation'
                                } -OnSubmit {
                                    If ((Get-UDElement -Id 'Confirmation').checked -eq $true) {
                                        $Output = $Session:FormattedData.Where({$_.PrinterName -notin $PrinterName})
                                        $Output | Export-Csv $Session:CsvPath -NoTypeInformation -Force
                                        Sync-UDElement -Id 'table'
                                        Hide-UDModal
                                    }
                                    Else {
                                        Show-UDToast -Title 'Checkbox' -Message "NOT deleting $topic."
                                        Start-sleep -Seconds 2
                                        Hide-UDModal
                                    }
                                }                        
                            } -FullWidth -MaxWidth 'md'
                        }
                    }
                )
                New-UDTable -Data $Session:FormattedData -Columns $Columns -ShowSelection -OnRowSelection {
                    if ($EventData.Selected){
                        $Session:SelectedRow = $EventData
                        Sync-UDElement -Id 'editor'
                    }
                } -DisableMultiSelect
            }
        }

        New-UDDynamic -Id 'editor' -Content {
            if ($Session:SelectedRow){
                New-UDCard -Title "Edit Printer [$($Session:SelectedRow.PrinterName)]" -Content {
                    New-UDForm -Content {
                        $RowData = $Session:FormattedData[$Session:SelectedRow.Id]
                        If($RowData.DefaultPrinter -eq $true){
                            $DefaultValue = 'Yes'
                        } Else {
                            $DefaultValue = 'No'
                        }
                        
                        New-UDSelect -Label "Default Printer?" -Option {
                            New-UDSelectOption -Name 'Yes' -Value 'Yes'
                            New-UDSelectOption -Name 'No' -Value 'No'
                        } -Id 'DefaultPrinterSelection' -DefaultValue $DefaultValue

                        $RowData | Select-Object $Properties | Get-Member -MemberType Properties | ForEach-Object {
                            New-UDTextbox -Id $_.Name -Label $_.Name -Value $RowData.$($_.Name)
                        }
                    } -OnSubmit {
                        If($EventData.DefaultPrinterSelection -eq 'Yes'){
                            $PrinterTarget = $EventData.PrinterName
                            $Csv = Import-Csv -Path $Session:CsvPath
                            $Csv[$Session:SelectedRow.Id] = $EventData
                            $NewDefaultArray = $Csv.ForEach({
                                $Obj = [PSCustomObject]@{
                                    DefaultPrinter = $null
                                    Hostname = $_.Hostname
                                    PrinterName = $_.PrinterName
                                    PrinterIP = $_.PrinterIP
                                    PrinterDriver = $_.PrinterDriver
                                }
                                If($_.PrinterName -eq $PrinterTarget -and $EventData.DefaultPrinterSelection -eq 'Yes'){
                                    $Obj.DefaultPrinter = 'True'
                                }
                                $Obj
                            })

                            $Sorted = $NewDefaultArray | Group-Object DefaultPrinter | Sort-Object Name -Descending
                            # Create sorted Array for export
                            $ExportArray = Foreach ($Item in $Sorted){
                                $Item.Group
                            }
                            # Export to CSV file
                            $ExportArray | Select-Object $Properties | Export-Csv -Path $Session:CsvPath
                        } Else {
                            $Csv = Import-Csv -Path $Session:CsvPath
                            $Csv[$Session:SelectedRow.Id] = $EventData
                            $Csv | Select-Object $Properties | Export-Csv -Path $Session:CsvPath
                        }
                        $Session:SelectedRow = $null
                        Sync-UDElement -Id 'editor'
                        Sync-UDElement -Id 'table'
                    } -OnCancel {
                        $Session:SelectedRow = $null
                        Sync-UDElement -Id 'editor'
                    }
                }
            }
        }

        New-UDButton -Text "Add Row" -OnClick {
            $Session:ShowAdd = $true 
            Sync-UDElement -Id 'addEditor'
        }

        New-UDDynamic -Id 'addEditor' -Content {
            if ($Session:ShowAdd)
            {
                New-UDCard -Title "Add Row" -Content {
                    New-UDForm -Content {
                        New-UDSelect -Label "Default Printer?" -Option {
                            New-UDSelectOption -Name 'Yes' -Value 'Yes'
                            New-UDSelectOption -Name 'No' -Value 'No'
                        } -Id 'DefaultPrinterSelection' -DefaultValue 'No'

                        $Csv = Import-Csv -Path $Session:CsvPath
                        $RowData = $Csv[0]
                        # Create predefined textbox based on the hostname of the CSV file
                        New-UDTextbox -Id 'Hostname' -Label 'Hostname' -Value $RowData.HostName
                        # Create empty text boxes for remaining properties (Printer Name/IP/Driver)
                        $RowData | Select-Object $Properties -ExcludeProperty Hostname | Get-Member -MemberType Properties | ForEach-Object {
                            New-UDTextbox -Id $_.Name -Label $_.Name 
                        }
                    } -OnSubmit {
                        If($EventData.DefaultPrinterSelection -eq 'Yes'){
                            $NewDefaultPrinter = $EventData.PrinterName
                            $Csv = Import-Csv -Path $Session:CsvPath
                            $NewCsv = $Csv += $EventData
                            $NewDefaultArray = $NewCsv.ForEach({
                                $Obj = [PSCustomObject]@{
                                    DefaultPrinter = $null
                                    Hostname = $_.Hostname
                                    PrinterName = $_.PrinterName
                                    PrinterIP = $_.PrinterIP
                                    PrinterDriver = $_.PrinterDriver
                                }
                                If($_.PrinterName -eq $NewDefaultPrinter){
                                    $Obj.DefaultPrinter = 'True'
                                }
                                $Obj
                            })

                            $Sorted = $NewDefaultArray | Group-Object DefaultPrinter | Sort-Object Name -Descending
                            # Create sorted Array for export
                            $ExportArray = Foreach ($Item in $Sorted){
                                $Item.Group
                            }
                            # Export to CSV file
                            $ExportArray | Select-Object  $Properties | Export-Csv -Path $Session:CsvPath
                        } Else {
                            $Csv = Import-Csv -Path $Session:CsvPath
                            $Csv += $EventData 
                            $Csv | Select-Object $Properties | Export-Csv -Path $Session:CsvPath
                        }
                        
                        $Session:ShowAdd = $false
                        Sync-UDElement -Id 'addEditor'
                        Sync-UDElement -Id 'table'
                    } -OnCancel {
                        $Session:ShowAdd = $false
                        Sync-UDElement -Id 'addEditor'
                    }
                }
            }
        }
    }
} -NavigationLayout permanent -Navigation $NavigationSvcDesk -Url '/getprinterinfo'

Try removing the ID from the button. The reason it’s deleting the last row is because it’s overwriting the button script block with each row.

That did it! I’m able to perform all four functions successfully! In case it can benefit anyone else, below is the working page code. Thanks again @adam!!

$PageGetPrinterInfo = New-UDPage -Name 'Get Printer Info - Dynamic' -Content {
    New-UDTypography -Text 'Enter endpoint hostname'
    New-UDForm -Content {
        New-UDTextbox -Id 'Endpoint' -Placeholder 'Endpoint Hostname'
    } -OnSubmit {
        $Properties = "HostName","PrinterIP","PrinterName","PrinterDriver"
        $Session:Endpoint = $EventData.Endpoint
        New-UDDynamic -Id 'table' -Content {
            $CsvRootPath = 'D:\Files\PrinterFiles'
            $Session:CsvPath = Join-Path $CsvRootPath "$($Session:Endpoint).csv"

            if ($Session:CsvPath) {
                [Array]$RawData = Import-Csv $Session:CsvPath -ErrorAction Stop
                $DefaultPrinter = ($RawData | Select-Object -First 1).PrinterName
                $Session:FormattedData = $RawData.ForEach({
                    $Obj = [PSCustomObject]@{
                        DefaultPrinter = $null
                        Hostname = $_.Hostname
                        PrinterName = $_.PrinterName
                        PrinterIP = $_.PrinterIP
                        PrinterDriver = $_.PrinterDriver
                    }
                    
                    If($_.PrinterName -eq $DefaultPrinter){
                        $Obj.DefaultPrinter = 'True'
                    }
                    
                    $Obj #Returns object to $FormattedData parent array
                })
                # Create Table from Data #
                $Columns = @(
                    New-UDTableColumn -Property Hostname -Title 'Endpoint Name'
                    New-UDTableColumn -Property PrinterName -Title 'Printer Name'
                    New-UDTableColumn -Property PrinterIP -Title 'Printer IP'
                    New-UDTableColumn -Property PrinterDriver -Title 'Printer Driver'
                    New-UDTableColumn -Property DefaultPrinter -Title 'Default Printer'
                    New-UDTableColumn -Property Delete -Title Delete -Render {
                        New-UDButton -Text 'Delete' -OnClick {
                            $PrinterName = $EventData.PrinterName
                            Show-UDModal -Content {
                                New-UDForm -Content {
                                    New-UDCheckBox -Label "Check box and press submit to confirm deletion of [$PrinterName], click outside of this box to cancel."  -Id 'Confirmation'
                                } -OnSubmit {
                                    If ((Get-UDElement -Id 'Confirmation').checked -eq $true) {
                                        $Output = $Session:FormattedData.Where({$_.PrinterName -notin $PrinterName})
                                        $Output | Select-Object $Properties | Export-Csv $Session:CsvPath -NoTypeInformation -Force
                                        Sync-UDElement -Id 'table'
                                        Hide-UDModal
                                    }
                                    Else {
                                        Show-UDToast -Title 'Checkbox' -Message "NOT deleting $topic."
                                        Start-sleep -Seconds 2
                                        Hide-UDModal
                                    }
                                }                        
                            } -FullWidth -MaxWidth 'md'
                        }
                    }
                )
                New-UDTable -Data $Session:FormattedData -Columns $Columns -ShowSelection -OnRowSelection {
                    if ($EventData.Selected){
                        $Session:SelectedRow = $EventData
                        Sync-UDElement -Id 'editor'
                    }
                } -DisableMultiSelect
            }
        }

        New-UDDynamic -Id 'editor' -Content {
            if ($Session:SelectedRow){
                New-UDCard -Title "Edit Printer [$($Session:SelectedRow.PrinterName)]" -Content {
                    New-UDForm -Content {
                        $RowData = $Session:FormattedData[$Session:SelectedRow.Id]
                        If($RowData.DefaultPrinter -eq $true){
                            $DefaultValue = 'Yes'
                        } Else {
                            $DefaultValue = 'No'
                        }
                        
                        New-UDSelect -Label "Default Printer?" -Option {
                            New-UDSelectOption -Name 'Yes' -Value 'Yes'
                            New-UDSelectOption -Name 'No' -Value 'No'
                        } -Id 'DefaultPrinterSelection' -DefaultValue $DefaultValue

                        $RowData | Select-Object $Properties | Get-Member -MemberType Properties | ForEach-Object {
                            New-UDTextbox -Id $_.Name -Label $_.Name -Value $RowData.$($_.Name)
                        }
                    } -OnSubmit {
                        If($EventData.DefaultPrinterSelection -eq 'Yes'){
                            $PrinterTarget = $EventData.PrinterName
                            $Csv = Import-Csv -Path $Session:CsvPath
                            $Csv[$Session:SelectedRow.Id] = $EventData
                            $NewDefaultArray = $Csv.ForEach({
                                $Obj = [PSCustomObject]@{
                                    DefaultPrinter = $null
                                    Hostname = $_.Hostname
                                    PrinterName = $_.PrinterName
                                    PrinterIP = $_.PrinterIP
                                    PrinterDriver = $_.PrinterDriver
                                }
                                If($_.PrinterName -eq $PrinterTarget -and $EventData.DefaultPrinterSelection -eq 'Yes'){
                                    $Obj.DefaultPrinter = 'True'
                                }
                                $Obj
                            })

                            $Sorted = $NewDefaultArray | Group-Object DefaultPrinter | Sort-Object Name -Descending
                            # Create sorted Array for export
                            $ExportArray = Foreach ($Item in $Sorted){
                                $Item.Group
                            }
                            # Export to CSV file
                            $ExportArray | Select-Object $Properties | Export-Csv -Path $Session:CsvPath
                        } Else {
                            $Csv = Import-Csv -Path $Session:CsvPath
                            $Csv[$Session:SelectedRow.Id] = $EventData
                            $Csv | Select-Object $Properties | Export-Csv -Path $Session:CsvPath
                        }
                        $Session:SelectedRow = $null
                        Sync-UDElement -Id 'editor'
                        Sync-UDElement -Id 'table'
                    } -OnCancel {
                        $Session:SelectedRow = $null
                        Sync-UDElement -Id 'editor'
                    }
                }
            }
        }

        New-UDButton -Text "Add Row" -OnClick {
            $Session:ShowAdd = $true 
            Sync-UDElement -Id 'addEditor'
        }

        New-UDDynamic -Id 'addEditor' -Content {
            if ($Session:ShowAdd)
            {
                New-UDCard -Title "Add Row" -Content {
                    New-UDForm -Content {
                        New-UDSelect -Label "Default Printer?" -Option {
                            New-UDSelectOption -Name 'Yes' -Value 'Yes'
                            New-UDSelectOption -Name 'No' -Value 'No'
                        } -Id 'DefaultPrinterSelection' -DefaultValue 'No'

                        $Csv = Import-Csv -Path $Session:CsvPath
                        $RowData = $Csv[0]
                        # Create predefined textbox
                        New-UDTextbox -Id 'Hostname' -Label 'Hostname' -Value $RowData.HostName
                        # Create empty text boxes for remaining properties (Printer Name/IP/Driver)
                        $RowData | Select-Object $Properties -ExcludeProperty Hostname | Get-Member -MemberType Properties | ForEach-Object {
                            New-UDTextbox -Id $_.Name -Label $_.Name 
                        }
                    } -OnSubmit {
                        If($EventData.DefaultPrinterSelection -eq 'Yes'){
                            $NewDefaultPrinter = $EventData.PrinterName
                            $Csv = Import-Csv -Path $Session:CsvPath
                            $NewCsv = $Csv += $EventData
                            $NewDefaultArray = $NewCsv.ForEach({
                                $Obj = [PSCustomObject]@{
                                    DefaultPrinter = $null
                                    Hostname = $_.Hostname
                                    PrinterName = $_.PrinterName
                                    PrinterIP = $_.PrinterIP
                                    PrinterDriver = $_.PrinterDriver
                                }
                                If($_.PrinterName -eq $NewDefaultPrinter){
                                    $Obj.DefaultPrinter = 'True'
                                }
                                $Obj
                            })

                            $Sorted = $NewDefaultArray | Group-Object DefaultPrinter | Sort-Object Name -Descending
                            # Create sorted Array for export
                            $ExportArray = Foreach ($Item in $Sorted){
                                $Item.Group
                            }
                            # Export to CSV file
                            $ExportArray | Select-Object  $Properties | Export-Csv -Path $Session:CsvPath
                        } Else {
                            $Csv = Import-Csv -Path $Session:CsvPath
                            $Csv += $EventData 
                            $Csv | Select-Object $Properties | Export-Csv -Path $Session:CsvPath
                        }
                        
                        $Session:ShowAdd = $false
                        Sync-UDElement -Id 'addEditor'
                        Sync-UDElement -Id 'table'
                    } -OnCancel {
                        $Session:ShowAdd = $false
                        Sync-UDElement -Id 'addEditor'
                    }
                }
            }
        }
    }
}
1 Like