There are a lot of forum threads about the error that InplaceSearchEnabled property of XsltListViewWebPart (XLV) cannot be changed programmatically, only through UI and WebPart properties. I experienced the same issue when was trying to add XLV to sub site (display items of root level list on subsite) - the search input was not displayed and the InplaceSearchEnabled property was set to null. Finally I found the solution (actually a workaround) and it is described below.
First I was trying to debug SharePoint.dll assembly (thanks to .NET Reflector) but the code was to complicated and full of Reflection. So I decided to look into the client-side part of the search functionality. And here what I found:
Search input is located inside inplaceSearchDiv_<wpq> div which is added to HTML in sp.ui.listsearchboxbootstrap.js. So we need to include this script to our page.
The div is rendered for the web part that is registered in g_listSearchBoxInfo global array and if ListSchema's property InplaceSearchEnabled is set to true.
The content of that div is added in sp.ui.listsearchbox.js.
In the code of the page with working search sp.ui.listsearchboxbootstrap.js is added as simple script, sp.ui.listsearchbox.js is registered as SOD with a bunch of dependencies:
So based on these observations I decided to add search using JavaScript (even if the InplaceSearchEnabled property itself was not set). Here are the actions to initialize all we need:
Add JSLink property to Web Part to load custom code when the Web Part is rendering
Load all needed scripts and register them as SOD if needed
Get Web Part's wpq identifier and register it in g_listSearchBoxInfo
Set ListSchema.InplaceSearchEnabled to true
Enjoy the result
And here is the code:
This will add search input to the web part and it will work as expected. Additional remarks: resources (.resx SODs) are loaded with culture parameter which is set to en-us here (I don't need any other culture). But if your portal will potentially use different cultures you can get the name of current culture from _spPageContextInfo. It will be available in onload event. The same I can say about /_layouts/15/ path. You can use _spPageContextInfo.layoutsUrl to get Layouts folder Url. This code shows you how to enable the search. If it is enabled and you want to disable it you can just set ListSchema.InplaceSearchEnabled to false and remove registration of the wpq from g_listSearchBoxInfo.
Comments