Enable empty SP search textbox does not update results


Hi Guys,

This post is about enabling empty search queries. By default, when user press ‘Enter’ on an empty Search Box, nothing happens.  A very simple question might be asked that why would anyone search for empty string any way?  True, no one actually needs it desperately but while going in flow this case could cause user bed experiences because users are likely to start with the refiners.

Problem:

Consider this flow:

  1. Navigate to SharePoint Search page
  2. Search with any keyword like “Test”
  3. If search results are not relevant, I just removed Test keyword from the textbox and hit search button.
  4. Nothing actually happens here. It suppose to clear all existing results.

Without the ability to search for the empty string (or a “clear” button), the only way to do same would be to reload the page.

Solution: 

The Search Box webpart supports empty string search. Yes, its true, it’s just disabled by default.  This feature is controlled by a property, AllowEmptySearch, which can not be managed from the UI. This fix is rather easy. This is a property that can be set on the search box, by default set to false. Follow the given instructions to update this property:

  1. Edit the page where search box is placed.
  2. Export your Search Box webart.
  3. Edit the .webpart file using your favorite text editor
  4. Search for the property AllowEmptySearch and update its value to True.
  5. Now import this web part to gallery and add it to your page in place of default search box web part.

This functionality is necessary when you have pages on which you configured the search web parts to use predefined queries in order to show results when the page gets loaded.

When you update this property to true, which can be done by exporting the search box web part, and changing the following line in the XML:

<! old >
<property name=“AllowEmptySearch” type=“bool”>False</property>
<! new >
<property name=“AllowEmptySearch” type=“bool”>True</property>

Note: you can also update the web part with PowerShell.

Another way to approach it is via setting this property from within your display template. To update the property within the search box display template, you have to add the following lines of code:

// Allow empty keyword searches
if (!ctx.ClientControl.get_allowEmptySearch()) {
    ctx.ClientControl.set_allowEmptySearch(true);
}

Hope this small trick helps you solve this issue.

Happy SharePointing !

Ref: Enable empty SPsearch textbox does not update results

Advertisements

Add welcome pop up for first time users of your site using AngularJs Material


Hi Guys,

We really do only have one chance for putting a first impression for end users on our website. User’s will never land back to your website if there is nothing interesting found on web site. Same logic works for SharePoint sites too. When a visitor lands on your site for the first time (and maybe the last), how you welcome them will have a big impact. This can be accomplished with pop-up boxes, fullscreen welcome mats, live chat invitations, and more.

This post is all about a welcome popup on SharePoint site. In brief, I try my best to provide very easy solution of showing welcome pop up.

Requirement: One of my recent project client asked to show a welcome message. Server side webarts are not promoted by out clients because our site was built in SP online. It sounds very easy but complication added by showing this pop up only once per user.

Solution: As a solution, i suggested to achieve this using Content editor web part. Just place some quick JS code on the landing page and with the help of a list we are able to detect if user is first time user or not. So here is the components of this solution:

  1. A list “Users” which stores list of first time users
  2. Content editor web part.
  3. Site Assets library to refer the local references like Angular, Jquery, css etc.

Let me go through step by step implementation of this solution.

Step I: Create a “Users” list

  1. Visit Site > Site contents.
  2. Click on New > Choose Custom List template> Name it as “FirstTimeUsers”.
  3. Once list is created. Navigate to newly created List settings > Add column
  4. Add column “User” of type “Person and Group”.
  5. Now with this list Title field is required. We can make this field hidden or optional if not required.

We are done with creating a list which stores information about first time users. We will be updating using rest api calls and each time when user logged on to site. His/her entries will be added to this list only.

Step II: Add references for angular, material, jquery etc.

This step can be skipped in case you need to refer all required libraries from CDN. But I never recommend this way, rather download the latest files to Site assets library. It also reduces extra burden on your site to download these library each time from CDN.

  1. Navigate to the Site assets library.
  2. Create a folder called “CustomFiles”.
  3. Create another folder “AngularJS”.
  4. Download files angular.min.js, angular-animate-min.js, angular-aria.min.js, angular-material.min.css, angular-material.min.js, angular-messages.min.js, jquery-3.3.1.min.js
  5. Upload these files to AngularJs folder.   

