SharePoint Online (Office PnP): Populate default fields in View dynamically

Scenarios: How to add all fields into view dynamically


Code Snippet

Function AddDefaultFieldsToView {
	Param (
		[Parameter(Mandatory=$True)] 
        [string]$ContentTypeName,
		[Parameter(Mandatory=$True)] 
        [string]$ViewName,
		[Parameter(Mandatory=$True)] 
        [string]$ListName
	)

	$view = Get-PnPView -Identity $ViewName -List $ListName
	if($view -eq $null) {
		Write-Host "View $ViewName does not exist in $ListName"
		return
	}

	$ct = Get-PnPContentType -InSiteHierarchy -Identity $ContentTypeName	
	$columns = Get-PnPProperty -ClientObject $ct -Property "Fields"

	Write-Host "Applying default columns to View: '$ViewName' from ContentType: '$ContentTypeName'"
    foreach ($column in $columns | Where-Object { !$_.Hidden } ) {        
		if($view.ViewFields -contains $column.InternalName){
			Write-Host ("'" + $column.Title + "' already exist in View")
			continue
		}

        if ($column.Title -match "Modified By" -or
			$column.Title -match "Created By" -or
			$column.Title -eq "Name" -or
			$column.Title -eq "Content Type" -or
			$column.Title -eq "Title"
		) {
			#system fields				
            continue
        }
		
        $view.ViewFields.Add($column.Title)        
		Write-Host ("Added field '" + $column.Title + "' to '" + $ViewName + "'")
    }

	$view.Update()
	Execute-PnPQuery
	Write-Host "Applied default columns"
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s