Step III: Create angularJS app files

  1. Create two files named as: dialog.tmpl.html and dialogApp.js
  2. Copy following code to dialog.tmpl.html file: dialog_tmpl_html
  3. Copy following code to dialogApp.js: dialogapp_js
  4. Now change the <Site URL> with the url of your site.

These two files are required for angularJS to initialize and configure to show dialog box. The html file can be used to modify contents of dialog box.

Step IV: Add content editor webpart on homepage.

  1. Navigate to the page where you need to show pop up
  2. Edit this page and click on add webpart under any zone
  3. Under “Media and content” find “Content Editor” web part. and add it.
  4. Now Edit this web part and under ribbon find “Format text” tab and “Edit Source” option under it.
  5. Now past following code here:

http://SiteURL/SiteAssets/customfiles/angularjs/angular.min.js

http://SiteURL/SiteAssets/customfiles/angularjs/angular-animate.min.js

http://SiteURL/SiteAssets/customfiles/angularjs/angular-aria.min.js

http://SiteURL/SiteAssets/customfiles/angularjs/angular-messages.min.js

http://SiteURL/SiteAssets/customfiles/angularjs/angular-material.min.js

http://SiteURL/SiteAssets/customfiles/dialogApp.js
http://SiteURL/SiteAssets/customfiles/angularjs/jquery-3.3.1.min.js
<link href=”<SiteURL>/SiteAssets/customfiles/angularjs/angular-material.min.css” rel=”stylesheet”/>

​​​​​​​

</div>

That is it. Just save your page and Publish it.

Step V: Test your pop up.

Now log on with separate users on the home page and check if there is entry created under “FirstTimeUsers” list.

Let me explain here a little about the ajax calls here. The code under dialogApp.js files first get the information of the logged on user. Get user information SharePoint using REST Api. Then using REST api, it tries to find out its entry under “FirstTimeUsers” list. Here is the rest call:

/_api/web/lists/getByTitle(‘FirstTimeUsers’)/items?$select=User/EMail&$expand=User&$filter=User/EMail eq ‘<email_of_user>’

In case, it found any entry popup is not shown to user. But if it has found any entry then pop up is shown and on close event of the pop up another rest query will insert entry to the FirstTimeUsers List.

That is all about it. Don’t forget to hit like and kindly rate this article.

Happy SharePointing !!!

 

Get user information SharePoint using REST Api


Hi,

While working on a requirement, I encountered a scenario where I need to show welcome pop up to the first time users. First time user, SharePoint does not provide any api or any solution which gives information about users who logged on first time on your web site. I have documented the whole solution on some other post(Add welcome pop up for first time users of your site using AngularJs Material) But this post I only want to scope it to retrieve information of logged on user. Information mean current user’s accountId, First name, Last name, Email and other required details.

I am only talking about client side code here i.e. using REST api or SP default APIs. Below are the various ways to get the property of current user who is logged on to SP site. There are many ways to achieve this requirement but I prefer to use SP.UserProfiles.PeopleManager Api to get it. It gives us vast option to retrieve any user information. Here are some details of getting various details:

  1. Get all properties of current user:

    http://siteurl/_api/SP.UserProfiles.PeopleManager/GetMyProperties

  2. Get single property of current user:

    http://siteurl/_api/SP.UserProfiles.PeopleManager/GetMyProperties/PictureUrl

    OR

    http://siteurl/_api/SP.UserProfiles.PeopleManager/GetMyProperties?$select=PictureUrl

  3. Get Multiple Properties for the current user:

    http://siteurl/_api/SP.UserProfiles.PeopleManager/GetMyProperties?$select=PictureUrl,AccountName

  4. Get all properties of Specific User:
    For Office 365/SharePoint Online:

    http://siteurl/_api/SP.UserProfiles.PeopleManager/GetPropertiesFor(accountName=@v)?@v=’i:0%23.f|membership|mohit.vashishtha@siteurl.onmicrosoft.com’

    For SharePoint 2013 On-Premise:

    http://siteurl/_api/SP.UserProfiles.PeopleManager/GetPropertiesFor(accountName=@v)?@v=’domain\username’

  5. Get Specific UserProfile Property of Specific User:
    For Office 365/SharePoint Online:

    http://siteurl/_api/SP.UserProfiles.PeopleManager/GetUserProfilePropertyFor(accountName=@v,propertyName=’LastName&#8217;)?@v=’i:0%23.f|membership|mohit.vashishtha@siteurl.onmicrosoft.com’

    For SharePoint 2013 On-Premise:

    http://siteurl/_api/SP.UserProfiles.PeopleManager/GetPropertiesFor(accountName=@v)?@v=’domain\username’

NOTE: I had issues with getting the specific property for a user on #5. This worked fine though:

http://siteUrl/_api/SP.UserProfiles.PeopleManager/GetPropertiesFor(accountName=@v)?@v=’domain\mohit.vashishtha’&$select=DisplayName,AccountName,PictureUrl

Here are some details about user properties:

List of User Properties (Use the GetPropertiesFor function for these):

  • AccountName
  • DirectReports
  • DisplayName
  • Email
  • ExtendedManagers
  • ExtendedReports
  • IsFollowed
  • LatestPost
  • Peers
  • PersonalUrl
  • PictureUrl
  • Title
  • UserProfileProperties
  • UserUrl

List of User Profile Properties (Use the GetUserProfilePropertyFor function for these):

  • AboutMe
  • SPS-LastKeywordAdded
  • AccountName
  • SPS-Locale
  • ADGuid
  • SPS-Location
  • Assistant
  • SPS-MasterAccountName
  • CellPhone
  • SPS-MemberOf
  • Department
  • SPS-MUILanguages
  • EduExternalSyncState
  • SPS-MySiteUpgrade
  • EduOAuthTokenProviders
  • SPS-O15FirstRunExperience
  • EduPersonalSiteState
  • SPS-ObjectExists
  • EduUserRole
  • SPS-OWAUrl
  • Fax
  • SPS-PastProjects
  • FirstName
  • SPS-Peers
  • HomePhone
  • SPS-PersonalSiteCapabilities
  • LastName
  • SPS-PersonalSiteInstantiationState
  • Manager
  • SPS-PhoneticDisplayName
  • Office
  • SPS-PhoneticFirstName
  • PersonalSpace
  • SPS-PhoneticLastName
  • PictureURL
  • SPS-PrivacyActivity
  • PreferredName
  • SPS-PrivacyPeople
  • PublicSiteRedirect
  • SPS-ProxyAddresses
  • QuickLinks
  • SPS-RegionalSettings-FollowWeb
  • SID
  • SPS-RegionalSettings-Initialized
  • SISUserId
  • SPS-ResourceAccountName
  • SPS-AdjustHijriDays
  • SPS-ResourceSID
  • SPS-AltCalendarType
  • SPS-Responsibility
  • SPS-Birthday
  • SPS-SavedAccountName
  • SPS-CalendarType
  • SPS-SavedSID
  • SPS-ClaimID
  • SPS-School
  • SPS-ClaimProviderID
  • SPS-ShowWeeks
  • SPS-ClaimProviderType
  • SPS-SipAddress
  • SPS-ContentLanguages
  • SPS-Skills
  • SPS-DataSource
  • SPS-SourceObjectDN
  • SPS-Department
  • SPS-StatusNotes
  • SPS-DisplayOrder
  • SPS-Time24
  • SPS-DistinguishedName
  • SPS-TimeZone
  • SPS-DontSuggestList
  • SPS-UserPrincipalName
  • SPS-Dotted-line
  • SPS-WorkDayEndHour
  • SPS-EmailOptin
  • SPS-WorkDayStartHour
  • SPS-FeedIdentifier
  • SPS-WorkDays
  • SPS-FirstDayOfWeek
  • Title
  • SPS-FirstWeekOfYear
  • UserName
  • SPS-HashTags
  • UserProfile_GUID
  • SPS-HireDate
  • WebSite
  • SPS-Interests
  • WorkEmail
  • SPS-JobTitle
  • WorkPhone
  • SPS-LastColleagueAdded

Happy SharePointing !!!

Reassign a workflow task – Task update was not accepted. To edit a task associated with a workflow task process, you must be the person to whom the task is currently assigned.


Hi guys,

Recently one of my client has faced this issue while reassigning a task of default Approval workflow. Here is the screen shot:

      

SharePoint by default only allows the assignee to re-assign the task. If you try to re-assign a task that is not assigned to you, you get the following message:

Task update was not accepted. To edit a task associated with a workflow task process, you must be the person to whom the task is currently assigned.

Solution

To overwrite this behaviour:

  1. Open SharePoint Designer
  2. Open the Workflow you wish to modify.
  3. On the step where you start the workflow task ‘Start <workflow task name> process on Current Item with…’, right click on the task name.
  4. Select Properties and look for the attribute TaskProcessOwner.
  5. Click on the ‘‘ button to select a group or specific user.
  6. You may wish to create a SharePoint group specifically for this purpose. All members of this group will have permissions to re-assign tasks that are assigned to other people.

Hope this post help you to fix this error.

Happy SharePointing.

SharePoint Online/2013 Replace no results default text ‘Nothing here matches your search’ from search results web part


 

As we all aware, SharePoint search have great potential to provide very powerful search solution. Couple of new webparts are added in SharePoint 2013, like Content Search web part for which I should use rather a word “Smart” search web part. With a new rendering mechanism, content search webpart becomes more and more simple to edit and customize. That mechanism is called “Display Templates” and these are based upon simple Json to HTML templates.

I recently has faced a project scenario, where I was asked to replace the part of search result web part and I provided a solution by updating search display template.

Requirement:  When we add a search result web part on any result page along with a search text box web part to enter search keywords. Search results will be displayed in web part if keyword matches any text. When we add both these web parts on page and before entering the search term also the results web part show  “Nothing here matches your search” (as shown in below image), which my users want to modify based on their content and want to add some useful links into it.

Blog1

 

Solution:

Initially, I thought that this may be easily updated using some web part property, but after researching about it, I found that there are html/json files called, display templates, which are responsible for rendering this text. Let me explain how to find them and which Display Template we need to customize in order to achieve our target.

All kind of Display Templates are stored at the one location under master page gallery. Here are the steps to reach out to the html file.

  1. Open the site collection.
  2. Navigate to Site Settings.
  3. Under Web Designer Galleries click on Master pages and page layoutsBlog2
  4. Now click on the folder Display Templates and then Search.     Blog3
  5. Under the search folder you will find html and .Js files present.
  6. We are more intereste d in ‘Control_SearchResults.html’. Make sure you click in html file not JS file with same name.

If you are not familiar with this structure then you must be thinking that “Why JS and HTML files with two names?”

In brief, actually display templates are JS files only but just to the sake of simplicity MS has provided HTML so that it is easier to modify/edit display templates. There is out of box event receiver attached to this list when there is any modification detected in HTML file, a new version of JS will be generated by the event receiver. Display Templates are actually split into two different files, the Control and the Item.

Control Display Template

This is the part of your design that does not get repeated as each items gets loaded in the Search Results. It’s the container around and where you refer to any custom CSS or JS files you may want to use.

Put simply, it’s the box where search results will be loaded.

Item Display Template

This is where you design how each item will look like and which managed properties from the result item will be used and where on the design. If I take my example above, that’s all in the Item Display Template. The size of the rectangle, where the Title goes and where the Description goes as well as the animation itself.

Search Results web part of SharePoint uses ‘Control_SearchResults.html’ display template which is available under Master Page Library –> Display Templates –> Search.

Now lets start actual modification of the template:

  1. Download a copy of ‘Control_SearchResults.html’. Click Control_SearchResults.html template file and Download a Copyblog5
  2. Rename the downloaded file as Control_SearchResults_Custom.html. Open the control template file in any of your preferred editors such as SharePoint Designer and customize the file, as per our need.blog6
  3. Change the Title in this HTML file, this title will be available for selection in web part properties.
  4. Now we want to get the search text entered in to search box web part, for that we will use ctx object as following ctx.DataProvider.get_currentQueryState().k
  5. Search if(ctx.ClientControl.get_shouldShowNoResultMessage()){    line in HTML file (as shown in below image).
    Search_Result_SP_2013_Display_Template_1
  6. Find the unordered list just below that code and modify it according to your need.
  7. For example if you don’t want to show any message until user enters some keyword, replace if statement line with
    var currentQueryTerm = ctx.DataProvider.get_currentQueryState().k; if(ctx.ClientControl.get_shouldShowNoResultMessage() && currentQueryTerm!=””){
    (As shown in below image)
    Search_Result_SP_2013_Display_Template_2
  8. Save the modified HTML file.
  9. Go to Master Page Library –> Display Templates –> Search and upload new control template.
  10. You will see that respective ‘Control_SearchResults_custom.js’ will be created by SharePoint.
  11. Now go to your page where Search Result web part is added, edit Search results web part. Under Display Templates section select newly uploaded display template.( as shown in below image).Select our custom control display template.

  12. Save the changes and that’s it, you will see the  expected result.

Hope this information is helpful for you to modify display templates.

Happy SharePointing 🙂

 

Angular 5: Intallation and configuration with Angular CLI


Hi Guys,

In this blog, I am sharing how one can easily install angular (version 5.2.0). Angular 6 beta is out till date, which is not yet stable. Most of developers are excited to try one of the most modern and powerful frontend JS framework. Here is the quick guide to install angular 5 with CLI on development environment. I am choosing a stable version of Angular (5.2.0) for installation purpose in this blog.

Lucky, if you are familiar with Angular 2 or 4 and have good experience with it, the process of starting a new Angular 5 project is pretty much the same.

However, if you are new to angular and not having previous experience with Angular, don’t worry — installing Angular 5 is like a breeze. Let’s get started.

Pre-requisites: Here are the list of tools which you require before proceeding.

  1. Visual Studio Code/Visual Studio – Download
  2. Node.js – Download
  3. Node Package Manager(NPM)

To check whether or not you have both of these installed, visiting your commend line(Win + R => cmd) or console and type following commands:

node -v

npm -v

These commands should tell latest versions of Node and NPM installed on your system. For me these two versions are: node version is “v8.9.4” and npm version is “5.6.0”. If either of these commands are unrecognized, visit the downloads section of Nodejs.org and download/run the appropriate installer based on your OS.
Follow through the installation steps with default settings, which will install NPM by default. Once finished, reload your command line / console and retype the above commands — they should now give you version numbers.

NOTE: In case you are working offline, it is hard to get/download packages unless you are connected to internet or some local package manager. In order to install/configure custom local package manager execute following command with change of local URL:

npm config set registry “<URL of package manager URL>”

Installing Angular CLI: 

The Angular CLI makes it easy to create an application that already works, right out of the box. It requires Node 4 or higher and npm 3 or higher. Now if you are successfully installed node and NPM next step is to install Angular CLI.

PS > npm install -g @angular/cli@latest

This command might take some time as it installs all the dependencies related to CLI and packages. Once CLI is installed you can verify and check the version by executing this command:

PS > ng -v

The output screen will look somewhat like this:

My version of CLI is 1.6.6. Great, That’s it. We are ready to start our first angular application. Here is the command to create a base project using CLI:

PS > ng new my-first-angular-proj –style=scss –routing

The style flag is provided in case we want to use SASS compiler for creating CSS, and another flag –routing is used to provide us with the routing scaffolding.

It will take several minutes depending upon internet connection. Once completed it will show following message:

So its all done! Now on the command prompt navigate into the new project folder. To do that, simply type:

PS > cd my-first-angular-proj 

To serve your project in the browser, which is useful for development as it automatically compiles your project and reloads it in the browser, type:

PS > ng server

And that’s it! You have a fresh copy of Angular 5 ready and waiting for you to develop.

Happy Angular Coding 🙂

SQL Server install error Wait on the Database Engine Recovery Handle Failed


Hi Guys,

Last week during the installation of SQL Server standalone instance, I have faced an issue. After installing all the prerequisites and I started installing SQL Server. Though, I did not get any warnings or errors in any of the rules or steps during the SQL Server installation wizard, but I got the below error at the end of the installation:

The following error has occurred:
Wait on the Database Engine recovery handle failed. Check the SQL Server error log for potential causes.

This issue is giving misleading message. Well, I could not able to understand the cause of this error. I followed standard installation guide and completed pre-check before proceeding installation of SQL Server, but I still got this issue. In this blog, I will explain how did I resolved this issue.

After many rounds of troubleshooting I decided to do some research on the web.  This was the first time I got this issue, so I had no clue about how to fix except for reading and analyzing the error log files. Interestingly, I found multiple solutions to fix this issue over the internet. Below are three options which can be used to fix this issue. I will explain the first in this tip and the remaining in future tips.

  1. Fix it by uninstalling SQL Server and then reinstalling
  2. Fix issue by using sa account
  3. Fix using by creating a login post installation and connecting to the instance in single user mode

This error comes about because the account which the user selected on the Server Configuration page during installation is somehow not able to bring the SQL Server database engine services online. Either it lacks privileges or it is corrupted. During installation of the database engine services, SQL Server tries to bring online the database services as an internal process, but due to the startup account either being corrupt or not having the appropriate privileges it fails to do so and ultimately the installation fails. There might be a possibility that someone had tried to install SQL Server previously on this machine, but failed to do so and they did not clean the machine properly during the uninstallation.

Wait on the Database Engine recovery handle failed.  Check the SQL Server error log for potential causes.

When you click on OK button after reading and analyzing the error, the below screen will appear confirming that a few of the features failed to install.

SQL Server features failed to install

I decided to review the error log file to find out more about this error, but I did not get much from the error log file as shown in the below screen shot.

SQL Server Error Log File

To move forward, I will uninstall this SQL Server instance and then reinstall it again with some minor changes. Let’s go ahead and uninstall it using the “Add/Remove Program” feature in Windows. If you are not able to remove SQL Server instance then you will need to do a manual uninstallation to clean the machine. Make sure to remove all SQL Server related files from the system as well as the registry. Before removing anything from the registry create a backup of the registry first. I uninstalled this instance successfully and proceeded with the next step.

Restart your machine after successful removal of the SQL Server instance. Now go ahead and launch the SQL Server setup again to start the SQL Server installation.

Fill all the required details and click on Next buttons to proceed until the “Server Configuration” page. You can see below that the SQL Server database engine and SQL Server Agent service account is configured to run with NT AUTHORITY/NETWORK SERVICE and NT AUTHORITY/NETWORK SERVICE. Our last installation failed due to this, so here I will change these service accounts to use the local System account to run the installation.

Note: The “Network Service” is a built-in local account used by the service control manager.This account is not recognized by the security subsystem, hence you cannot specify its name in a call to the Lookup for Account Name.

To lookup  “Network Service” account name, in location select “local machine” instead of Entire Directory.

We can change both service accounts to local System. On the SQL Server Database Engine and Agent service, click the drop down option to select user NT Authority\NETWORK SERVICE which is also known as the local system account.

Now click on the Next button and proceed with the installation by filling in the required details and clicking on the Next buttons until the end of the setup. Installation should now proceed and finish with a green status for all features as you can see in the below screenshot.

SQL Server Successful Installation

Now you can check the SQL Server services to make sure they are running. You can also connect to the database instance and run some queries to check that things are working properly.

Hope this help you.

Thanks

AngularJS: Export Json object to Excel using AlaSQL


Hello,

I have spent significant time developing AngularJS and Angular 2 applications. But this requirement is quite new to me. Well, user wants to export to excel feature on one of our application page where we are using filtered data based upon some parameters. The design decision was on me whether to choose server side function to convert Json object in to CSV format and then export it to excel.

But I decided to choose another approach, not to involve server in exporting a Json data. I was not aware about ALASQL but later explored and found its very useful for me to implement this solution. Here I am explaining how to implement it.

What you need to import :

Just an intro about these two libraries:

AlaSQL is an open source SQL database for Javascript with a strong focus on query speed and data source flexibility for both relational data and schemaless data. It works in your browser, Node.js, and Cordova.

This library is designed for:

  • Fast in-memory SQL data processing for BI and ERP applications on fat clients
  • Easy ETL and options for persistency by data import / manipulation / export of several formats
  • All major browsers, Node.js, and mobile applications

Where js-xlsx is used to support for AngularJS export library. Both of these two has support to NG2 you can find more details about it here.

There are two ways to achieve the export:

  1. From Json object
    • alasql(‘SELECT * INTO XLS(“test.xls”,?) FROM ?’,[customStyle,$scope.items]);
  2. From html(like table)
    • alasql(‘SELECT * INTO XLSX(“myinquires.xlsx”,{headers:true})  FROM HTML(“#HtmltagID”,{headers:true})’);

It is very easy to implement. Please refer to my plnkr code to see the examples.

http://plnkr.co/edit/2UKA8yPl9Uiarr2uSwEd?p=preview

Hope this blog is beneficial for you.

 

AngularJS: Bind UI Select selection sequentially


Hello,

I felt lucky to work with angularJS with the integration with SharePoint(as backend) in my recent project. There was a requirement to have two drop-downs on a single page application where on selection of one; other drop-down value will be automatically filtered.  I am going to share with you guys that how I have implemented.  I understand that this may not be Ideal way of doing it but I am sure that it is quickest solution that I did in code to achieve this requirement.

HTML: The below html will generate two dropdowns and populate with country and states data.

<h3>Countries</h3>
<ui-select ng-model="ctrl.country.selected" name="country" theme="bootstrap" title="Select a Country" >
<ui-select-match placeholder="Select or search a country in the list...">{{$select.selected.name}}</ui-select-match>
<ui-select-choices repeat="country in ctrl.countries | filter: $select.search">
<span ng-bind-html="country.name | highlight: $select.search"></span>
<small ng-bind-html="country.code | highlight: $select.search"></small>
</ui-select-choices>
</ui-select>
<h3>States</h3>
<ui-select ng-model="ctrl.state.selected" name="state" theme="bootstrap" title="Select a state">
<ui-select-match placeholder="Select or search a state in the list...">{{$select.selected.name}}</ui-select-match>
<ui-select-choices repeat="s in ctrl.states | countryFilter: { concode: ctrl.country.selected.code }">
<span ng-bind-html="s.name | highlight: $select.search"></span>
<small ng-bind-html="s.concode | highlight: $select.search"></small>
</ui-select-choices>
<ui-select-no-choice>
<span ng-if="ctrl.country.selected.name">&nbsp; No state found for '{{ctrl.country.selected.name}}' country !</span>
<span ng-if="!ctrl.country.selected.name">&nbsp; Please select country !</span>
</ui-select-no-choice>
</ui-select>

Custom Filter:

If you have notice in abouve html code, I have created a custom search filter which search the states dropdown data based on the countyr selected using first dropdown. Here is the code for the filter:

app.filter("countryFilter", function () {
return function (items, props) {
var out = [];
if (angular.isArray(items)) {
var keys = Object.keys(props);
items.forEach(function (item) {
var itemMatches = false;
for (var i = 0; i < keys.length; i++) {
var prop = keys[i];
var text = props[prop].toLowerCase();
//if (item[prop].toString().toLowerCase().indexOf(text) !== -1) {
if (item[prop].toString().toLowerCase() === text) {
itemMatches = true;
break;
}
}
if (itemMatches) {
out.push(item);
}
});
} else {
// Let the output be the input untouched
out = items;
}
return out;
};
});

Demo: Plunker Demo

Output:

untitled

Hope this post will help you creating synchronous drop down using UI-Select.

Happy Coding !!

Not able to view result while building Search Query


Hello SharePointers ;),

Here is another quick finding which I just thought should be shared to save someone precious time. If you are dealing with SharePoint 2013 search and Result sources, you must try to test the query template before saving it. If you are not able to see any results instead just a red error saying below text don’t get scared I have quick solution for you.

“The Search display templates are not present on this site collection. To add them, you need to activate the “Search Server Web Parts and Templates” feature on the Site Collection Features page.

Display Error: The display template had an error. You can correct it by fixing the template or by changing the display template used in either the Web Part properties or Result Types.

Template ‘~sitecollection/_Catalogs/masterpage/DisplayTemplates/System/Control_QueryBuilderPreview.js’ not found or has sytax errors. (Load Template: ) ”

Search_Error

You must get frustrated because your search is properly configured, its crawling the data and you are able to see results while searching.  After looking at what was missing I found that in fact there was a feature missing on the Central Administration site collection. The feature is called Search WebParts.

But its not so quick that you just navigate to Site collection feature and activate it. As this feature is present at central admin site collection level so it requires extra privileges to activate it. To fix the problem, simply run the following command in an elevated SharePoint Management Shell:

Enable-SPFeature SearchWebParts -url http://<central admin url>

Bingo!! Just, re-open the “build your query” page, and everything should work properly!

Search_Error

Hope that post was able to help you. Please press like button it that saved your time.

Happy SharePointing 🙂